diff --git a/crates/ide-core/src/remote_settings.rs b/crates/ide-core/src/remote_settings.rs index 62442a36f..3d1fc5276 100644 --- a/crates/ide-core/src/remote_settings.rs +++ b/crates/ide-core/src/remote_settings.rs @@ -191,6 +191,19 @@ pub struct RunTarget { pub image_user: bool, } +/// A plugin-owned argv wrapper for project runs (API 1.4). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct PluginRunTarget { + pub id: String, + pub name: String, + pub program: String, + pub args: Vec, + pub workdir_args: Vec, + pub container_root: Option, + pub commands: Vec<(String, Vec)>, +} + #[cfg(test)] mod deployment_tests { use super::*; diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 8feb6a512..fbfceea4b 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -767,6 +767,8 @@ impl Default for PythonSettings { pub struct PhpSettings { /// `php` CLI executable; empty = the one on `PATH`. pub interpreter: String, + /// Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local. + pub run_target: String, /// PHP version the language server checks the code against (`7.4`); empty = from /// `composer.json` (`config.platform.php`, else the lowest version `require.php` allows). pub language_level: String, @@ -794,6 +796,8 @@ pub struct RubySettings { pub struct NodeSettings { /// `node` executable; empty = the one on `PATH`. pub interpreter: String, + /// Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local. + pub run_target: String, /// `npm` | `pnpm` | `yarn`; empty = detect from the lock file / `packageManager`. pub package_manager: String, } diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 5549be1af..293775a55 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -272,6 +272,8 @@ impl Default for PythonDebuggerSettings { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct RunSettings { + /// Target for configurations without an explicit target. Empty = local. + pub default_target: String, pub confirm_rerun: bool, /// Ask before closing a Run tab whose process is still running. pub confirm_terminate: bool, @@ -282,7 +284,13 @@ pub struct RunSettings { impl Default for RunSettings { fn default() -> Self { - Self { confirm_rerun: true, confirm_terminate: true, show_on_start: true, termination_timeout_ms: 3000 } + Self { + default_target: String::new(), + confirm_rerun: true, + confirm_terminate: true, + show_on_start: true, + termination_timeout_ms: 3000, + } } } diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 01bebbe96..4ba1300b2 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -249,6 +249,11 @@ impl Host { self.cancel_request(request); } let project = self.projects.write().remove(window)?; + if self.windows_for_root(&project.root).is_empty() + && let Some(plugins) = self.plugin_host() + { + plugins.withdraw_project_run_targets(&project.root); + } project.files_events_active.store(false, std::sync::atomic::Ordering::Release); project.plugin_diagnostics.close(); if let Some(plugins) = plugins::editor_plugin_host() { diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index b65f5382c..e04d3c0b7 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -218,6 +218,9 @@ async fn start_inner( ) -> IdeResult { host.require_trust(window)?; let project = host.project(window)?; + if config.extras.target.is_none() { + config.extras.target = ide_sdk::apply::run_target(&config, &project.settings.effective()).map(str::to_owned); + } if config.detected && config.id.starts_with(ide_run::EXTERNAL_PREFIX) && let Some(plugins) = host.plugin_host() @@ -250,6 +253,25 @@ async fn start_inner( } if let Some(id) = config.extras.target.as_deref().filter(|t| !t.is_empty()) { let settings = project.settings.effective(); + if id.starts_with("plugin-target:") { + let plugins = + host.plugin_host().ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?; + let root = project.root.clone(); + let id = id.to_owned(); + let config = host.blocking(move || plugins.prepare_run_target(&root, &id, &config)).await?; + project.require_trust()?; + return host.processes.start( + &project.root, + &config, + &StartOptions { + encoding: Some(settings.console.encoding).filter(|e| !e.trim().is_empty()), + python_paths: Vec::new(), + ruby_reporter: None, + }, + sink, + Box::new(move |c| on_output(c)), + ); + } let target = ide_remote::service::run_target(&settings, id)?; if target.kind != RunTargetKind::Ssh { // A local run of the docker CLI: the command is resolved in the container, and diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 5d34cf46a..d8c33f36b 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -494,6 +494,7 @@ pub(super) struct Shared { pub(super) prompts_blocked: Mutex>, pub(super) next_prompt: AtomicU64, pub(super) run_configurations: super::run_detectors::DynamicConfigurations, + pub(super) run_targets: Mutex, pub(super) operations: Mutex>, pub(super) content_tabs: Mutex>, pub(super) content_requests: Mutex, @@ -560,6 +561,7 @@ impl Shared { prompts_blocked: Mutex::default(), next_prompt: AtomicU64::new(1), run_configurations: Arc::default(), + run_targets: Mutex::default(), operations: Mutex::default(), content_tabs: Mutex::default(), content_requests: Mutex::default(), @@ -739,6 +741,7 @@ impl Shared { /// Withdraws a plugin's run-time state (it stopped or failed). Its /// subscriptions go only with `subscriptions`, as they survive restarts. pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) { + self.withdraw_run_targets(Some(plugin), None); self.run_configurations.write().retain(|(p, _), _| p != plugin); self.operations.lock().retain(|_, op| op.plugin != plugin); self.content_tabs.lock().retain(|(p, _, _), _| p != plugin); @@ -994,7 +997,7 @@ impl PluginApi { self.approved_program_in_project(program, None) } - fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result { + pub(super) fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result { if let Some(pin) = root.and_then(|root| { self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned() }) { @@ -1248,6 +1251,13 @@ fn failed(e: impl std::fmt::Display) -> HostError { } impl HostApi for PluginApi { + fn register_run_target(&self, root: &Path, target: ide_plugin::PluginRunTarget) -> Result<(), HostError> { + self.register_target(root, target) + } + fn unregister_run_target(&self, root: &Path, id: &str) { + self.unregister_target(root, id); + } + fn start_run( &self, client: &str, diff --git a/crates/ide-host/src/plugins/execution.rs b/crates/ide-host/src/plugins/execution.rs index 9e617ec83..95328befe 100644 --- a/crates/ide-host/src/plugins/execution.rs +++ b/crates/ide-host/src/plugins/execution.rs @@ -464,6 +464,9 @@ impl PluginHost { if owned.debug_adapter.is_none() { return Err(IdeError::invalid("this configuration has no debugger")); } + if config.extras.target.is_none() { + config.extras.target = owned.extras.target.clone(); + } if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) { return Err(IdeError::invalid("debugging this target is not supported")); } diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index 677aeff4e..4cb624f26 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -40,6 +40,7 @@ mod providers; pub mod remote; pub mod remote_host; mod run_detectors; +pub mod run_targets; mod semantic_tokens; mod theme; mod types; @@ -661,6 +662,7 @@ impl PluginHost { /// Unloads the project plugins of `root` (the project became untrusted or closed). pub fn restrict_project(&self, root: &Path) { + self.shared.withdraw_run_targets(None, Some(root)); let _guard = self.lifecycle.lock(); let ids: Vec<_> = self .plugins diff --git a/crates/ide-host/src/plugins/remote_host.rs b/crates/ide-host/src/plugins/remote_host.rs index 2f0fffd05..7d5a5df11 100644 --- a/crates/ide-host/src/plugins/remote_host.rs +++ b/crates/ide-host/src/plugins/remote_host.rs @@ -131,7 +131,8 @@ pub fn package_digest(dir: &Path, files: &[PathBuf]) -> IdeResult { pub fn forwarded(event: &PluginEvent) -> bool { matches!( event, - PluginEvent::WindowRequest { .. } + PluginEvent::RunTargetsChanged + | PluginEvent::WindowRequest { .. } | PluginEvent::ContentTabReply { .. } | PluginEvent::DecorationsChanged { .. } | PluginEvent::EditorOpen { .. } @@ -720,6 +721,21 @@ impl RemotePlugins { let h = h.clone(); async move { super::index_ops::plugin_endpoints(&c.host, alive(&h)?, &c.window, c.arg("pluginId")?).await } }); + let h = host.clone(); + d.add("plugin_run_targets", move |c| { + let h = h.clone(); + async move { super::run_targets::list(&c.host, alive(&h)?.as_ref(), &c.window) } + }); + let h = host.clone(); + d.add("plugin_answer_run_target", move |c| { + let h = h.clone(); + async move { + let plugins = alive(&h)?; + let id: String = c.arg("id")?; + let use_target = c.arg("useTarget")?; + blocking(move || super::run_targets::answer(&c.host, &plugins, &c.window, &id, use_target)).await + } + }); d.add("plugin_line_markers", |c| async move { crate::ops::lsp::plugin_line_markers(&c.host, &c.window, c.arg("doc")?).await }); diff --git a/crates/ide-host/src/plugins/run_targets.rs b/crates/ide-host/src/plugins/run_targets.rs new file mode 100644 index 000000000..8b2b01325 --- /dev/null +++ b/crates/ide-host/src/plugins/run_targets.rs @@ -0,0 +1,150 @@ +//! Project-owned registrations, retained across idle instance reclamation. +use super::api::{PluginApi, Shared}; +use super::{PluginEvent, PluginHost}; +use ide_core::{IdeError, IdeResult}; +use ide_plugin::{HostError, PluginRunTarget}; +use std::path::{Path, PathBuf}; + +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, specta::Type)] +#[serde(rename_all = "camelCase")] +pub struct RegisteredRunTarget { + /// Opaque selector id, namespaced by the host. + pub id: String, + pub plugin_id: String, + pub plugin_name: String, + pub target: PluginRunTarget, + pub prompt: bool, +} + +pub(super) type Targets = std::collections::BTreeMap<(PathBuf, String), RegisteredRunTarget>; +fn selector(plugin: &str, id: &str) -> String { + format!("plugin-target:{}:{plugin}{id}", plugin.len()) +} +impl Shared { + fn target_answer_file(&self, root: &Path, id: &str) -> PathBuf { + let key = format!("{}\0{id}", root.display()); + self.data_dir.join(".run-target-answers").join(blake3::hash(key.as_bytes()).to_hex().as_str()) + } + pub(super) fn withdraw_run_targets(&self, plugin: Option<&str>, root: Option<&Path>) { + let mut targets = self.run_targets.lock(); + let before = targets.len(); + targets.retain(|(r, _), t| !(plugin.is_none_or(|p| p == t.plugin_id) && root.is_none_or(|path| path == r))); + if before != targets.len() { + drop(targets); + self.sink.emit(None, PluginEvent::RunTargetsChanged); + } + } +} +impl PluginApi { + pub(super) fn register_target(&self, root: &Path, target: PluginRunTarget) -> Result<(), HostError> { + ide_remote::plugin_target::validate(&target).map_err(|e| HostError::Invalid(e.to_string()))?; + let workspace = self.shared.workspace().ok_or(HostError::Cancelled)?; + if !workspace.projects().iter().any(|r| r == root) { + return Err(HostError::NotFound("project is not open".into())); + } + if !workspace.trusted(root) { + return Err(HostError::Denied("project is not trusted".into())); + } + self.approved_program_in_project(&target.program, Some(root))?; + let blocked = self.shared.prompts_blocked.lock(); + if blocked.contains(self.pkg.id()) { + return Err(HostError::Cancelled); + } + let id = selector(self.pkg.id(), &target.id); + let mut targets = self.shared.run_targets.lock(); + if !targets.contains_key(&(root.into(), id.clone())) + && targets.iter().filter(|((r, _), t)| r == root && t.plugin_id == self.pkg.id()).count() >= 32 + { + return Err(HostError::Invalid("at most 32 targets per plugin and project".into())); + } + let prompt = !self.shared.target_answer_file(root, &id).exists(); + targets.insert( + (root.into(), id.clone()), + RegisteredRunTarget { + id, + plugin_id: self.pkg.id().into(), + plugin_name: self.pkg.manifest.name.clone(), + target, + prompt, + }, + ); + drop(targets); + drop(blocked); + self.shared.sink.emit(None, PluginEvent::RunTargetsChanged); + Ok(()) + } + pub(super) fn unregister_target(&self, root: &Path, id: &str) { + if self.shared.run_targets.lock().remove(&(root.into(), selector(self.pkg.id(), id))).is_some() { + self.shared.sink.emit(None, PluginEvent::RunTargetsChanged); + } + } +} +impl PluginHost { + /// Drops registrations when their project closes or loses trust. + pub fn withdraw_project_run_targets(&self, root: &Path) { + self.shared.withdraw_run_targets(None, Some(root)); + } + pub fn run_targets(&self, root: &Path) -> Vec { + self.shared.run_targets.lock().iter().filter(|((r, _), _)| r == root).map(|(_, t)| t.clone()).collect() + } + pub fn prepare_run_target( + &self, + root: &Path, + id: &str, + config: &ide_run::RunConfig, + ) -> IdeResult { + let target = self + .shared + .run_targets + .lock() + .get(&(root.into(), id.into())) + .cloned() + .ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?; + let program = self.program_for_project(&target.plugin_id, &target.target.program, Some(root))?; + ide_remote::plugin_target::prepare(root, &target.target, &program, config) + } +} + +pub fn list(host: &crate::Host, plugins: &PluginHost, window: &str) -> IdeResult> { + Ok(plugins.run_targets(&host.project(window)?.root)) +} + +/// The first answer wins across the project's windows. Only Use changes settings. +pub fn answer( + host: &crate::Host, + plugins: &PluginHost, + window: &str, + id: &str, + use_target: bool, +) -> IdeResult { + host.require_trust(window)?; + let project = host.project(window)?; + let mut targets = plugins.shared.run_targets.lock(); + let target = targets + .get_mut(&(project.root.clone(), id.into())) + .ok_or_else(|| IdeError::not_found("plugin run target is no longer available"))?; + let file = plugins.shared.target_answer_file(&project.root, id); + if file.exists() { + target.prompt = false; + return Ok(project.settings.effective()); + } + if use_target { + plugins.program_for_project(&target.plugin_id, &target.target.program, Some(&project.root))?; + let scope = ide_workspace::SettingsScope::Project; + for key in ["run.defaultTarget", "languages.php.runTarget", "languages.node.runTarget"] { + project.settings.set(scope, key, serde_json::json!(id))?; + for window in host.windows_for_root(&project.root) { + if let Ok(open) = host.project(&window) { + open.settings.reload(); + open.sink.emit(ide_core::IdeEvent::SettingsChanged { key: key.into() }); + } + } + } + } + std::fs::create_dir_all(file.parent().unwrap())?; + std::fs::write(file, if use_target { "use" } else { "not-now" })?; + target.prompt = false; + drop(targets); + plugins.shared.sink.emit(None, PluginEvent::RunTargetsChanged); + Ok(project.settings.effective()) +} diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index 6fde91f3b..518688f1c 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -165,6 +165,8 @@ pub struct PluginUpdate { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(tag = "type", rename_all = "camelCase")] pub enum PluginEvent { + /// Project target registrations or remembered prompt answers changed. + RunTargetsChanged, /// A window-owned operation; an empty request id queues an asynchronous run. #[serde(rename_all = "camelCase")] WindowRequest { plugin_id: String, request_id: String, request: WindowRequest }, diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index d052e0804..603dbc77d 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -146,6 +146,9 @@ impl crate::Host { phpstan.interrupt(); } if !trusted { + if let Some(plugins) = self.plugin_host() { + plugins.withdraw_project_run_targets(&project.root); + } project.lsp.set_execution_allowed(false); } project.repos(); diff --git a/crates/ide-host/tests/plugin_workbench.rs b/crates/ide-host/tests/plugin_workbench.rs index 2862e3e62..08e790f19 100644 --- a/crates/ide-host/tests/plugin_workbench.rs +++ b/crates/ide-host/tests/plugin_workbench.rs @@ -229,3 +229,126 @@ async fn plugin_debug_uses_the_source_language_and_revalidates_its_owned_program plugins.set_capability("execution", "process:execution-tool", false).unwrap(); assert!(plugins.prepare_debug_run("main", config).is_err()); } + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn plugin_run_targets_register_prompt_route_revalidate_and_withdraw() { + use ide_host::plugins::{Consent, PluginEvent, PluginHost, run_targets}; + use ide_plugin::{Invocation, Limits}; + use std::os::unix::fs::PermissionsExt; + let f = Harness::new(); + f.host.set_project_trust(&f.root, true, false).await.unwrap(); + let plugins = Arc::new( + PluginHost::new( + f._tmp.path().join("plugins"), + Arc::new(|_: Option<&str>, _: PluginEvent| {}), + Limits { idle_timeout: Some(std::time::Duration::from_millis(10)), ..Default::default() }, + ) + .unwrap(), + ); + plugins.set_workspace(Some(Arc::new(f.workspace()))); + f.host.set_plugin_host(&plugins); + let package = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/execution"); + plugins.install_from_dir(&package, &Consent::all()).unwrap(); + let tool = f._tmp.path().join("wrapper"); + std::fs::write(&tool, "#!/bin/sh\nprintf 'cwd=%s\\n' \"$PWD\"\nprintf '<%s>\\n' \"$@\"\n").unwrap(); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + let invocation = + || Invocation { client: Some("main".into()), workspace_root: Some(f.root.clone()), ..Default::default() }; + assert!(plugins.run_command("execution", "target", None, invocation()).is_err()); + plugins.choose_program("execution", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap(); + plugins.run_command("execution", "target", None, invocation()).unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(30)).await; + plugins.tick_at(std::time::Instant::now()); + assert_eq!(plugins.info_of("execution").unwrap().status, ide_host::plugins::PluginStatus::Inactive); + let targets = run_targets::list(&f.host, &plugins, "main").unwrap(); + assert_eq!(targets.len(), 1); + assert!(targets[0].prompt); + assert!(f.host.project("main").unwrap().settings.effective().run.default_target.is_empty()); + let id = &targets[0].id; + let settings = run_targets::answer(&f.host, &plugins, "main", id, false).unwrap(); + assert!(settings.run.default_target.is_empty()); + // A stale prompt in a second window cannot change an answered selection. + assert!(run_targets::answer(&f.host, &plugins, "second", id, true).unwrap().run.default_target.is_empty()); + plugins.run_command("execution", "untarget", None, invocation()).unwrap(); + assert!(plugins.run_targets(&f.root).is_empty()); + plugins.run_command("execution", "target", None, invocation()).unwrap(); + assert!(!plugins.run_targets(&f.root)[0].prompt); + plugins.run_command("execution", "target", Some("preferred"), invocation()).unwrap(); + let preferred = plugins.run_targets(&f.root).into_iter().find(|t| t.target.id == "preferred").unwrap(); + let settings = run_targets::answer(&f.host, &plugins, "main", &preferred.id, true).unwrap(); + assert_eq!(settings.run.default_target, preferred.id); + assert_eq!(settings.languages.php.run_target, preferred.id); + assert_eq!(settings.languages.node.run_target, preferred.id); + assert_eq!(f.host.project("second").unwrap().settings.effective().run.default_target, preferred.id); + std::fs::write(f.root.join("execution.marker"), "").unwrap(); + std::fs::write(f.root.join("entry.py"), "print('test')\n").unwrap(); + let mut detected = + plugins.run_detection().detect(&f.root).into_iter().find(|c| c.id == "plugin:execution:detected").unwrap(); + detected.args = vec!["entry.py".into()]; + ide_run::save_user_configs(&f.root, &[detected]).unwrap(); + let mut debug = f.workspace().run_configuration("main", "execution", "detected").unwrap(); + debug.extras.target = None; + let error = plugins.prepare_debug_run("main", debug).unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::InvalidInput); + assert!(error.to_string().contains("target")); + assert!(plugins.run_command("execution", "debug", None, invocation()).unwrap_err().to_string().contains("target")); + let output = Arc::new(parking_lot::Mutex::new(String::new())); + let captured = output.clone(); + let config = ide_run::RunConfig { + id: "php-target".into(), + name: "PHP target".into(), + kind: "php".into(), + command: "php".into(), + args: vec!["x.php".into(), "a b; $(touch forbidden)".into()], + cwd: None, + env: Default::default(), + detected: false, + is_test: false, + debug_adapter: None, + allow_parallel: false, + extras: Default::default(), + }; + let run = ide_host::ops::run::start( + &f.host, + "main", + config.clone(), + Arc::new(move |chunk| { + if let ide_run::OutputChunk::Stdout { text } = chunk { + captured.lock().push_str(&text); + } + }), + ) + .await + .unwrap(); + for _ in 0..100 { + if f.host.processes.list().iter().any(|r| r.id == run.id && !r.running) { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + let text = output.lock().clone(); + assert!(text.contains("\n<--cwd=/container>\n\n\n"), "{text}"); + assert!(text.contains(&format!("cwd={}", f.root.display())), "{text}"); + assert!(!f.root.join("forbidden").exists()); + // Pin checks are repeated at launch, not only at registration. + std::fs::write(&tool, "#!/bin/sh\nexit 99\n").unwrap(); + assert!(ide_host::ops::run::start(&f.host, "main", config.clone(), Arc::new(|_| {})).await.is_err()); + plugins.set_capability("execution", "process:execution-tool", false).unwrap(); + assert!(plugins.run_targets(&f.root).is_empty()); + assert!(ide_host::ops::run::start(&f.host, "main", config, Arc::new(|_| {})).await.is_err()); + plugins.choose_program("execution", "process:execution-tool", Some(&f.root), Some(&tool)).unwrap(); + plugins.run_command("execution", "target", None, invocation()).unwrap(); + f.host.set_project_trust(&f.root, false, false).await.unwrap(); + assert!(plugins.run_targets(&f.root).is_empty()); + assert!( + plugins.run_command("execution", "target", None, invocation()).unwrap_err().to_string().contains("trusted") + ); + f.host.set_project_trust(&f.root, true, false).await.unwrap(); + plugins.run_command("execution", "target", None, invocation()).unwrap(); + f.host.close_project_detached("main"); + assert_eq!(plugins.run_targets(&f.root).len(), 1); + f.host.close_project_detached("second"); + assert!(plugins.run_targets(&f.root).is_empty()); + plugins.shutdown(); +} diff --git a/crates/ide-host/tests/remote_plugins.rs b/crates/ide-host/tests/remote_plugins.rs index 1cf8ed0e3..e6b504e03 100644 --- a/crates/ide-host/tests/remote_plugins.rs +++ b/crates/ide-host/tests/remote_plugins.rs @@ -477,7 +477,7 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution let bin = tmp.path().join("bin"); std::fs::create_dir(&bin).unwrap(); let executable = bin.join("execution-tool"); - std::fs::write(&executable, "#!/bin/sh\nread line\nprintf '%s\\n' \"$line\"\n").unwrap(); + std::fs::write(&executable, "#!/bin/sh\nif [ \"$1\" = wrapped ]; then printf '<%s>\\n' \"$@\" > \"$PWD/wrapped.txt\"; exit; fi\nread line\nprintf '%s\\n' \"$line\"\n").unwrap(); std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o755)).unwrap(); let path_var = { let bin = bin.clone(); @@ -521,6 +521,38 @@ async fn api14_stage3_remote_terminal_pins_and_exit_events_stay_on_the_execution invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap(); sync(&peer, &desktop, &[]).await; assert!(sync(&peer, &desktop, &["execution"]).await.failed.is_empty()); + invoke( + &peer, + "plugin_run_command", + json!({"pluginId":"execution", "commandId":"target", "arg":null, "editor":null}), + ) + .await + .unwrap(); + let targets = invoke(&peer, "plugin_run_targets", json!({})).await.unwrap(); + assert_eq!(targets.as_array().unwrap().len(), 1); + assert_eq!(targets[0]["pluginId"], "execution"); + assert!(desktop.run_targets(&project).is_empty()); + let id = targets[0]["id"].as_str().unwrap(); + let settings = invoke(&peer, "plugin_answer_run_target", json!({"id":id, "useTarget":false})).await.unwrap(); + assert_eq!(settings["run"]["defaultTarget"], ""); + let config = json!({"id":"wrapped-php", "name":"Wrapped PHP", "kind":"php", "command":"php", "args":["x.php", "literal ; $(touch bad)"], "env":{}, "detected":false, "isTest":false, "target":id}); + invoke(&peer, "run_start", json!({"config":config, "onOutput":{"$channel":38}})).await.unwrap(); + until("remote wrapped run", 5, || project.join("wrapped.txt").exists()).await; + assert_eq!( + std::fs::read_to_string(project.join("wrapped.txt")).unwrap(), + "\n<--cwd=/container>\n\n\n\n" + ); + assert!(!project.join("bad").exists()); + invoke( + &peer, + "plugin_run_command", + json!({"pluginId":"execution", "commandId":"untarget", "arg":null, "editor":null}), + ) + .await + .unwrap(); + assert_eq!(invoke(&peer, "plugin_run_targets", json!({})).await.unwrap(), json!([])); + client.plugin_events.lock().clear(); + client.events.lock().clear(); let runner = peer.clone(); let run = tokio::spawn(async move { invoke( diff --git a/crates/ide-plugin/src/lib.rs b/crates/ide-plugin/src/lib.rs index 30d01ab93..72775c594 100644 --- a/crates/ide-plugin/src/lib.rs +++ b/crates/ide-plugin/src/lib.rs @@ -26,3 +26,5 @@ pub use wasmtime::component::Component; mod execution; pub use execution::*; + +pub use ide_core::remote_settings::PluginRunTarget; diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 044785d7e..5c662c14a 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -64,6 +64,16 @@ pub const CANCELLED: &str = "was cancelled"; /// which routes notifications and status items to windows and edits to open /// documents. Capabilities are already checked when these are called. pub trait HostApi: Send + Sync { + /// Registers a project-scoped wrapper after validating its process grant and pin. + fn register_run_target(&self, root: &Path, target: crate::PluginRunTarget) -> Result<(), HostError> { + let _ = (root, target); + Err(HostError::Failed("run targets unavailable".into())) + } + /// Withdraws this plugin's target, preserving the user's remembered prompt answer. + fn unregister_run_target(&self, root: &Path, id: &str) { + let _ = (root, id); + } + /// Starts one of this plugin's configurations in a window. fn start_run( &self, diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index b4cb5bdf8..55b0aadea 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -1846,6 +1846,39 @@ impl From for crate::Content } } +impl bindings::openidea::plugin::run_targets::Host for StoreData { + fn register( + &mut self, + project: Resource, + target: bindings::openidea::plugin::run_targets::RunTarget, + ) -> Fallible<()> { + if let Err(e) = self.require(Capability::Process(target.program.clone())) { + return Ok(Err(e)); + } + let root = self.table.get(&project)?.root.clone(); + Ok(self + .host + .register_run_target( + &root, + crate::PluginRunTarget { + id: target.id, + name: target.name, + program: target.program, + args: target.args, + workdir_args: target.workdir_args, + container_root: target.container_root, + commands: target.commands, + }, + ) + .map_err(to_wit)) + } + fn unregister(&mut self, project: Resource, id: String) -> wasmtime::Result<()> { + let root = self.table.get(&project)?.root.clone(); + self.host.unregister_run_target(&root, &id); + Ok(()) + } +} + impl bindings::openidea::plugin::run::Host for StoreData { fn start(&mut self, config: String, args: Vec, debug: bool) -> Fallible { if let Err(e) = self.require_window() { diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index 1b02ea378..70fcc6002 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 76b952c0f..302531a0c 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -fd49e1032cb7f21e8b2e75952cd0c55402a53879be5279c0a4edced2c0a28378 +aca0cf50e9b7e9f66d62705ba040c7caee745f0cf97fe492cb39af86971aed22 diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 762b64d11..30033e299 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 87e5cb37d..52bd8acde 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -31c908f292255eedff07d31e42ac951fcbdaa6ac18780c41680318519cca3eba +f3d07c243ae6e279f49cb4e1bd9fa67117ad4f7ebfb4c22dcfe1510701b56a71 diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index 3d62fd4f9..a7eee1e1d 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index 8c34c9801..f08e5e4c0 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -73f5b3c6d12525aae266f1d8d29d1e626f97d16b2842e9a51367ec51bd0faa16 +6134e5ad5b174fe75ee6ddba9604a30d5d30bd675ffabbaea1ad78831a21609a diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 346aeddfc..10a2228c9 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index d8bc6fb6d..d644317c0 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -958787ffaecf4fe99f4fdc30591d98f4d3d1492208db4a94b226839c1a4ba1fa +9f9b56b7044adac003648ca18d34ceffb58505918f550cf8ad187ac14a8845d7 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index c00b96f21..cd1255687 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index c4f871307..3ab2e473d 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -f9f076f9b4b1670722b4bce2619492600cebae044e4ccf3fa4d66c9c5acb4d40 +ed71c7f1ad8420439f58426f898b41d982ae97653916b1c56590705320dc66b1 diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index 456c306b5..38e6e6081 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index 80398aa5b..991637c08 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -3d09d87137b9e56b980dbfdb9ff04cef680576298f5ead117917ec296bd2bb4d +fc3b498f6f82197db683cd2aa9500593f883f962492ca11f0a6940233ad6c7f0 diff --git a/crates/ide-plugin/tests/fixtures/execution/plugin.toml b/crates/ide-plugin/tests/fixtures/execution/plugin.toml index 1eafb88e6..7da140bb5 100644 --- a/crates/ide-plugin/tests/fixtures/execution/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/execution/plugin.toml @@ -43,3 +43,10 @@ title = "content" [[contributes.commands]] id = "events" title = "events" + +[[contributes.commands]] +id = "target" +title = "target" +[[contributes.commands]] +id = "untarget" +title = "untarget" diff --git a/crates/ide-plugin/tests/fixtures/execution/src/lib.rs b/crates/ide-plugin/tests/fixtures/execution/src/lib.rs index 5b496ef11..a9d6548c6 100644 --- a/crates/ide-plugin/tests/fixtures/execution/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/execution/src/lib.rs @@ -2,8 +2,28 @@ use openidea_plugin::{host, register_plugin, *}; #[derive(Default)] struct Execution; impl Plugin for Execution { - fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result, Error> { + fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result, Error> { match id { + "target" => { + let project = ctx.project().ok_or_else(|| Error::Invalid("no project".into()))?; + host::register_run_target( + &project, + &PluginRunTarget { + id: arg.unwrap_or("wrapper").into(), + name: "Execution target".into(), + program: "execution-tool".into(), + args: vec!["wrapped".into()], + workdir_args: vec!["--cwd={cwd}".into()], + container_root: Some("/container".into()), + commands: vec![("composer".into(), vec!["composer".into()])], + }, + )?; + Ok(None) + } + "untarget" => { + host::unregister_run_target(&ctx.project().unwrap(), arg.unwrap_or("wrapper")); + Ok(None) + } "run" | "debug" => { host::start_run(arg.unwrap_or("detected"), &["appended".into()], id == "debug").map(Some) } diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index d9f5973cc..3a1f090dc 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 2b1742862..22ec5194a 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -fbcb5bd5df53955f023c2081837678ea2d591b503ae4b33282b9ed288c926f4d +131d45a3c7ef42f063e1100ab7f9d4e1e7b7fcf2095f27377f95eb59387756ee diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index 97fd103fe..5fe12a395 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 0dc3de5a9..cfee5f223 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -8eeb6053d1ab0fca27eae8bd22b9e226cfdfe1a09b8abe5b93b130c6b2cb3a44 +ea0612a1a1248e5410de7e55ff2dad7c4c1973cff690ce0e7f151e5d9395b209 diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index 92cbc1d92..a881f8a7d 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index 43f0ca958..7be43c759 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -0663bba12d8e91b11738a0a51380a393f5f9c28c10de52825bf11b9cc7ce31ff +99cbcce92580b3b292bb92ab34468a156554b1afa53df66320a85df92b37f936 diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index d57893124..7a7d3bb56 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index 834418091..b3695a554 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -f86f6b160823401e80462158d2cc7d1d52835d4487c3d71844f27f48ddf1bfd0 +e7209fe969f00bb2ffb135e401aede7fa40a5b59ca865cc2c0f499d935b8d944 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 12b28350d..a9a820304 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index ce51e19b9..a5608e6bd 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -d139e628e3497f8fde3c56faa0f9e33315fc8c3daf89e1e8db1ab3f8ea5ed8e7 +da1d956ebc383809fd44dd40fa37d9107bf71e2cf2328dcb4a9f4be9203fdff1 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index cacead43f..0dec53401 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index 0c1ef4679..4ddef10cc 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -27c82fc8d8297f6f1d990227a07ca0b3b6351b768cae4cc117afb2cd1901fa89 +9367abca6a02ab0867707450b0dad9a810b586ca14593f8b4ceecbdef67763cd diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index 3538a5356..dbb3305b1 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index 69e2d2d33..22c5bb0a2 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -ab2f64512307cc51261d359b404a50371d5d5f248903ed9fc007c0699cd23e99 +9d6498184eff25bfa053c5ab81f22ffc2ec817e83b26ce8496ab25e7f75c4811 diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 89bae50d0..51464f0b0 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 18da23bde..1c9546015 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -354b750d92a13ba24f23d0b3b6baf74a5c94ab5494d45fa48e2b8b5299dd5ffa +caad529a0659e7b48763026f49025c29d78d1bc12702e4fed307d1f94d76556f diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index eebf74ca0..d32b077c7 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index 5167861de..d668c0bbe 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -02749044dc9a4a1a8e586f2444b542c92aa1bbe57115649bebdb603117df41bf +867d6182eefeb902cfc500c3f7e9eaaf0e58483acfcc3dcac28c3f032d2a7628 diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index ed003c379..18aa9eef7 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index 0153404d8..ce11f4669 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -bb2712ef88dbaffe93871aaf77a37afd4f0368343f1cb31edb45b91a726e74d7 +663c709e7b9da5a97851383f2b47c41eda745b870dc4c770dca0fe092afad4e9 diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 1bd189f12..25ac8761d 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index a88fbbb01..9ffd13442 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -02c4b90c7e8f0c11b123c1c448331d5439d92e04d9672a88321fb7351ff1f2aa +18e0bfeacbd6d5b2cb4ec86ff42d0daf7d679134b2be70136abc24b6572b514b diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index a5d516a0f..760839aab 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index a71b574ea..f029b8e66 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -87794561120d35a3168d34c3c90527c4d46c3387b6937b441425b11b479873d9 +413693a2fbb1ad85f5443040bb15e6535572d2aac00cb9f6626dc059ac08137a diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index 728429521..985a7211e 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index 35b2d4bd6..b847bdfd6 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -49cc9486316cb5ffbddb9d5bc93cd182c06e1a01a8dcd4c9d335170e4746955a +46541cd8169abd46eea69185feb2a5c00d6315f9ba22ff15bb357cf058ca0e68 diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 8983fff7b..6427a09a6 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index a9b12f015..fb39b6fca 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -36110599d633b5d5f6ba0e8cab87c6020d8961b37b1a09ab45601d6303bbee4f +a44ecdc63945e57ad99cd1a285b3b5cd7f82b6825dc110273fc9ddff943c9527 diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index d13416d2b..252818a63 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index 597754ba2..bdf2e5c2c 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -2f9da3991a052b07dfd5b43258c3356d4e037fd375fcacdf9c485ed3eac0e91c +c0d21fff65bd68e7cb827bdd3436961e5082d2eaa611022ce6ca9fb486e29e3e diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index 21cc94230..8de9fc9fa 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index 0aacf83b8..331e896b7 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -68cad6550041e7ba84067e5b81b39ef13d6c4b682ae20b06d0e8bc65f79f9ef0 +14d881cbad963cc24abf17d9eaddbaa61fa15fa363ddb6951df0439e3341760f diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index c35ea351d..2841a1d8b 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index d756bb531..513c081e9 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -b120996b0c0407256932ad352551cd3b57386a51ac07e14a50e2b0f99c15597c +850f96f66fe3d2872c797dda2100358e0e92ecc7661e447ecb7d71e525ae7958 diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index 7fe1d047e..ecee4deb2 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index b21e3b925..5a0d685ae 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -2af20bfd432256aae61cea81fa5c6a2807b272e257e8cedac3c23bafe0d9789d +a56c82dce6035ee8ae2367bc188c05e2d7ad5520ba6c1fb9bf58586b92f5326a diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index cc866a4f3..3f91cb8e7 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index 92f88910f..044802bce 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -13dc72091bf3b94cde9c8f06a2d47c7a16ba12097a4c0bf5968a3bef3450d2cf +8b1377bb6901a5b8595a5818d997cd8fd7d4287269c54c138032f7de6b44b219 diff --git a/crates/ide-remote/src/lib.rs b/crates/ide-remote/src/lib.rs index 2d19e4ad3..7a42a0132 100644 --- a/crates/ide-remote/src/lib.rs +++ b/crates/ide-remote/src/lib.rs @@ -16,3 +16,5 @@ pub use deploy::{ pub use mapping::{Excludes, Mappings, ResolvedMapping}; pub use service::{DeployedPath, DeploymentRoot, RemoteService}; pub use target::{RemoteRuns, RemoteStart}; + +pub mod plugin_target; diff --git a/crates/ide-remote/src/plugin_target.rs b/crates/ide-remote/src/plugin_target.rs new file mode 100644 index 000000000..54fa1906a --- /dev/null +++ b/crates/ide-remote/src/plugin_target.rs @@ -0,0 +1,120 @@ +//! Shell-free argv construction for plugin-owned run targets. +use ide_core::remote_settings::PluginRunTarget; +use ide_core::{IdeError, IdeResult}; +use ide_run::{RunConfig, wrap}; +use std::path::Path; + +/// Validates a bounded target before replacing an existing registration. +pub fn validate(target: &PluginRunTarget) -> IdeResult<()> { + let label = |s: &str, max: usize| !s.is_empty() && s.len() <= max && !s.chars().any(char::is_control); + if !label(&target.id, 128) || !label(&target.name, 256) || !label(&target.program, 256) { + return Err(IdeError::invalid("invalid run target id, name or program")); + } + let argv = |args: &[String]| args.len() <= 256 && args.iter().all(|a| a.len() <= 16384 && !a.contains('\0')); + let mut names = std::collections::BTreeSet::new(); + if !argv(&target.args) + || !argv(&target.workdir_args) + || target.commands.len() > 64 + || target.commands.iter().any(|(name, args)| { + !label(name, 256) || wrap::program_name(name) != *name || !names.insert(name) || !argv(args) + }) + || serde_json::to_vec(target).map_or(true, |v| v.len() > 256 << 10) + || target + .container_root + .as_ref() + .is_some_and(|r| !r.starts_with('/') || r.contains(['\0', '\n', '\r']) || r.split('/').any(|p| p == "..")) + { + return Err(IdeError::invalid("invalid run target arguments or container root")); + } + Ok(()) +} + +/// Wraps argv, keeping the local cwd and environment for the approved wrapper. +/// The wrapper decides whether to forward environment into its container. +pub fn prepare(root: &Path, target: &PluginRunTarget, program: &Path, config: &RunConfig) -> IdeResult { + validate(target)?; + let cwd = wrap::run_dir(root, config); + let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); + let cwd = cwd.canonicalize().unwrap_or(cwd); + let relative = + cwd.strip_prefix(&root).ok().filter(|p| !p.components().any(|c| matches!(c, std::path::Component::ParentDir))); + let mapped_cwd = target.container_root.as_deref().zip(relative).map(|(container, rel)| { + if rel.as_os_str().is_empty() { + container.to_owned() + } else { + format!("{}/{}", container.trim_end_matches('/'), rel.to_string_lossy().replace('\\', "/")) + } + }); + let mapped = target + .container_root + .as_deref() + .map(|container| crate::target::argv_command(config, &Default::default(), &root, container)); + let command = mapped.as_ref().map_or_else( + || { + let p = Path::new(&config.command); + if p.is_absolute() && !p.starts_with(&root) { + wrap::program_name(&config.command) + } else { + config.command.clone() + } + }, + |m| m.program.clone(), + ); + let name = wrap::program_name(&config.command); + let override_args = target.commands.iter().find(|(n, _)| n == &name).map(|(_, a)| a); + let mut args = override_args.unwrap_or(&target.args).clone(); + if let Some(cwd) = mapped_cwd { + args.extend(target.workdir_args.iter().map(|a| a.replace("{cwd}", &cwd))); + } + if override_args.is_none() { + args.push(command); + } + args.extend(mapped.as_ref().map_or_else(|| config.args.clone(), |m| m.args.clone())); + let mut result = config.clone(); + result.command = program.to_string_lossy().into_owned(); + result.args = args; + result.cwd = Some(cwd.into()); + result.extras.target = None; + // A wrapper's -c/-e are its own flags, not interpreter flags to inspect. + result.kind = "shell".into(); + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + fn config(command: &str, args: &[&str], cwd: &str) -> RunConfig { + serde_json::from_value(serde_json::json!({"id":"test", "name":"Test", "kind":"php", "command":command, "args":args, "cwd":cwd, "env":{}, "detected":false, "isTest":false})).unwrap() + } + #[test] + fn prefix_override_cwd_and_literal_argv() { + let target = PluginRunTarget { + id: "ddev".into(), + name: "DDEV".into(), + program: "ddev".into(), + args: vec!["exec".into()], + workdir_args: vec!["--dir".into(), "{cwd}".into()], + container_root: Some("/var/www/html".into()), + commands: vec![("composer".into(), vec!["composer".into()])], + }; + let root = Path::new("/project"); + let program = Path::new("/approved/ddev"); + let run = + prepare(root, &target, program, &config("/usr/bin/php", &["x.php", "$(touch bad); a b"], "src")).unwrap(); + assert_eq!(run.command, "/approved/ddev"); + assert_eq!(run.args, ["exec", "--dir", "/var/www/html/src", "php", "x.php", "$(touch bad); a b"]); + assert_eq!(run.cwd.unwrap().to_string_lossy(), "/project/src"); + let run = prepare(root, &target, program, &config(r"C:\tools\composer.exe", &["install"], "/outside")).unwrap(); + assert_eq!(run.args, ["composer", "install"]); + let in_project = prepare(root, &target, program, &config("/tools/composer", &["install"], "src")).unwrap(); + assert_eq!(in_project.args, ["composer", "--dir", "/var/www/html/src", "install"]); + let run = prepare(root, &target, program, &config("composer", &["install"], "../outside")).unwrap(); + assert_eq!(run.args, ["composer", "install"]); + let mut target = target; + target.container_root = None; + let run = prepare(root, &target, program, &config("php", &["x.php"], "src")).unwrap(); + assert_eq!(run.args, ["exec", "php", "x.php"]); + let run = prepare(root, &target, program, &config("echo a; touch bad", &[], ".")).unwrap(); + assert_eq!(run.args, ["exec", "echo a; touch bad"]); + } +} diff --git a/crates/ide-remote/src/target.rs b/crates/ide-remote/src/target.rs index 97577e0d9..1bf971216 100644 --- a/crates/ide-remote/src/target.rs +++ b/crates/ide-remote/src/target.rs @@ -109,6 +109,22 @@ fn interpreter<'a>(program: &str, target: &'a RunTarget) -> Option<&'a str> { /// Builds the remote command of `config`; `root` (the project) maps onto `remote_root`. pub fn remote_command(config: &RunConfig, target: &RunTarget, root: &Path, remote_root: &str) -> RemoteCommand { + target_command(config, target, root, remote_root, true) +} + +/// Maps paths and interpreters while preserving argv, including a command containing spaces. +/// Unlike SSH/container shell configurations, plugin wrappers never accept a shell line. +pub fn argv_command(config: &RunConfig, target: &RunTarget, root: &Path, remote_root: &str) -> RemoteCommand { + target_command(config, target, root, remote_root, false) +} + +fn target_command( + config: &RunConfig, + target: &RunTarget, + root: &Path, + remote_root: &str, + allow_shell: bool, +) -> RemoteCommand { let root_str = root.to_string_lossy().into_owned(); let map = |s: &str| -> String { if root_str.is_empty() { @@ -129,7 +145,7 @@ pub fn remote_command(config: &RunConfig, target: &RunTarget, root: &Path, remot }; let env = config.env.iter().map(|(k, v)| (k.clone(), map_text(v))).collect(); let command = config.command.trim(); - if config.args.is_empty() && command.contains(char::is_whitespace) { + if allow_shell && config.args.is_empty() && command.contains(char::is_whitespace) { return RemoteCommand { program: String::new(), args: Vec::new(), diff --git a/crates/ide-sdk/src/apply.rs b/crates/ide-sdk/src/apply.rs index 7ad8e2009..14c689878 100644 --- a/crates/ide-sdk/src/apply.rs +++ b/crates/ide-sdk/src/apply.rs @@ -1173,6 +1173,29 @@ fn add_maven_options(args: &mut Vec, options: &[String], additive_profil args.splice(0..0, missing); } +/// The interpreter target or project default; an explicit local choice returns an empty id. +pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a str> { + let name = ide_run::wrap::program_name(&config.command); + let target = if matches!(name.as_str(), "php" | "composer" | "phpunit" | "pest") + || matches!(config.kind.as_str(), "php" | "composer" | "phpunit") + { + &settings.languages.php.run_target + } else if matches!(name.as_str(), "node" | "npm" | "npx" | "pnpm" | "yarn" | "bun") + || matches!(config.kind.as_str(), "node" | "npm" | "vitest" | "jest" | "mocha") + { + &settings.languages.node.run_target + } else { + return non_empty(&settings.run.default_target); + }; + if target == "local" { + Some("") + } else if target.is_empty() { + non_empty(&settings.run.default_target) + } else { + Some(target) + } +} + /// Points run configurations at the selected toolchains: Python configs use the /// project interpreter, npm scripts the chosen package manager and Node.js, /// cargo / go configs the selected toolchain, Maven / Gradle their runner JDK @@ -1210,6 +1233,19 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings }; for c in configs.iter_mut() { + if let Some(pm) = pm + && c.kind == "npm" + && c.detected + && matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun") + { + c.command = pm.to_owned(); + } + if c.extras.target.is_none() { + c.extras.target = run_target(c, s).map(str::to_owned); + } + if c.extras.target.as_deref().is_some_and(|t| t.starts_with("plugin-target:")) { + continue; + } let owner = ide_run::scope::owner(root, c); resolve_run_command(c, root, s); let mut path_dirs: Vec = Vec::new(); @@ -1243,13 +1279,6 @@ pub fn apply_to_run_configs(configs: &mut [RunConfig], root: &Path, s: &Settings } } "npm" | "node" | "deno" | "bun" => { - if let Some(pm) = pm - && c.kind == "npm" - && c.detected - && matches!(c.command.as_str(), "npm" | "pnpm" | "yarn" | "bun") - { - c.command = pm.to_owned(); - } // The configuration's own Node interpreter, else the project's. let own = c.extras.params.get("nodeInterpreter").and_then(|p| setting_path(root, p)); if let Some(dir) = @@ -1367,6 +1396,9 @@ pub fn without_derived(config: &RunConfig, root: &Path, s: &Settings) -> RunConf c }; let mut out = config.clone(); + if out.extras.target.as_deref() == run_target(&out, s) { + out.extras.target = None; + } // Until nothing changes: some entries are derived only once others are gone // (the virtualenv's `PATH` is added only without `VIRTUAL_ENV`). An entry derived before // the configuration's own choice (an npm script's Node interpreter) is derived too. diff --git a/crates/ide-sdk/src/tests.rs b/crates/ide-sdk/src/tests.rs index ec9d12190..dcef83a8d 100644 --- a/crates/ide-sdk/src/tests.rs +++ b/crates/ide-sdk/src/tests.rs @@ -2169,3 +2169,31 @@ fn project_structure_module_jdk_language_level_and_external_libraries() { let groups = crate::libraries::project_libraries(root, &settings, &[]); assert!(groups.iter().any(|g| g.name == "servlet-api" && g.kind == "library" && g.roots.len() == 1)); } + +#[test] +fn plugin_interpreter_targets_route_all_php_node_command_families() { + let mut settings = Settings::default(); + settings.languages.php.run_target = "plugin-target:php".into(); + settings.languages.node.run_target = "plugin-target:node".into(); + settings.languages.php.interpreter = "/local/php".into(); + settings.languages.node.interpreter = "/local/node".into(); + for (command, kind, expected) in [ + ("php", "php", "php"), + ("composer", "composer", "php"), + ("vendor/bin/phpunit", "phpunit", "php"), + ("node", "node", "node"), + ("npm", "npm", "node"), + ("node_modules/.bin/vitest", "vitest", "node"), + ("npx", "node", "node"), + ] { + let mut config: ide_run::RunConfig = serde_json::from_value(serde_json::json!({ "id":"run", "name":"run", "kind":kind, "command":command, "args":[], "env":{}, "detected":true, "isTest":false })).unwrap(); + crate::apply::apply_to_run_configs(std::slice::from_mut(&mut config), Path::new("/project"), &settings); + assert_eq!(config.extras.target.as_deref(), Some(format!("plugin-target:{expected}").as_str())); + assert_eq!(config.command, command); + assert!(config.env.is_empty()); + assert!(crate::apply::without_derived(&config, Path::new("/project"), &settings).extras.target.is_none()); + config.extras.target = Some(String::new()); + crate::apply::apply_to_run_configs(std::slice::from_mut(&mut config), Path::new("/project"), &settings); + assert_eq!(config.extras.target.as_deref(), Some("")); + } +} diff --git a/plugins/README.md b/plugins/README.md index 61488c14a..4b98c6d18 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -495,6 +495,8 @@ then run `openidea-plugin check`. | `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | | `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | | `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:` in the project root: output that keeps coming, interactive sessions. | +| `host::register_run_target(project, target)` | `run-targets.register` | API 1.4: project-scoped, read-only argv wrapper; requires its process grant, executable pin and project trust; remote projects run on the server. | +| `host::unregister_run_target(project, id)` | `run-targets.unregister` | Withdraw this plugin's target; remembered prompt answers remain. | | `host::start_run(config, args, debug)` | `run.start` | API 1.4: start an owned configuration in this window's Run tool window; returns an id, followed by `run-exited`. Approved `process:` program; commands/events only. | | `host::open_terminal_session(key, title, cmd)` | `views.open-terminal-session` | API 1.4: keyed, pinned terminal in this window, append-only env; returns its operation id and later `terminal-exited`. | | `host::write_terminal(key, text)` | `views.write-terminal` | API 1.4: write only to this plugin's still-running terminal in this window; trusted project, commands/events only. | @@ -2060,3 +2062,57 @@ one dismisses the balloon and runs the command in the receiving window with its normal editor and project context. No capability is needed. Invalid or undeclared actions reject the whole notification. Labels are limited to 256 bytes and arguments to 64 KiB. Plain `host::notify` behaves as before. + +### Plugin-provided run targets (API 1.4) + +`host::register_run_target(project, target)` registers or replaces a read-only, +project-scoped target owned by the plugin. `host::unregister_run_target(project, +id)` removes it. `PluginRunTarget` has `id`, `name`, a granted `process:` `program`, +`args`, `workdir_args`, optional `container_root`, and `commands` (pairs of tool +names and replacement argv). Targets appear in Settings › Run Targets and every +run configuration's Run on selector, labelled with their plugin. They survive +idle instance reclamation; stopping, disabling, reloading or uninstalling a plugin +withdraws them. Registrations and execution for remote projects are on the server. +A missing target fails the run rather than silently using the local tool. + +For each launch the host checks project trust and the wrapper's current process +grant and executable pin, including per-project executable choices. Debugging on +plugin targets returns `invalid`; language servers are not run in these targets. +There are at most 32 targets per plugin/project, 64 unique command overrides and +256 arguments per prefix (16 KiB each, 256 KiB metadata per registration). + +The host constructs argv directly, without a shell: + +- No override: `program + args + workdir_args + command + command arguments`. +- Override matching `wrap::program_name(command)` (basename without `.exe`, `.cmd` + or `.bat`): `program + override + workdir_args + command arguments`. The override + replaces **both** the prefix and the command name and includes the tool itself. + +DDEV, for example: `program = "ddev"`, `args = ["exec"]`, +`commands = [("composer", ["composer"])]` runs `php x.php` as +`ddev exec php x.php` and `composer install` as `ddev composer install`. + +Local absolute tool paths outside the project use the tool basename. +When `container_root` is set, project paths in argv map under that root. Each +`workdir_args` element may contain `{cwd}`; for example `["--dir", "{cwd}"]`. +The host substitutes the configuration's working directory mapped under +`container_root`. It omits **all** workdir arguments when there is no container +root or the working directory is outside the project. Without `workdir_args`, +the wrapper manages its container directory itself. The wrapper process always +starts in the configuration's **local** working directory, so tools such as DDEV +can find their project. Configuration env and env files reach the local wrapper; +no generic env-forwarding flags are added. Container env is forwarded only if +the wrapper's own conventions allow it. + +Registration never changes a selection. The first registration prompts the +project's windows: “Use for running PHP / Node / Composer in this project?” +with **Use** / **Not now**. The first answer is remembered on the host per +project + plugin + target id. Use sets the project's default run target and its +PHP and Node run-target choices; Not now leaves settings alone. Interpreters +also have a Run in target choice in Settings (Default run target, Local machine, +or a named target). The `languages.php.runTarget` / `languages.node.runTarget` +settings store a selector id, empty for the default, or `local` for local execution. Code-created PHP/Node runs, +Composer/npm scripts, PHPUnit and Node tests use that choice through the normal +Run flow. Explicit per-configuration targets take precedence. Choosing Local +machine explicitly overrides defaults. Language servers, tool discovery/version +probes and external analysis helpers remain local to the host. diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 7f048844b..3d2ad3c4d 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index cc222d8a7..ab03df14c 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -1fff539520d04708c37de01116f55f2453d638600cd879d0494d405427d7253e +ff03abdb82800057592e18466292e642ad18f644eab5855993cd67e00850698b diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index 9dd6de93b..a70548890 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index c87f43929..e146254c5 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -da99bca60545937b82fc6f88aeca392cd991c6d8f21bbd04fb25965c3cb24856 +6429c38a0dbc856e4b992e4ec80148e75b54a87730c8e1b137169d259f3d6d54 diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index f8657f957..0e02d0425 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index 517e9fe90..c6718c074 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -334dc90682133da39fa190e0a95a85d32bbeeadba704c918122fe390d3989c6d +41c3f77d244a40c27a52cd66b1514dea9be0cb6cde85515d72f67cd1b8dabab1 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 090eb6290..810facdfc 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 59a1ebedb..907425feb 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -d0886a4b074f2cdb119a8c74bf13b95592a3f4f4b1df80dffca92554560821dc +14f8678dd23d0dd9d6e25b4af27a6d964010eebd5715c6ea8fe49aff91811dbe diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index 6e5b438c2..1351dffe4 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index e027bcac9..287dcd086 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -1aaa0540c035bcf93dc81756b771ebb77f70bebf63cf43cededc80a0688c1aac +765857e31af345347bda02016f4162e90cd5e3f4fc4d19957d867ea1a0d88b02 diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 15cc40623..204ed76f1 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 81526d649..6f07058ed 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -c062aec81853deafa036eac3174475935f41ff0fb75567aba570be64bb6dc4e2 +f1b38b7bde8db372ef45077db017d2612712bc4ff1d3946136e3b3bc2c197a75 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index 7421f3cd1..feb5b6737 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index 9daf19d7a..efb053ad1 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -0a1a92812b92b7d62ec662d73316767cb8c0435c7b4823842ba873be7bfa771d +661638c93c0e695bf61b647289cf5f242c5d057fa1ebc176768166053254d364 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index a0ef05af6..21dcd79c0 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index 78bdc6f2f..9cfc339a1 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -e036b4f5dc4d6e072ebaa4d3be8072236c130a6ec3c5d303f2a0680245d4e223 +ccbfb3bd2f763aaca519947d7205236108201919effd848f7963c850337f0773 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index f1b8d0667..830222629 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index 336061161..1b465d476 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -2a48ef3332a70b6b71ebc0469dcb01e8ba8c56cdfc360af0fc75b27886d76577 +d83934c41880875ac20ffa119dba61d9fc04339653df1cbcc2da9f6465360dcf diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index 9c6693d70..fb2578db8 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index d2572f31c..fe25189df 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -815f433e3a004079ab0cc2e9f07943488df17e933735b86875fc980d4ccff506 +1f423f8744f7470b43b364ed3b42b283039a3700fa908b7052d163afe9fdb427 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 04e0d8239..31d7725f7 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index ba4bb5606..7d6641b28 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -6e70e57bf86e2d65e0b299e8ec02f9e74323a6d5ca8507bae5b4ccd59dbcefe3 +4f70b1ec6d7ba5e67d5d49607ba30185cd7c0842b229a732ad6f17bf32ebb24c diff --git a/sdk/rust/openidea-plugin/src/execution.rs b/sdk/rust/openidea-plugin/src/execution.rs index 3d3669ac8..e8866312d 100644 --- a/sdk/rust/openidea-plugin/src/execution.rs +++ b/sdk/rust/openidea-plugin/src/execution.rs @@ -178,3 +178,16 @@ impl crate::Event { (kind == expected).then(|| serde_json::from_str(data).ok()).flatten() } } + +/// A plugin-owned argv wrapper for project runs (API 1.4). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginRunTarget { + pub id: String, + pub name: String, + pub program: String, + pub args: Vec, + pub workdir_args: Vec, + pub container_root: Option, + pub commands: Vec<(String, Vec)>, +} diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 417b1affc..345ced511 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -690,6 +690,24 @@ mod imp { } } + pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> { + wit::run_targets::register( + project, + &wit::run_targets::RunTarget { + id: target.id.clone(), + name: target.name.clone(), + program: target.program.clone(), + args: target.args.clone(), + workdir_args: target.workdir_args.clone(), + container_root: target.container_root.clone(), + commands: target.commands.clone(), + }, + ) + .map_err(error) + } + pub fn unregister_run_target(project: &ProjectRes, id: &str) { + wit::run_targets::unregister(project, id); + } pub fn start_run(config: &str, args: &[String], debug: bool) -> Result { wit::run::start(config, args, debug).map_err(error) } @@ -1599,3 +1617,12 @@ pub fn open_content_tab(tab: &crate::ContentTab) -> Result<(), Error> { pub fn reply_content_tab(request: &str, reply: &crate::ContentTabReply) -> Result<(), Error> { imp::reply_content_tab(request, reply) } + +/// Registers/replaces a read-only project target. Requires the program's process grant. +pub fn register_run_target(project: &Project, target: &crate::PluginRunTarget) -> Result<(), Error> { + imp::register_run_target(&project.inner, target) +} +/// Withdraws a target owned by this plugin. +pub fn unregister_run_target(project: &Project, id: &str) { + imp::unregister_run_target(&project.inner, id); +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index e724fadd6..edd5126ca 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -150,6 +150,7 @@ struct State { terminal_writes: Vec<(String, String)>, content_tabs: BTreeMap, content_replies: Vec<(String, crate::ContentTabReply)>, + run_targets: BTreeMap<(String, String), crate::PluginRunTarget>, run_configurations: BTreeMap, configuration_runs: Vec<(String, String, Vec, bool)>, log_tabs: Vec, @@ -478,6 +479,10 @@ impl MockHost { self.state.borrow().locations.clone() } + /// Registered targets of this mock plugin, scoped by project root. + pub fn run_targets(&self) -> BTreeMap<(String, String), crate::PluginRunTarget> { + self.state.borrow().run_targets.clone() + } /// Configurations available to start_run in native tests. pub fn set_run_configurations(&self, configs: Vec) { self.state.borrow_mut().run_configurations = configs.into_iter().map(|c| (c.id.clone(), c)).collect(); @@ -1754,6 +1759,29 @@ pub mod current { Ok(()) } + pub fn register_run_target(project: &ProjectRes, target: &crate::PluginRunTarget) -> Result<(), Error> { + with(|s| { + require(s, &format!("process:{}", target.program))?; + if target.id.is_empty() + || target.name.is_empty() + || target + .args + .iter() + .chain(&target.workdir_args) + .chain(target.commands.iter().flat_map(|(_, a)| a)) + .any(|a| a.contains('\0')) + { + return Err(Error::Invalid("invalid run target".into())); + } + s.run_targets.insert((project.root.clone(), target.id.clone()), target.clone()); + Ok(()) + }) + } + pub fn unregister_run_target(project: &ProjectRes, id: &str) { + with(|s| { + s.run_targets.remove(&(project.root.clone(), id.into())); + }); + } pub fn start_run(config: &str, args: &[String], debug: bool) -> Result { with(|s| { let c = s.run_configurations.get(config).ok_or_else(|| Error::NotFound(config.into()))?; diff --git a/sdk/rust/openidea-plugin/tests/api14_stage3.rs b/sdk/rust/openidea-plugin/tests/api14_stage3.rs index 89c6f08f8..86f011b73 100644 --- a/sdk/rust/openidea-plugin/tests/api14_stage3.rs +++ b/sdk/rust/openidea-plugin/tests/api14_stage3.rs @@ -30,3 +30,26 @@ fn owned_configurations_require_grants_and_reject_debug_without_a_debugger() { assert!(matches!(host::start_run("tests", &[], true), Err(Error::Invalid(_)))); assert!(matches!(host::start_run("foreign", &[], false), Err(Error::NotFound(_)))); } + +#[test] +fn run_targets_require_a_program_grant_and_are_project_scoped() { + let mock = MockHost::install(); + let project = mock.invocation().project().unwrap(); + let target = PluginRunTarget { + id: "ddev".into(), + name: "DDEV".into(), + program: "ddev".into(), + args: vec!["exec".into()], + ..Default::default() + }; + assert!(matches!(host::register_run_target(&project, &target), Err(Error::Denied(_)))); + let mock = mock.with_capabilities(&["process:ddev"]); + host::register_run_target(&project, &target).unwrap(); + assert_eq!(mock.run_targets().len(), 1); + host::register_run_target(&project, &target).unwrap(); + assert_eq!(mock.run_targets().len(), 1); + host::unregister_run_target(&project, "missing"); + assert_eq!(mock.run_targets().len(), 1); + host::unregister_run_target(&project, "ddev"); + assert!(mock.run_targets().is_empty()); +} diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index 03312b0aa..ffe202a3f 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -33,6 +33,7 @@ world plugin { import command-runner; import views; import run; + import run-targets; import settings; export lifecycle; diff --git a/sdk/rust/openidea-plugin/wit/run-targets.wit b/sdk/rust/openidea-plugin/wit/run-targets.wit new file mode 100644 index 000000000..66a41e700 --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/run-targets.wit @@ -0,0 +1,36 @@ +package openidea:plugin@1.4.0; + +/// Project-scoped targets owned by the registering plugin (API 1.4). +interface run-targets { + use types.{error}; + use workspace.{project}; + + /// An argv wrapper using a granted, pinned process program. No shell is used. + /// Normally: program + args + workdir-args + command + command arguments. + /// An override matches wrap::program_name(command) and replaces args AND command: + /// program + override + workdir-args + command arguments. + /// DDEV: program="ddev", args=["exec"], commands=[("composer", ["composer"])]: + /// `ddev exec php x.php` and `ddev composer install`. + /// Each workdir-args element may contain {cwd}, mapped under container-root. + /// All workdir-args are omitted without container-root or for cwd outside the project. + /// Without workdir-args the wrapper manages its container directory itself. + /// The wrapper always starts in the configuration's LOCAL working directory. + /// Environment reaches the wrapper; forwarding into a container depends on its conventions. + /// Registration never selects the target. Debugging plugin targets is invalid. + record run-target { + id: string, + name: string, + program: string, + args: list, + workdir-args: list, + container-root: option, + commands: list>>, + } + + /// Registers/replaces this plugin's target in an open, trusted project. + /// Targets survive idle reclamation, and disappear on unregister or plugin stop. + /// Remote project registration and execution take place on the server. + register: func(project: borrow, target: run-target) -> result<_, error>; + /// Removes only this plugin's target from the project; missing ids are harmless. + unregister: func(project: borrow, id: string); +} diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 49a1c3fe0..0a6be2d74 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -531,6 +531,8 @@ pub fn builder() -> tauri_specta::Builder { plugin::plugin_navigation_goto, plugin::plugin_navigation_markers, plugin::plugin_endpoints, + plugin::plugin_run_targets, + plugin::plugin_answer_run_target, plugin::plugin_market, plugin::plugin_market_url, plugin::plugin_set_market_url, diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index 9e1ed5094..6e288d8f2 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -1027,3 +1027,25 @@ pub async fn plugin_prepare_debug_run( .await .map_err(|e| IdeError::internal(e.to_string()))? } + +#[tauri::command] +#[specta::specta] +pub async fn plugin_run_targets( + window: Window, + state: State<'_, AppState>, +) -> IdeResult> { + ide_host::plugins::run_targets::list(&state.host, &state.plugins, window.label()) +} +#[tauri::command] +#[specta::specta] +pub async fn plugin_answer_run_target( + window: Window, + state: State<'_, AppState>, + id: String, + use_target: bool, +) -> IdeResult { + let host = state.host.clone(); + let plugins = state.plugins.clone(); + let window = window.label().to_owned(); + state.host.blocking(move || ide_host::plugins::run_targets::answer(&host, &plugins, &window, &id, use_target)).await +} diff --git a/src/bindings.ts b/src/bindings.ts index 08459eb58..1aff1f41e 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1208,6 +1208,8 @@ export const commands = { } | null, IdeError>(__TAURI_INVOKE("plugin_navigation_goto", { doc, pos })), pluginNavigationMarkers: (paths: string[]) => typedError(__TAURI_INVOKE("plugin_navigation_markers", { paths })), pluginEndpoints: (pluginId: string) => typedError(__TAURI_INVOKE("plugin_endpoints", { pluginId })), + pluginRunTargets: () => typedError(__TAURI_INVOKE("plugin_run_targets")), + pluginAnswerRunTarget: (id: string, useTarget: boolean) => typedError(__TAURI_INVOKE("plugin_answer_run_target", { id, useTarget })), /** The marketplace's plugins: read again when `refresh` or when none was read yet, else the last index read. */ pluginMarket: (refresh: boolean) => typedError(__TAURI_INVOKE("plugin_market", { refresh })), pluginMarketUrl: () => __TAURI_INVOKE("plugin_market_url"), @@ -5947,6 +5949,8 @@ export type NodeAt = { export type NodeSettings = { /** `node` executable; empty = the one on `PATH`. */ interpreter?: string, + /** Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local. */ + runTarget?: string, /** `npm` | `pnpm` | `yarn`; empty = detect from the lock file / `packageManager`. */ packageManager?: string, }; @@ -6144,6 +6148,8 @@ export type PhpLevelSource = export type PhpSettings = { /** `php` CLI executable; empty = the one on `PATH`. */ interpreter?: string, + /** Run PHP/Composer or Node/package-manager commands in this target; empty = project default, `local` = local. */ + runTarget?: string, /** * PHP version the language server checks the code against (`7.4`); empty = from * `composer.json` (`config.platform.php`, else the lowest version `require.php` allows). @@ -6232,6 +6238,8 @@ export type PluginEvent = PluginEvent_Serialize | PluginEvent_Deserialize; /** Backend → UI notifications (Tauri event `ide://plugin`). */ export type PluginEvent_Deserialize = +/** Project target registrations or remembered prompt answers changed. */ +({ type: "runTargetsChanged" }) & { actions?: never; arg?: never; args?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; cwd?: never; done?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; path?: never; pluginId?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; selection?: never; sets?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never } | /** A window-owned operation; an empty request id queues an asynchronous run. */ ({ type: "windowRequest"; pluginId: string; requestId: string; request: WindowRequest_Deserialize }) & { actions?: never; arg?: never; args?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; cwd?: never; done?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; path?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; reveal?: never; root?: never; selection?: never; sets?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never } | /** Reply to a content action in this window. */ @@ -6324,6 +6332,8 @@ actions: NotificationAction[] }) & { arg?: never; args?: never; cancellable?: ne /** Backend → UI notifications (Tauri event `ide://plugin`). */ export type PluginEvent_Serialize = +/** Project target registrations or remembered prompt answers changed. */ +({ type: "runTargetsChanged" }) & { actions?: never; arg?: never; args?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; cwd?: never; done?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; path?: never; pluginId?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; request?: never; requestId?: never; reveal?: never; root?: never; selection?: never; sets?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never } | /** A window-owned operation; an empty request id queues an asynchronous run. */ ({ type: "windowRequest"; pluginId: string; requestId: string; request: WindowRequest_Serialize }) & { actions?: never; arg?: never; args?: never; body?: never; cancellable?: never; capabilities?: never; chain?: never; channel?: never; column?: never; cwd?: never; done?: never; id?: never; item?: never; key?: never; level?: never; line?: never; log?: never; message?: never; newWindow?: never; path?: never; program?: never; prompt?: never; promptId?: never; ranges?: never; reply?: never; reveal?: never; root?: never; selection?: never; sets?: never; taskId?: never; text?: never; theme?: never; title?: never; total?: never; updates?: never; url?: never; value?: never; view?: never } | /** Reply to a content action in this window. */ @@ -6463,6 +6473,17 @@ export type PluginOutputLine = { text: string, }; +/** A plugin-owned argv wrapper for project runs (API 1.4). */ +export type PluginRunTarget = { + id: string, + name: string, + program: string, + args: string[], + workdirArgs: string[], + containerRoot: string | null, + commands: ([string, string[]])[], +}; + /** A secret a plugin declares, and whether the user stored it. */ export type PluginSecretState = { name: string, @@ -7005,6 +7026,15 @@ export type ReferencesIncomplete = /** A native query failed; indexed anchors are still available. */ "serverFailed"; +export type RegisteredRunTarget = { + /** Opaque selector id, namespaced by the host. */ + id: string, + pluginId: string, + pluginName: string, + target: PluginRunTarget, + prompt: boolean, +}; + /** A registry agent this machine can run (or has installed). */ export type RegistryAgent = { id: string, @@ -7437,6 +7467,8 @@ export type RunInfo = { /** Run/Debug configuration behaviour. */ export type RunSettings = { + /** Target for configurations without an explicit target. Empty = local. */ + defaultTarget?: string, confirmRerun?: boolean, /** Ask before closing a Run tab whose process is still running. */ confirmTerminate?: boolean, diff --git a/src/features/plugins/__tests__/runTargets.test.ts b/src/features/plugins/__tests__/runTargets.test.ts new file mode 100644 index 000000000..6e3f2ca39 --- /dev/null +++ b/src/features/plugins/__tests__/runTargets.test.ts @@ -0,0 +1,90 @@ +import { beforeEach, expect, it, vi } from "vitest"; +import { useProject } from "@/platform/project"; +import { usePluginRunTargets } from "@/platform/pluginRunTargets"; +import { withRunTarget } from "@/platform/runTargetSelection"; +import type { RegisteredRunTarget, RunConfig, Settings } from "@/bindings"; +const mocks = vi.hoisted(() => ({ list: vi.fn(), answer: vi.fn(), notify: vi.fn(), expire: vi.fn() })); +vi.mock("../backend", () => ({ pluginsBackend: () => ({ runTargets: mocks.list, answerRunTarget: mocks.answer }) })); +vi.mock("@/workbench/contributions", () => ({ notifications: () => ({ notify: mocks.notify, expire: mocks.expire }) })); +import { refreshRunTargets, startRunTargets } from "../runTargets"; +const target: RegisteredRunTarget = { + id: "plugin-target:4:testddev", + pluginId: "test", + pluginName: "Test", + prompt: true, + target: { + id: "ddev", + name: "DDEV", + program: "ddev", + args: ["exec"], + workdirArgs: [], + containerRoot: null, + commands: [], + }, +}; +beforeEach(() => { + vi.clearAllMocks(); + useProject.setState({ project: { root: `/project-${Math.random()}` } as never, settings: {} }); + usePluginRunTargets.setState({ targets: [] }); + mocks.list.mockResolvedValue([target]); +}); +it("loads settings-window targets after its project arrives without prompting there", async () => { + useProject.setState({ project: null }); + const stop = startRunTargets(false); + try { + useProject.setState({ project: { root: "/settings-owner" } as never }); + await vi.waitFor(() => expect(usePluginRunTargets.getState().targets).toEqual([target])); + expect(mocks.notify).not.toHaveBeenCalled(); + mocks.list.mockResolvedValue([]); + await refreshRunTargets(false); + expect(usePluginRunTargets.getState().targets).toEqual([]); + expect(mocks.answer).not.toHaveBeenCalled(); + } finally { + stop(); + } +}); +it("offers Use / Not now once without changing the selection on registration", async () => { + const original = useProject.getState().settings; + await refreshRunTargets(); + expect(useProject.getState().settings).toBe(original); + expect(mocks.answer).not.toHaveBeenCalled(); + const notification = mocks.notify.mock.calls[0]![0]; + expect(notification.body).toBe("Use DDEV for running PHP / Node / Composer in this project?"); + expect(notification.actions.map((a: { label: string }) => a.label)).toEqual(["Use", "Not now"]); + await refreshRunTargets(); + expect(mocks.notify).toHaveBeenCalledTimes(1); + mocks.answer.mockResolvedValue(original); + mocks.list.mockResolvedValue([{ ...target, prompt: false }]); + notification.actions[1].run(); + await vi.waitFor(() => expect(mocks.answer).toHaveBeenCalledWith(target.id, false)); + expect(useProject.getState().settings).toBe(original); +}); +it("Use applies only the host-returned settings and a removed target disappears", async () => { + const settings: Settings = { + run: { defaultTarget: target.id }, + languages: { php: { runTarget: target.id }, node: { runTarget: target.id } }, + }; + await refreshRunTargets(); + mocks.answer.mockResolvedValue(settings); + mocks.list.mockResolvedValue([{ ...target, prompt: false }]); + mocks.notify.mock.calls[0]![0].actions[0].run(); + await vi.waitFor(() => expect(useProject.getState().settings).toBe(settings)); + mocks.list.mockResolvedValue([]); + await refreshRunTargets(); + expect(usePluginRunTargets.getState().targets).toEqual([]); + expect(mocks.expire).toHaveBeenCalledWith(`plugin-run-target:${target.id}`); +}); +it("explicit local and per-config selections win over interpreter and project defaults", () => { + useProject.setState({ + settings: { + run: { defaultTarget: "default" }, + languages: { php: { runTarget: "php-target" }, node: { runTarget: "node-target" } }, + }, + }); + const config = { command: "php", kind: "php" } as RunConfig; + expect(withRunTarget(config).target).toBe("php-target"); + expect(withRunTarget({ ...config, command: "npm", kind: "npm" }).target).toBe("node-target"); + expect(withRunTarget({ ...config, command: "cargo", kind: "cargo" }).target).toBe("default"); + expect(withRunTarget({ ...config, target: "" }).target).toBe(""); + expect(withRunTarget({ ...config, target: "explicit" }).target).toBe("explicit"); +}); diff --git a/src/features/plugins/backend.ts b/src/features/plugins/backend.ts index 8106c34d2..c83ed774b 100644 --- a/src/features/plugins/backend.ts +++ b/src/features/plugins/backend.ts @@ -1,3 +1,4 @@ +import { useProject } from "@/platform/project"; /** * Plugin host backend: `plugin_*` IPC + a `plugin_subscribe` event channel in the desktop * app; an in-memory simulation (the bundled samples) in plain-browser @@ -126,6 +127,8 @@ export interface PluginsBackend { /** The detail tabs of item `key` in a Services or `detail = true` view. */ serviceDetail(pluginId: string, view: string, key: string): Promise; /** The HTTP routes a plugin reports for this window's project (`[[contributes.endpoints]]`). */ + runTargets(): Promise; + answerRunTarget(id: string, useTarget: boolean): Promise; endpoints(pluginId: string): Promise; /** * Runs the program of node `key`'s log tab `tab` (with the toggles in `on`) and streams its @@ -292,6 +295,8 @@ export const tauriPluginsBackend: PluginsBackend = { await call(commands.pluginViewEvent(pluginId, view, event, doc, doc == null ? editorContext() : null)); }, serviceDetail: (pluginId, view, key) => call(commands.pluginServiceDetail(pluginId, view, key)), + runTargets: () => call(commands.pluginRunTargets()), + answerRunTarget: (id, useTarget) => call(commands.pluginAnswerRunTarget(id, useTarget)), endpoints: (pluginId) => call(commands.pluginEndpoints(pluginId)), serviceLog: (pluginId, view, key, tab, on, onLine, onError, onExit) => { const request = nextRequestId(); @@ -651,6 +656,8 @@ export function createMemoryPluginsBackend( }), viewEvent: async () => {}, serviceDetail: async () => [], + runTargets: async () => [], + answerRunTarget: async () => useProject.getState().settings as import("@/bindings").Settings, endpoints: async () => [], answerCommand: async () => {}, finishOperation: async () => {}, diff --git a/src/features/plugins/bridge.ts b/src/features/plugins/bridge.ts index a0fd057ce..328b0c2e9 100644 --- a/src/features/plugins/bridge.ts +++ b/src/features/plugins/bridge.ts @@ -36,6 +36,7 @@ import { defineBuiltinUiPoints } from "./points"; import { localizeContributions, loadPluginCatalogs, usePluginCatalogs } from "./pluginText"; import { clearUiContributions, syncUiContributions } from "./projection"; import { handleRuntimeEvent, refreshEventKinds, startRuntimeUi } from "./runtimeUi"; +import { refreshRunTargets } from "./runTargets"; import { grantPlugin, runPluginCommand, @@ -330,6 +331,7 @@ export function handlePluginEvent(e: PluginEvent) { */ export function followPluginChanges(): () => void { return pluginsBackend().onEvent((e) => { + if (e.type === "runTargetsChanged") void refreshRunTargets(false).catch(() => {}); if (e.type === "commandsChanged" || e.type === "themeChanged" || e.type === "languagesChanged") handlePluginEvent(e); }); diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index e37bf2456..df6138bb9 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -35,6 +35,7 @@ import { showInstalledIntellijThemes, useIntellijThemesDialog } from "./intellij import { startWorkspaceContains } from "./workspaceContains"; import { startPluginDecorations } from "./decorations"; import { startIndexedMarkers } from "./indexedMarkers"; +import { startRunTargets } from "./runTargets"; import { startPluginNavigation } from "./navigation"; import { installFromDisk, refreshPlugins, reloadPlugin, SETTINGS_PAGE_ID, updateAllPlugins, usePlugins } from "./store"; @@ -63,6 +64,7 @@ export function activateSettingsPages(): () => void { provideConsentDialog(), defineBuiltinUiPoints(), followPluginChanges(), + startRunTargets(false), syncProjection(), trackPluginTheme(), trackIconTheme(), diff --git a/src/features/plugins/runTargets.ts b/src/features/plugins/runTargets.ts new file mode 100644 index 000000000..761f77b86 --- /dev/null +++ b/src/features/plugins/runTargets.ts @@ -0,0 +1,79 @@ +import type { RegisteredRunTarget } from "@/bindings"; +import { tx } from "@/platform/i18n"; +import { isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { usePluginRunTargets } from "@/platform/pluginRunTargets"; +import { notifications } from "@/workbench/contributions"; +import { pluginsBackend } from "./backend"; + +let revision = 0; +const shown = new Set(); +function clearTargets(prompts = true) { + revision++; + if (prompts) + for (const target of usePluginRunTargets.getState().targets) + notifications().expire?.(`plugin-run-target:${target.id}`); + shown.clear(); + usePluginRunTargets.setState({ targets: [] }); +} +export async function refreshRunTargets(prompts = true) { + const request = ++revision; + const root = useProject.getState().project?.root; + if (!root) { + clearTargets(prompts); + return; + } + const targets = await pluginsBackend().runTargets(); + if (request !== revision || root !== useProject.getState().project?.root) return; + for (const previous of prompts ? usePluginRunTargets.getState().targets : []) { + if (!targets.some((t) => t.id === previous.id && t.prompt)) { + notifications().expire?.(`plugin-run-target:${previous.id}`); + shown.delete(`${root}\0${previous.id}`); + } + } + usePluginRunTargets.setState({ targets }); + if (!prompts) return; + for (const target of targets) { + const key = `${root}\0${target.id}`; + if (!target.prompt || shown.has(key)) continue; + shown.add(key); + const answer = async (use: boolean) => { + if (root !== useProject.getState().project?.root) return; + try { + const settings = await pluginsBackend().answerRunTarget(target.id, use); + if (root === useProject.getState().project?.root) useProject.setState({ settings }); + await refreshRunTargets(); + } catch (error) { + shown.delete(key); + notifications().notify({ group: "plugins", level: "error", title: "Run Targets", body: String(error) }); + } + }; + notifyTarget(target, answer); + } +} +function notifyTarget(target: RegisteredRunTarget, answer: (use: boolean) => Promise) { + notifications().notify({ + sticky: true, + group: "plugins", + key: `plugin-run-target:${target.id}`, + level: "info", + title: "Run Targets", + body: tx`Use ${target.target.name} for running PHP / Node / Composer in this project?`, + actions: [ + { label: "Use", run: () => void answer(true) }, + { label: "Not now", run: () => void answer(false) }, + ], + }); +} +export function startRunTargets(prompts = true): () => void { + if (isTauri()) void refreshRunTargets(prompts).catch(() => {}); + const unsubscribe = useProject.subscribe((s, old) => { + if (s.project?.root === old.project?.root) return; + clearTargets(prompts); + void refreshRunTargets(prompts).catch(() => {}); + }); + return () => { + unsubscribe(); + clearTargets(prompts); + }; +} diff --git a/src/features/plugins/runtimeUi.tsx b/src/features/plugins/runtimeUi.tsx index bf1322de5..787885c57 100644 --- a/src/features/plugins/runtimeUi.tsx +++ b/src/features/plugins/runtimeUi.tsx @@ -13,6 +13,7 @@ import { WASM_CONTENT_VIEW, } from "./views/contentTab"; import { create } from "zustand"; +import { refreshRunTargets, startRunTargets } from "./runTargets"; import type { CommitAnswer, CommandAnswer, @@ -474,6 +475,9 @@ async function answerCommand(e: Extract /** Handles the runtime UI events; returns whether `e` was one. */ export function handleRuntimeEvent(e: PluginEvent): boolean { switch (e.type) { + case "runTargetsChanged": + void refreshRunTargets().catch(() => {}); + return true; case "decorationsChanged": setPluginDecorations(e.pluginId, e.sets); return true; @@ -632,7 +636,13 @@ function refreshOnProjectChange(): () => void { export function startRuntimeUi(): () => void { const stopParser = providePluginTestParser((config, chunk) => pluginsBackend().parseTestResults(config, chunk)); - const disposers = [stopParser, projectStatusItems(), trackWorkbenchEvents(), refreshOnProjectChange()]; + const disposers = [ + startRunTargets(), + stopParser, + projectStatusItems(), + trackWorkbenchEvents(), + refreshOnProjectChange(), + ]; return () => disposers.reverse().forEach((d) => d()); } diff --git a/src/features/run/ConfigForm.tsx b/src/features/run/ConfigForm.tsx index 61989a47c..526dc760e 100644 --- a/src/features/run/ConfigForm.tsx +++ b/src/features/run/ConfigForm.tsx @@ -4,6 +4,7 @@ * Before launch list. */ import { isJvmApplication, parseJavaArgs } from "@/platform/javaLaunch"; +import { useRunTargets } from "@/platform/pluginRunTargets"; import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode, type RefObject } from "react"; import clsx from "clsx"; import { isTauri, type BeforeLaunchTask, type BuildPolicy, type RunConfig } from "@/platform/ipc"; @@ -45,7 +46,6 @@ import { import { gradleContainsModule } from "./gradleRun"; import { EnvDialog } from "./EnvDialog"; import { useBuildModel } from "@/platform/buildModel"; -import { withTarget } from "./remote"; import { COMPOUND, formParams, terminalApplies, withParams } from "./types"; import { TomcatSettings } from "./TomcatSettings"; import styles from "./Run.module.css"; @@ -243,7 +243,7 @@ function BrowseButton({ export function ConfigForm({ config, all, type, errors, template, onChange, modifyRequest }: ConfigFormProps) { const openByDefault = useWorkflowSettings((s) => s.run.showOnStart); const externalTools = useWorkflowSettings((s) => s.externalTools); - const runTargets = useWorkflowSettings((s) => s.runTargets); + const runTargets = useRunTargets(); const toolWindows = useContributions((s) => s.toolWindows); const tx = useTx(); const txTemplate = useTxTemplate(); @@ -383,6 +383,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi }); const targetOptions: SelectOption[] = [ + { value: "__default", label: "Default run target" }, { value: "", label: "Local machine" }, ...runTargets.map((t) => ({ value: t.id, label: t.name.trim() || t.id })), ]; @@ -446,9 +447,14 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi } > + + ); +} + export function NodePage() { const [pm, setPm] = useSetting("languages.node.packageManager"); const { list } = useDetected("packageManager"); @@ -103,6 +122,7 @@ export function NodePage() { aria-label="Node interpreter" hint="Runs npm scripts and Node-based language servers (vtsls, eslint, pyright…)." /> + + + {current && (
update({ name })} /> diff --git a/src/platform/languageSettings.ts b/src/platform/languageSettings.ts index f97105753..4eb1c669e 100644 --- a/src/platform/languageSettings.ts +++ b/src/platform/languageSettings.ts @@ -132,8 +132,9 @@ export interface ArtifactConfigValid { export interface LanguagesValid { python: { interpreter: string; activateVirtualenv: boolean }; ruby: { interpreter: string }; - node: { interpreter: string; packageManager: "" | "npm" | "pnpm" | "yarn" | "bun" }; + node: { runTarget: string; interpreter: string; packageManager: "" | "npm" | "pnpm" | "yarn" | "bun" }; php: { + runTarget: string; interpreter: string; languageLevel: (typeof PHP_LANGUAGE_LEVELS)[number]; includePaths: string[]; @@ -227,8 +228,8 @@ export type FolderListKey = export const DEFAULT_LANGUAGES: LanguagesValid = { python: { interpreter: "", activateVirtualenv: true }, ruby: { interpreter: "" }, - node: { interpreter: "", packageManager: "" }, - php: { interpreter: "", languageLevel: "", includePaths: [], stubs: [], phpstanConfig: "" }, + node: { runTarget: "", interpreter: "", packageManager: "" }, + php: { runTarget: "", interpreter: "", languageLevel: "", includePaths: [], stubs: [], phpstanConfig: "" }, rust: { toolchain: "", stdlib: "", checkOnSave: true, checkCommand: "check", rustfmtArgs: "" }, go: { goroot: "", gopath: "", buildTags: DEFAULT_GO_BUILD_TAGS, modules: { env: {}, autoVendor: true } }, typescript: { version: "bundled" }, @@ -350,10 +351,12 @@ export function validateLanguages(raw: unknown): LanguagesValid { }, ruby: { interpreter: text(ruby.interpreter, d.ruby.interpreter) }, node: { + runTarget: text(node.runTarget, ""), interpreter: text(node.interpreter, d.node.interpreter), packageManager: oneOf(node.packageManager, ["", "npm", "pnpm", "yarn", "bun"] as const, d.node.packageManager), }, php: { + runTarget: text(php.runTarget, ""), interpreter: text(php.interpreter, d.php.interpreter), languageLevel: oneOf(php.languageLevel, PHP_LANGUAGE_LEVELS, d.php.languageLevel), includePaths: strings(php.includePaths), diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index e7ac608cb..7307e2211 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -578,5 +578,12 @@ "Open Plugin Terminal Session": "Open Plugin Terminal Session", "Debug Plugin Configuration": "Debug Plugin Configuration", "Expected: {0}": "Expected: {0}", - "Actual: {0}": "Actual: {0}" + "Actual: {0}": "Actual: {0}", + "Use {0} for running PHP / Node / Composer in this project?": "Use {0} for running PHP / Node / Composer in this project?", + "Use": "Use", + "Not now": "Not now", + "Run in target": "Run in target", + "Run in target {0}": "Run in target {0}", + "Default run target": "Default run target", + "Read-only": "Read-only" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 992844821..0636a8726 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6921,5 +6921,11 @@ "Open Plugin Terminal Session": "打开插件终端会话", "Debug Plugin Configuration": "调试插件配置", "Expected: {0}": "期望值:{0}", - "Actual: {0}": "实际值:{0}" + "Actual: {0}": "实际值:{0}", + "Use {0} for running PHP / Node / Composer in this project?": "在此项目中使用 {0} 运行 PHP / Node / Composer?", + "Use": "使用", + "Not now": "暂不使用", + "Run in target": "在目标中运行", + "Run in target {0}": "在目标 {0} 中运行", + "Default run target": "默认运行目标" } diff --git a/src/platform/pluginRunTargets.ts b/src/platform/pluginRunTargets.ts new file mode 100644 index 000000000..d8c3d67d2 --- /dev/null +++ b/src/platform/pluginRunTargets.ts @@ -0,0 +1,24 @@ +/** Host-owned registrations shared by plugins, Run and Settings. */ +import { create } from "zustand"; +import { useMemo } from "react"; +import type { RegisteredRunTarget } from "@/bindings"; +import { DEFAULT_RUN_TARGET, type RunTargetValid } from "./remoteSettings"; +import { useWorkflowSettings, workflowSettings } from "./workflowSettings"; + +export const usePluginRunTargets = create<{ targets: RegisteredRunTarget[] }>(() => ({ targets: [] })); +export type RuntimeRunTarget = Omit & { kind: RunTargetValid["kind"] | "plugin" }; +const converted = (targets: RegisteredRunTarget[]): RuntimeRunTarget[] => + targets.map((t) => ({ + ...DEFAULT_RUN_TARGET, + kind: "plugin", + id: t.id, + name: `${t.target.name} (${t.pluginName})`, + })); +export function runTargets(): RuntimeRunTarget[] { + return [...workflowSettings().runTargets, ...converted(usePluginRunTargets.getState().targets)]; +} +export function useRunTargets(): RuntimeRunTarget[] { + const saved = useWorkflowSettings((s) => s.runTargets); + const plugins = usePluginRunTargets((s) => s.targets); + return useMemo(() => [...saved, ...converted(plugins)], [saved, plugins]); +} diff --git a/src/platform/remoteSettings.ts b/src/platform/remoteSettings.ts index b1576f629..75ad2fefe 100644 --- a/src/platform/remoteSettings.ts +++ b/src/platform/remoteSettings.ts @@ -243,7 +243,7 @@ let seq = 0; export const newRemoteId = (prefix: string) => `${prefix}-${Date.now().toString(36)}-${++seq}`; /** Whether `target` runs configurations in a container (Docker, Compose) rather than over SSH. */ -export const inContainer = (target: Pick) => target.kind !== "ssh"; +export const inContainer = (target: { kind: string }) => target.kind === "docker" || target.kind === "compose"; /** Backend connection descriptor for deployment and folder browsing. */ export function deploymentConnection(server: DeploymentServerValid): { kind: "local" } | { kind: "sftp"; ssh: string } { diff --git a/src/platform/runTargetSelection.ts b/src/platform/runTargetSelection.ts new file mode 100644 index 000000000..58ed19e3a --- /dev/null +++ b/src/platform/runTargetSelection.ts @@ -0,0 +1,24 @@ +import type { RunConfig } from "@/bindings"; +import { validateLanguages } from "./languageSettings"; +import { useProject } from "./project"; +import { workflowSettings } from "./workflowSettings"; + +/** Mirrors ide-sdk's interpreter target selection for guards before IPC launch. */ +export function withRunTarget(config: RunConfig): RunConfig { + if (config.target !== undefined && config.target !== null) return config; + const languages = validateLanguages(useProject.getState().settings?.languages); + const name = config.command + .split(/[\\/]/) + .at(-1) + ?.replace(/\.(exe|cmd|bat)$/i, ""); + const selected = + ["php", "composer", "phpunit", "pest"].includes(name ?? "") || ["php", "composer", "phpunit"].includes(config.kind) + ? languages.php.runTarget + : ["node", "npm", "npx", "pnpm", "yarn", "bun"].includes(name ?? "") || + ["node", "npm", "vitest", "jest", "mocha"].includes(config.kind) + ? languages.node.runTarget + : ""; + if (selected === "local") return { ...config, target: "" }; + const target = selected || workflowSettings().run.defaultTarget; + return target ? { ...config, target } : config; +} diff --git a/src/platform/workflowSettings.ts b/src/platform/workflowSettings.ts index 5e1caa97b..2c5a90138 100644 --- a/src/platform/workflowSettings.ts +++ b/src/platform/workflowSettings.ts @@ -95,6 +95,7 @@ export interface DebuggerSettingsValid { } export interface RunSettingsValid { + defaultTarget: string; confirmRerun: boolean; confirmTerminate: boolean; showOnStart: boolean; @@ -256,7 +257,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = { skipLibraryCode: true, python: { attachSubprocess: true, gevent: false }, }, - run: { confirmRerun: true, confirmTerminate: true, showOnStart: true, terminationTimeoutMs: 3000 }, + run: { defaultTarget: "", confirmRerun: true, confirmTerminate: true, showOnStart: true, terminationTimeoutMs: 3000 }, terminal: { startDirectory: "", env: {}, @@ -403,6 +404,7 @@ export function validateRun(raw: unknown): RunSettingsValid { const d = DEFAULT_WORKFLOW.run; const v = obj(raw); return { + defaultTarget: text(v.defaultTarget, ""), confirmRerun: bool(v.confirmRerun, d.confirmRerun), confirmTerminate: bool(v.confirmTerminate, d.confirmTerminate), showOnStart: bool(v.showOnStart, d.showOnStart), diff --git a/wit/plugin.wit b/wit/plugin.wit index 03312b0aa..ffe202a3f 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -33,6 +33,7 @@ world plugin { import command-runner; import views; import run; + import run-targets; import settings; export lifecycle; diff --git a/wit/run-targets.wit b/wit/run-targets.wit new file mode 100644 index 000000000..66a41e700 --- /dev/null +++ b/wit/run-targets.wit @@ -0,0 +1,36 @@ +package openidea:plugin@1.4.0; + +/// Project-scoped targets owned by the registering plugin (API 1.4). +interface run-targets { + use types.{error}; + use workspace.{project}; + + /// An argv wrapper using a granted, pinned process program. No shell is used. + /// Normally: program + args + workdir-args + command + command arguments. + /// An override matches wrap::program_name(command) and replaces args AND command: + /// program + override + workdir-args + command arguments. + /// DDEV: program="ddev", args=["exec"], commands=[("composer", ["composer"])]: + /// `ddev exec php x.php` and `ddev composer install`. + /// Each workdir-args element may contain {cwd}, mapped under container-root. + /// All workdir-args are omitted without container-root or for cwd outside the project. + /// Without workdir-args the wrapper manages its container directory itself. + /// The wrapper always starts in the configuration's LOCAL working directory. + /// Environment reaches the wrapper; forwarding into a container depends on its conventions. + /// Registration never selects the target. Debugging plugin targets is invalid. + record run-target { + id: string, + name: string, + program: string, + args: list, + workdir-args: list, + container-root: option, + commands: list>>, + } + + /// Registers/replaces this plugin's target in an open, trusted project. + /// Targets survive idle reclamation, and disappear on unregister or plugin stop. + /// Remote project registration and execution take place on the server. + register: func(project: borrow, target: run-target) -> result<_, error>; + /// Removes only this plugin's target from the project; missing ids are harmless. + unregister: func(project: borrow, id: string); +}