дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
feat(plugins): run configuration types with a plugin-provided form (#7445)
Plugins can contribute run configuration types (contributes.runConfigTypes, plugin API 1.20) whose settings form is rendered from the plugin's web view and prepared by the plugin. Every plugin-owned configuration, including ones the user creates from such a form, is launched by the host only after checking the plugin's process grant and executable pin; the debugger launch rechecks them, and Stop revalidates the executable. Tests cover user-created configurations and grant revocation. Co-authored-by: RuyimgByCN <[email protected]>
Цей коміт міститься в:
1 джерело
5c31ccfe70
коміт
7bfad25bb5
34 files changed
+2456
-210
No files matched your search
@@ -13,9 +13,13 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
/// Starts a session owned by this window: its events (and those of child sessions) go here only.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> IdeResult<DebugSessionId> {
|
||||
pub async fn debug_start(host: &Host, window: &str, mut config: LaunchConfig) -> IdeResult<DebugSessionId> {
|
||||
let project = host.project(window)?;
|
||||
project.require_trust()?;
|
||||
let plugin_run = take_plugin_run(&mut config)?;
|
||||
if let Some(run) = &plugin_run {
|
||||
verify_plugin_run(host, window, run, Some(&config.adapter)).await?;
|
||||
}
|
||||
let cancel = project.closed.child_token();
|
||||
let unity_pid = if config.adapter == "unity" {
|
||||
if config.request != "attach" {
|
||||
@@ -36,7 +40,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut config = config;
|
||||
let enhanced = take_enhanced_redefinition(&mut config);
|
||||
let executor = take_executor(&mut config);
|
||||
let java_exec = java_exec_path(&config);
|
||||
@@ -179,6 +182,9 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
return Err(ide_core::IdeError::cancelled());
|
||||
}
|
||||
host.require_trust(window)?;
|
||||
if let Some(run) = &plugin_run {
|
||||
verify_plugin_run(host, window, run, None).await?;
|
||||
}
|
||||
let server_port = debug_server_port(&config);
|
||||
let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port));
|
||||
let result = host.debugger.start_with_cancel(config, owner, custom, exception_classes, cancel).await;
|
||||
@@ -203,6 +209,36 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
result
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct PluginRun {
|
||||
config: ide_run::RunConfig,
|
||||
program: String,
|
||||
}
|
||||
|
||||
fn take_plugin_run(config: &mut LaunchConfig) -> IdeResult<Option<PluginRun>> {
|
||||
let Some(raw) = &config.extra_json else { return Ok(None) };
|
||||
if !raw.contains("__openideaPluginRun") {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut extra: serde_json::Map<String, serde_json::Value> =
|
||||
serde_json::from_str(raw).map_err(|e| ide_core::IdeError::invalid(e.to_string()))?;
|
||||
let Some(run) = extra.remove("__openideaPluginRun") else { return Ok(None) };
|
||||
extra.remove(ide_dap::native::ADAPTER_COMMAND);
|
||||
config.extra_json = Some(serde_json::Value::Object(extra).to_string());
|
||||
serde_json::from_value(run).map(Some).map_err(|e| ide_core::IdeError::invalid(e.to_string()))
|
||||
}
|
||||
|
||||
async fn verify_plugin_run(host: &Host, window: &str, run: &PluginRun, adapter: Option<&str>) -> IdeResult<()> {
|
||||
let denied = |message| ide_core::IdeError::new(ide_core::error::ErrorKind::PermissionDenied, message);
|
||||
let plugins = host.plugin_host().ok_or_else(|| denied("plugin host is not available"))?;
|
||||
let (window, config) = (window.to_owned(), run.config.clone());
|
||||
let checked = host.blocking(move || plugins.prepare_debug_run(&window, config)).await?;
|
||||
if checked.command != run.program || adapter.is_some_and(|name| checked.debug_adapter.as_deref() != Some(name)) {
|
||||
return Err(denied("plugin debug configuration changed before launch"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn native_debugger_command(
|
||||
root: &Path,
|
||||
settings: &ide_core::settings::CppDebuggerSettings,
|
||||
|
||||
@@ -373,28 +373,23 @@ async fn start_inner(
|
||||
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()
|
||||
{
|
||||
let provider = plugins.run_detection();
|
||||
let binary =
|
||||
provider.launch(&config).map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))?;
|
||||
config.command = if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
provider
|
||||
.detect(&project.root)
|
||||
.into_iter()
|
||||
.find(|c| c.id == config.id)
|
||||
.ok_or_else(|| IdeError::not_found("plugin configuration no longer available"))?
|
||||
.command
|
||||
} else {
|
||||
binary.to_string_lossy().into_owned()
|
||||
};
|
||||
config.detected = false;
|
||||
}
|
||||
let mut sink = project.sink.clone();
|
||||
let mut direct_stop = None;
|
||||
let mut plugin_authorized = false;
|
||||
if let Some(plugins) = host.plugin_host() {
|
||||
sink = plugins.run_operation_sink(window, &mut config, sink)?;
|
||||
let (next_sink, matched_op, op_stop) = plugins.run_operation_sink(window, &project.root, &mut config, sink)?;
|
||||
sink = next_sink;
|
||||
if matched_op {
|
||||
plugin_authorized = true;
|
||||
direct_stop = op_stop;
|
||||
}
|
||||
}
|
||||
if !plugin_authorized && let Some(owner) = crate::plugins::plugin_run_config_owner(&config)? {
|
||||
let plugins = host.plugin_host().ok_or_else(|| {
|
||||
IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "plugin host is not available")
|
||||
})?;
|
||||
direct_stop = plugins.authorize_run_config(&project.root, &owner, &mut config)?;
|
||||
plugin_authorized = true;
|
||||
}
|
||||
if let Some(agent) = agent {
|
||||
sink = agent.wrap_sink(sink);
|
||||
@@ -442,6 +437,8 @@ async fn start_inner(
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
direct_stop: None,
|
||||
plugin_authorized: true,
|
||||
},
|
||||
sink,
|
||||
Box::new(move |c| on_output(c)),
|
||||
@@ -473,6 +470,8 @@ async fn start_inner(
|
||||
plots: None,
|
||||
capture_junit_reports: false,
|
||||
conda_prefix: None,
|
||||
direct_stop: None,
|
||||
plugin_authorized,
|
||||
};
|
||||
project.require_trust()?;
|
||||
return host.processes.start(
|
||||
@@ -506,7 +505,7 @@ async fn start_inner(
|
||||
fallback.as_deref(),
|
||||
&settings,
|
||||
);
|
||||
} else {
|
||||
} else if !plugin_authorized {
|
||||
ide_sdk::apply::resolve_run_command(&mut config, root, &settings);
|
||||
}
|
||||
if config.kind == "go" {
|
||||
@@ -617,6 +616,8 @@ async fn start_inner(
|
||||
plots: if is_python { super::plots::prepare(host, &project).await } else { None },
|
||||
capture_junit_reports: config.is_test && config.extras.test_runner.as_deref() == Some("jvm"),
|
||||
conda_prefix,
|
||||
direct_stop,
|
||||
plugin_authorized,
|
||||
};
|
||||
project.require_trust()?;
|
||||
if config.kind == "go" && matches!(config.args.first().map(String::as_str), Some("mod" | "work")) {
|
||||
|
||||
@@ -591,30 +591,433 @@ impl PluginHost {
|
||||
}
|
||||
}
|
||||
|
||||
/// Owner of a plugin run configuration derived from its kind and/or id.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum PluginRunConfigOwner {
|
||||
/// A configuration created from `[[contributes.runConfigTypes]]` (`kind = "plugin:<plugin>:<typeId>"`).
|
||||
CustomType { plugin: String, type_id: String },
|
||||
/// A detected plugin configuration (or its saved override), with `kind = "plugin"` or a `plugin:` id.
|
||||
Detected { plugin: String, config_id: String },
|
||||
}
|
||||
|
||||
/// Identifies the owning plugin for any plugin-authored run configuration.
|
||||
pub(crate) fn plugin_run_config_owner(config: &ide_run::RunConfig) -> IdeResult<Option<PluginRunConfigOwner>> {
|
||||
if let Some(rest) = config.kind.strip_prefix(ide_run::EXTERNAL_PREFIX) {
|
||||
let Some((plugin, type_id)) = rest.split_once(':') else {
|
||||
return Err(IdeError::invalid("invalid plugin run configuration kind"));
|
||||
};
|
||||
if plugin.is_empty() || type_id.is_empty() || type_id.contains(':') {
|
||||
return Err(IdeError::invalid("invalid plugin run configuration kind"));
|
||||
}
|
||||
let raw_id = config
|
||||
.id
|
||||
.strip_prefix("workspace:")
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.map_or(config.id.as_str(), |(_, rest)| rest);
|
||||
if let Some(id_plugin) = raw_id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split(':').next())
|
||||
&& id_plugin != plugin
|
||||
{
|
||||
return Err(IdeError::invalid("plugin run configuration id does not match its kind"));
|
||||
}
|
||||
return Ok(Some(PluginRunConfigOwner::CustomType { plugin: plugin.into(), type_id: type_id.into() }));
|
||||
}
|
||||
let raw_id = config
|
||||
.id
|
||||
.strip_prefix("workspace:")
|
||||
.and_then(|s| s.split_once(':'))
|
||||
.map_or(config.id.as_str(), |(_, rest)| rest);
|
||||
if config.kind == "plugin" || raw_id.starts_with(ide_run::EXTERNAL_PREFIX) {
|
||||
if config.kind != "plugin" {
|
||||
return Err(IdeError::invalid("plugin detection id requires a plugin configuration kind"));
|
||||
}
|
||||
let Some((plugin, config_id)) = raw_id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split_once(':'))
|
||||
else {
|
||||
return Err(IdeError::invalid("invalid plugin run configuration"));
|
||||
};
|
||||
if plugin.is_empty() || config_id.is_empty() {
|
||||
return Err(IdeError::invalid("invalid plugin run configuration"));
|
||||
}
|
||||
return Ok(Some(PluginRunConfigOwner::Detected { plugin: plugin.into(), config_id: config_id.into() }));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn validate_plugin_program(program: &str) -> IdeResult<&str> {
|
||||
if program.is_empty()
|
||||
|| program.len() > 256
|
||||
|| program.chars().any(|c| c.is_whitespace() || c.is_control() || "|&;<>$`()".contains(c))
|
||||
|| (program.contains(['/', '\\']) && !std::path::Path::new(program).is_absolute())
|
||||
{
|
||||
return Err(IdeError::invalid(
|
||||
"plugin run configuration command must name a single program or approved executable",
|
||||
));
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
|
||||
fn validate_plugin_run_args(args: &[String]) -> IdeResult<()> {
|
||||
if args.len() > 256 || args.iter().any(|a| a.len() > 32768 || a.contains('\0')) {
|
||||
return Err(IdeError::invalid("invalid plugin run configuration arguments"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_loader_env(name: &str) -> bool {
|
||||
matches!(
|
||||
name.to_ascii_uppercase().as_str(),
|
||||
"LD_PRELOAD"
|
||||
| "LD_AUDIT"
|
||||
| "LD_LIBRARY_PATH"
|
||||
| "DYLD_INSERT_LIBRARIES"
|
||||
| "DYLD_LIBRARY_PATH"
|
||||
| "DYLD_FRAMEWORK_PATH"
|
||||
| "DYLD_FALLBACK_LIBRARY_PATH"
|
||||
| "DYLD_FALLBACK_FRAMEWORK_PATH"
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_plugin_run_env(env: &std::collections::BTreeMap<String, String>) -> IdeResult<()> {
|
||||
if env.len() > 64 {
|
||||
return Err(IdeError::invalid("at most 64 environment variables"));
|
||||
}
|
||||
for (name, value) in env {
|
||||
if name.is_empty() || name.len() > 256 || name.contains(['=', '\0']) || name.chars().any(char::is_whitespace) {
|
||||
return Err(IdeError::invalid(format!("{name:?} is not an environment variable name")));
|
||||
}
|
||||
if value.len() > 32768 || value.contains('\0') {
|
||||
return Err(IdeError::invalid(format!("the value of {name:?} is too long or holds a NUL")));
|
||||
}
|
||||
if inherited_env(name) || is_loader_env(name) {
|
||||
return Err(IdeError::invalid(format!(
|
||||
"environment variable {name:?} cannot override an inherited or loader variable"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_plugin_cwd(
|
||||
root: &std::path::Path,
|
||||
cwd: Option<&ide_core::IpcPath>,
|
||||
) -> IdeResult<Option<ide_core::IpcPath>> {
|
||||
let Some(path) = cwd.filter(|p| !p.as_os_str().is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let resolved = ide_plugin::resolve_in_root(root, &path.to_string_lossy()).map_err(IdeError::invalid)?;
|
||||
Ok(Some(resolved.into()))
|
||||
}
|
||||
|
||||
fn parse_plugin_stop_command(line: &str) -> IdeResult<(String, Vec<String>)> {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() || trimmed.len() > 4096 || trimmed.contains(['\0', '\r', '\n']) {
|
||||
return Err(IdeError::invalid("invalid plugin stop command"));
|
||||
}
|
||||
let mut tokens = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut in_token = false;
|
||||
let mut quote: Option<char> = None;
|
||||
let mut chars = trimmed.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match quote {
|
||||
Some('\'') => {
|
||||
if c == '\'' {
|
||||
quote = None;
|
||||
} else {
|
||||
current.push(c);
|
||||
}
|
||||
}
|
||||
Some('"') => {
|
||||
if c == '"' {
|
||||
quote = None;
|
||||
} else if c == '\\' {
|
||||
if let Some(&next) = chars.peek()
|
||||
&& matches!(next, '"' | '\\')
|
||||
{
|
||||
current.push(chars.next().unwrap());
|
||||
} else {
|
||||
current.push('\\');
|
||||
}
|
||||
} else {
|
||||
current.push(c);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if c.is_ascii_whitespace() {
|
||||
if in_token {
|
||||
tokens.push(std::mem::take(&mut current));
|
||||
in_token = false;
|
||||
}
|
||||
} else if c == '\'' || c == '"' {
|
||||
quote = Some(c);
|
||||
in_token = true;
|
||||
} else if c == '\\' {
|
||||
let Some(escaped) = chars.next() else {
|
||||
return Err(IdeError::invalid("plugin stop command has a trailing backslash"));
|
||||
};
|
||||
current.push(escaped);
|
||||
in_token = true;
|
||||
} else if "|&;<>$`()".contains(c) {
|
||||
return Err(IdeError::invalid(
|
||||
"plugin stop command must invoke a single executable without shell syntax",
|
||||
));
|
||||
} else {
|
||||
current.push(c);
|
||||
in_token = true;
|
||||
}
|
||||
}
|
||||
Some(_) => unreachable!(),
|
||||
}
|
||||
}
|
||||
if quote.is_some() {
|
||||
return Err(IdeError::invalid("plugin stop command has an unclosed quote"));
|
||||
}
|
||||
if in_token {
|
||||
tokens.push(current);
|
||||
}
|
||||
let Some((program, args)) = tokens.split_first() else {
|
||||
return Err(IdeError::invalid("plugin stop command has no program"));
|
||||
};
|
||||
let program = validate_plugin_program(program)?.to_owned();
|
||||
let args = args.to_vec();
|
||||
validate_plugin_run_args(&args)?;
|
||||
Ok((program, args))
|
||||
}
|
||||
|
||||
fn format_stop_display(program: &str, args: &[String]) -> String {
|
||||
let quote = |s: &str| {
|
||||
if !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || "-_./:=@,+".contains(c)) {
|
||||
s.to_owned()
|
||||
} else {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
};
|
||||
let mut out = quote(program);
|
||||
for arg in args {
|
||||
out.push(' ');
|
||||
out.push_str("e(arg));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn require_valid_debug_adapter(adapter: Option<String>) -> IdeResult<String> {
|
||||
let Some(adapter) = adapter.filter(|a| !a.is_empty()) else {
|
||||
return Err(IdeError::invalid("this configuration has no debugger"));
|
||||
};
|
||||
if adapter.len() > 128 || adapter.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return Err(IdeError::invalid("invalid debug adapter"));
|
||||
}
|
||||
Ok(adapter)
|
||||
}
|
||||
|
||||
impl PluginHost {
|
||||
fn authorize_plugin_stop(
|
||||
self: &Arc<Self>,
|
||||
plugin: &str,
|
||||
root: &std::path::Path,
|
||||
stop_command: Option<&str>,
|
||||
has_target: bool,
|
||||
) -> IdeResult<Option<ide_run::DirectStop>> {
|
||||
let Some(line) = stop_command.map(str::trim).filter(|s| !s.is_empty()) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if has_target {
|
||||
return Err(IdeError::invalid(
|
||||
"custom stop commands are not supported for plugin configurations on a run target",
|
||||
));
|
||||
}
|
||||
let (stop_program, stop_args) = parse_plugin_stop_command(line)?;
|
||||
let loaded = self.get(plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
let pinned = self.program_for_project(plugin, &stop_program, Some(root))?;
|
||||
let display = format_stop_display(&stop_program, &stop_args);
|
||||
let weak = Arc::downgrade(self);
|
||||
let plugin_id = plugin.to_owned();
|
||||
let program_name = stop_program;
|
||||
let project_root = root.to_path_buf();
|
||||
let verify: Arc<dyn Fn() -> Result<std::path::PathBuf, String> + Send + Sync> = Arc::new(move || {
|
||||
let Some(plugins) = weak.upgrade() else {
|
||||
return Err("plugin host is no longer available".into());
|
||||
};
|
||||
let loaded = plugins.get(&plugin_id).map_err(|e| e.to_string())?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(format!("plugin {plugin_id:?} is no longer enabled"));
|
||||
}
|
||||
plugins.program_for_project(&plugin_id, &program_name, Some(&project_root)).map_err(|e| e.to_string())
|
||||
});
|
||||
Ok(Some(ide_run::DirectStop { program: pinned, args: stop_args, display, verify: Some(verify) }))
|
||||
}
|
||||
|
||||
/// Authorizes a plugin-owned run configuration before `ProcessManager::start` (or remote target launch):
|
||||
/// requires the plugin to be live, checks its `process:` grant & executable pin, constrains env & cwd,
|
||||
/// and converts any `stop_command` into a shell-free re-verified [`ide_run::DirectStop`].
|
||||
pub(crate) fn authorize_run_config(
|
||||
self: &Arc<Self>,
|
||||
root: &std::path::Path,
|
||||
owner: &PluginRunConfigOwner,
|
||||
config: &mut ide_run::RunConfig,
|
||||
) -> IdeResult<Option<ide_run::DirectStop>> {
|
||||
if config.is_test && config.extras.emulate_terminal {
|
||||
return Err(IdeError::invalid("test configurations cannot emulate a terminal"));
|
||||
}
|
||||
let has_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
|
||||
let plugin = match owner {
|
||||
PluginRunConfigOwner::CustomType { plugin, type_id } => {
|
||||
let loaded = self.get(plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
if !self.ui.items(super::ui_points::RUN_CONFIG_TYPES, Some(plugin)).iter().any(|i| i.key == *type_id) {
|
||||
return Err(IdeError::not_found(format!(
|
||||
"plugin {plugin:?} does not declare run configuration type {type_id:?}"
|
||||
)));
|
||||
}
|
||||
let program = validate_plugin_program(&config.command)?.to_owned();
|
||||
validate_plugin_run_args(&config.args)?;
|
||||
validate_plugin_run_env(&config.env)?;
|
||||
if !has_target {
|
||||
config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?;
|
||||
}
|
||||
let binary = self.program_for_project(plugin, &program, Some(root))?;
|
||||
config.command = if has_target { program } else { binary.to_string_lossy().into_owned() };
|
||||
config.detected = false;
|
||||
plugin.as_str()
|
||||
}
|
||||
PluginRunConfigOwner::Detected { plugin, .. } => {
|
||||
if config.detected && config.id.starts_with(ide_run::EXTERNAL_PREFIX) {
|
||||
let provider = self.run_detection();
|
||||
let binary = provider
|
||||
.launch(config)
|
||||
.map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e))?;
|
||||
config.command = if has_target {
|
||||
provider
|
||||
.detect(root)
|
||||
.into_iter()
|
||||
.find(|c| c.id == config.id)
|
||||
.ok_or_else(|| IdeError::not_found("plugin configuration no longer available"))?
|
||||
.command
|
||||
} else {
|
||||
binary.to_string_lossy().into_owned()
|
||||
};
|
||||
config.detected = false;
|
||||
} else {
|
||||
let loaded = self.get(plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
let program = validate_plugin_program(&config.command)?.to_owned();
|
||||
validate_plugin_run_args(&config.args)?;
|
||||
validate_plugin_run_env(&config.env)?;
|
||||
if !has_target {
|
||||
config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?;
|
||||
}
|
||||
let binary = self.program_for_project(plugin, &program, Some(root))?;
|
||||
config.command = if has_target { program } else { binary.to_string_lossy().into_owned() };
|
||||
config.detected = false;
|
||||
}
|
||||
plugin.as_str()
|
||||
}
|
||||
};
|
||||
let stop = self.authorize_plugin_stop(plugin, root, config.extras.stop_command.as_deref(), has_target)?;
|
||||
config.extras.stop_command = None;
|
||||
Ok(stop)
|
||||
}
|
||||
|
||||
/// Rechecks the owned configuration's program before Debug and every IDE rerun.
|
||||
pub fn prepare_debug_run(&self, client: &str, mut config: ide_run::RunConfig) -> IdeResult<ide_run::RunConfig> {
|
||||
let Some((plugin, id)) = config.id.strip_prefix(ide_run::EXTERNAL_PREFIX).and_then(|s| s.split_once(':'))
|
||||
else {
|
||||
let Some(owner) = plugin_run_config_owner(&config)? else {
|
||||
return Err(IdeError::invalid("not a plugin configuration"));
|
||||
};
|
||||
let workspace = self.shared.workspace().ok_or_else(IdeError::cancelled)?;
|
||||
let owned = workspace.run_configuration(client, plugin, id).map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
if owned.debug_adapter.is_none() {
|
||||
return Err(IdeError::invalid("this configuration has no debugger"));
|
||||
let project_root = self.shared.project_of(client);
|
||||
match owner {
|
||||
PluginRunConfigOwner::Detected { plugin, config_id } => {
|
||||
let owned = workspace
|
||||
.run_configuration(client, &plugin, &config_id)
|
||||
.map_err(|e| IdeError::invalid(e.to_string()))?;
|
||||
let loaded = self.get(&plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
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"));
|
||||
}
|
||||
let adapter = require_valid_debug_adapter(config.debug_adapter.take().or(owned.debug_adapter))?;
|
||||
let pinned_owned = self.program_for_project(&plugin, &owned.command, project_root.as_deref());
|
||||
let program = if config.command.is_empty()
|
||||
|| config.command == owned.command
|
||||
|| pinned_owned.as_ref().is_ok_and(|p| std::path::Path::new(&config.command) == p.as_path())
|
||||
{
|
||||
owned.command
|
||||
} else {
|
||||
validate_plugin_program(&config.command)?.to_owned()
|
||||
};
|
||||
validate_plugin_run_args(&config.args)?;
|
||||
validate_plugin_run_env(&config.env)?;
|
||||
if let Some(root) = project_root.as_deref() {
|
||||
config.cwd = validate_plugin_cwd(root, config.cwd.as_ref())?;
|
||||
}
|
||||
config.command = self
|
||||
.program_for_project(&plugin, &program, project_root.as_deref())?
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
config.debug_adapter = Some(adapter);
|
||||
}
|
||||
PluginRunConfigOwner::CustomType { plugin, type_id } => {
|
||||
let root = project_root.ok_or_else(|| IdeError::invalid("no project in this window"))?;
|
||||
if !workspace.trusted(&root) {
|
||||
return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted"));
|
||||
}
|
||||
let loaded = self.get(&plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
let decl = self
|
||||
.ui
|
||||
.items(super::ui_points::RUN_CONFIG_TYPES, Some(&plugin))
|
||||
.into_iter()
|
||||
.find(|i| i.key == type_id)
|
||||
.ok_or_else(|| {
|
||||
IdeError::not_found(format!(
|
||||
"plugin {plugin:?} does not declare run configuration type {type_id:?}"
|
||||
))
|
||||
})?;
|
||||
if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
return Err(IdeError::invalid("debugging this target is not supported"));
|
||||
}
|
||||
let fallback_adapter = decl.decl.get("debugAdapter").and_then(|v| v.as_str()).map(str::to_owned);
|
||||
let adapter = require_valid_debug_adapter(config.debug_adapter.take().or(fallback_adapter))?;
|
||||
let program = validate_plugin_program(&config.command)?.to_owned();
|
||||
validate_plugin_run_args(&config.args)?;
|
||||
validate_plugin_run_env(&config.env)?;
|
||||
config.cwd = validate_plugin_cwd(&root, config.cwd.as_ref())?;
|
||||
config.command =
|
||||
self.program_for_project(&plugin, &program, Some(&root))?.to_string_lossy().into_owned();
|
||||
config.debug_adapter = Some(adapter);
|
||||
}
|
||||
}
|
||||
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"));
|
||||
}
|
||||
config.command = self
|
||||
.program_for_project(plugin, &owned.command, self.shared.project_of(client).as_deref())?
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
config.debug_adapter = owned.debug_adapter;
|
||||
config.extras.stop_command = None;
|
||||
config.extras.emulate_terminal = false;
|
||||
config.detected = false;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
@@ -671,10 +1074,13 @@ impl PluginHost {
|
||||
pub(crate) fn run_operation_sink(
|
||||
self: &Arc<Self>,
|
||||
client: &str,
|
||||
project_root: &std::path::Path,
|
||||
config: &mut ide_run::RunConfig,
|
||||
previous: Arc<dyn ide_core::EventSink>,
|
||||
) -> IdeResult<Arc<dyn ide_core::EventSink>> {
|
||||
let Some(id) = config.extras.params.get(RUN_OPERATION).cloned() else { return Ok(previous) };
|
||||
) -> IdeResult<(Arc<dyn ide_core::EventSink>, bool, Option<ide_run::DirectStop>)> {
|
||||
let Some(id) = config.extras.params.get(RUN_OPERATION).cloned() else {
|
||||
return Ok((previous, false, None));
|
||||
};
|
||||
let origin = self.shared.operations.lock().get(&id).and_then(|op| {
|
||||
if op.client != client {
|
||||
return None;
|
||||
@@ -682,16 +1088,39 @@ impl PluginHost {
|
||||
let OperationKind::Run { configuration, program, .. } = &op.kind else { return None };
|
||||
(configuration == &config.id).then(|| (op.plugin.clone(), op.root.clone(), program.clone()))
|
||||
});
|
||||
let Some((plugin, root, program)) = origin else { return Ok(previous) };
|
||||
let binary = self.program_for_project(&plugin, &program, root.as_deref())?;
|
||||
config.command = if config.extras.target.as_ref().is_some_and(|t| !t.is_empty()) {
|
||||
program
|
||||
} else {
|
||||
binary.to_string_lossy().into_owned()
|
||||
let Some((plugin, root, program)) = origin else {
|
||||
return Ok((previous, false, None));
|
||||
};
|
||||
if !matches!(plugin_run_config_owner(config)?, Some(PluginRunConfigOwner::Detected { plugin: owner, .. }) if owner == plugin)
|
||||
|| root.as_deref().is_some_and(|root| root != project_root)
|
||||
{
|
||||
return Err(IdeError::invalid("plugin operation does not match its run configuration"));
|
||||
}
|
||||
let loaded = self.get(&plugin)?;
|
||||
if !loaded.status().is_live() {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
format!("plugin {plugin:?} is not enabled"),
|
||||
));
|
||||
}
|
||||
let has_target = config.extras.target.as_deref().is_some_and(|t| !t.is_empty());
|
||||
validate_plugin_run_args(&config.args)?;
|
||||
validate_plugin_run_env(&config.env)?;
|
||||
if !has_target {
|
||||
config.cwd = validate_plugin_cwd(project_root, config.cwd.as_ref())?;
|
||||
}
|
||||
let binary = self.program_for_project(&plugin, &program, root.as_deref())?;
|
||||
config.command = if has_target { program } else { binary.to_string_lossy().into_owned() };
|
||||
config.detected = false;
|
||||
let stop = self.authorize_plugin_stop(
|
||||
&plugin,
|
||||
root.as_deref().unwrap_or(project_root),
|
||||
config.extras.stop_command.as_deref(),
|
||||
has_target,
|
||||
)?;
|
||||
config.extras.stop_command = None;
|
||||
let (weak, client) = (Arc::downgrade(self), client.to_owned());
|
||||
Ok(Arc::new(move |event: ide_core::IdeEvent| {
|
||||
let wrapped = Arc::new(move |event: ide_core::IdeEvent| {
|
||||
if let ide_core::IdeEvent::RunExited { code, .. } = &event
|
||||
&& let Some(plugins) = weak.upgrade()
|
||||
{
|
||||
@@ -699,7 +1128,8 @@ impl PluginHost {
|
||||
plugins.finish_operation(&client, &id, *code, stopped);
|
||||
}
|
||||
previous.emit(event);
|
||||
}))
|
||||
});
|
||||
Ok((wrapped, true, stop))
|
||||
}
|
||||
pub(crate) fn run_operation_started(&self, client: &str, operation: &str, run: ide_core::RunId) {
|
||||
if let Some(op) = self
|
||||
@@ -821,4 +1251,39 @@ mod tests {
|
||||
c.output_mode = ide_plugin::PluginOutputMode::Pipes;
|
||||
assert!(validate_configurations(&root, &[c]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_stop_command_parser_rejects_shell_syntax() {
|
||||
assert_eq!(parse_plugin_stop_command("catalina stop").unwrap(), ("catalina".into(), vec!["stop".into()]));
|
||||
assert_eq!(
|
||||
parse_plugin_stop_command(r#""/opt/tomcat/bin/catalina" stop --force 'now'"#).unwrap(),
|
||||
("/opt/tomcat/bin/catalina".into(), vec!["stop".into(), "--force".into(), "now".into()])
|
||||
);
|
||||
for bad in [
|
||||
"",
|
||||
" ",
|
||||
"tool; touch /tmp/x",
|
||||
"tool | cat",
|
||||
"tool && id",
|
||||
"tool $(id)",
|
||||
"tool `id`",
|
||||
"tool > out.txt",
|
||||
"tool\nrm -rf /",
|
||||
"./bin/tool stop",
|
||||
"\"unclosed stop",
|
||||
] {
|
||||
assert!(parse_plugin_stop_command(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_run_env_rejects_inherited_and_loader_vars() {
|
||||
use std::collections::BTreeMap;
|
||||
assert!(validate_plugin_run_env(&BTreeMap::from([("APP_PORT".into(), "8080".into())])).is_ok());
|
||||
for bad in ["LD_PRELOAD", "ld_library_path", "DYLD_INSERT_LIBRARIES", "DYLD_LIBRARY_PATH"] {
|
||||
assert!(validate_plugin_run_env(&BTreeMap::from([(bad.into(), "/tmp/evil.so".into())])).is_err(), "{bad}");
|
||||
}
|
||||
let (inherited, _) = std::env::vars().next().expect("inherited env");
|
||||
assert!(validate_plugin_run_env(&BTreeMap::from([(inherited, "x".into())])).is_err());
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,7 @@ mod websocket;
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub use docs::{MAX_PLUGIN_DOC, PluginDocs, explain_capabilities, plugin_docs};
|
||||
pub(crate) use execution::plugin_run_config_owner;
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
MAX_PLUGIN_ICON, map_asset as icon_theme_map_asset, plugin_icon, sanitize_svg, svg_prefix as icon_theme_svg_prefix,
|
||||
|
||||
@@ -97,6 +97,7 @@ pub fn register_builtin_points(
|
||||
registry.register(Arc::new(UiPoint::new(p::EDITOR_PANELS, ui.clone(), p::editor_panel)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::OVERLAYS, ui.clone(), p::overlay)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::DIALOGS, ui.clone(), p::dialog)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_CONFIG_TYPES, ui.clone(), p::run_config_type)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::RUN_ANYTHING, ui.clone(), p::run_anything)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::MARKER_ICONS, ui.clone(), p::marker_icon)))?;
|
||||
registry.register(Arc::new(UiPoint::new(p::FILE_ICONS, ui.clone(), p::file_icon)))?;
|
||||
|
||||
@@ -62,6 +62,11 @@
|
||||
//! width = 900 # pixels, 320–1600
|
||||
//! height = 600 # pixels, 200–1200
|
||||
//!
|
||||
//! [[contributes.runConfigTypes]]
|
||||
//! id = "tomcat"
|
||||
//! label = "SmartTomcat" # shown in Add New Configuration and Edit Configurations
|
||||
//! web = "web/run-config.html" # custom Run/Debug Configurations form (API 1.20)
|
||||
//!
|
||||
//! [[contributes.fileIcons]]
|
||||
//! id = "drawing"
|
||||
//! patterns = ["*.excalidraw"]
|
||||
@@ -102,9 +107,10 @@ pub const CUSTOM_EDITORS: &str = "customEditors";
|
||||
pub const EDITOR_PANELS: &str = "editorPanels";
|
||||
pub const OVERLAYS: &str = "overlays";
|
||||
pub const DIALOGS: &str = "dialogs";
|
||||
pub const RUN_CONFIG_TYPES: &str = "runConfigTypes";
|
||||
pub const RUN_ANYTHING: &str = "runAnything";
|
||||
/// The points whose declarations can name a `web` page (served, messaged, sent view events).
|
||||
pub const WEB_POINTS: [&str; 5] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS];
|
||||
pub const WEB_POINTS: [&str; 6] = [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS, RUN_CONFIG_TYPES];
|
||||
pub const FILE_ICONS: &str = "fileIcons";
|
||||
pub const MARKER_ICONS: &str = "markerIcons";
|
||||
pub const FILE_TEMPLATES: &str = "fileTemplates";
|
||||
@@ -1031,6 +1037,154 @@ pub(super) fn dialog(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String>
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn is_false(b: &bool) -> bool {
|
||||
!*b
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct RunConfigTypeDecl {
|
||||
id: String,
|
||||
label: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
description: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
group: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
icon_dark: Option<String>,
|
||||
web: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
layout: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
height: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
command: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
debug_adapter: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
terminal: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
owns_working_directory: bool,
|
||||
#[serde(default, skip_serializing_if = "is_false")]
|
||||
owns_environment: bool,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
prepare_command: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
match_config_prefix: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
defaults: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
const RUN_CONFIG_HEIGHT: std::ops::RangeInclusive<u32> = 120..=1200;
|
||||
|
||||
/// `[[contributes.runConfigTypes]]` (API 1.20): a custom Run/Debug Configurations
|
||||
/// form rendered by a package web page (`openidea.runConfig`).
|
||||
pub(super) fn run_config_type(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
|
||||
let d: RunConfigTypeDecl = decode(RUN_CONFIG_TYPES, decl)?;
|
||||
pkg.manifest.needs_api(&format!("contributes.{RUN_CONFIG_TYPES}"), 20)?;
|
||||
validate_item_id(&d.id, "run config type id")?;
|
||||
let what = format!("run config type {:?}", d.id);
|
||||
for point in [VIEWS, CUSTOM_EDITORS, EDITOR_PANELS, OVERLAYS, DIALOGS] {
|
||||
if pkg.manifest.declarations(point).iter().any(|v| v.get("id").and_then(|i| i.as_str()) == Some(&d.id)) {
|
||||
return Err(format!("{what}: {point} already declares the same id"));
|
||||
}
|
||||
}
|
||||
if d.label.trim().is_empty() || d.label.len() > MAX_TITLE {
|
||||
return Err(format!("{what}: `label` is 1–{MAX_TITLE} bytes"));
|
||||
}
|
||||
if let Some(desc) = &d.description
|
||||
&& (desc.trim().is_empty() || desc.len() > MAX_TITLE)
|
||||
{
|
||||
return Err(format!("{what}: `description` is 1–{MAX_TITLE} bytes"));
|
||||
}
|
||||
if let Some(group) = &d.group
|
||||
&& (group.trim().is_empty() || group.len() > 128)
|
||||
{
|
||||
return Err(format!("{what}: `group` is 1–128 bytes"));
|
||||
}
|
||||
if let Some(layout) = &d.layout
|
||||
&& layout != "embedded"
|
||||
&& layout != "full"
|
||||
{
|
||||
return Err(format!("{what}: `layout` is embedded or full"));
|
||||
}
|
||||
if let Some(height) = d.height
|
||||
&& !RUN_CONFIG_HEIGHT.contains(&height)
|
||||
{
|
||||
return Err(format!("{what}: `height` is {}–{} pixels", RUN_CONFIG_HEIGHT.start(), RUN_CONFIG_HEIGHT.end()));
|
||||
}
|
||||
if let Some(cmd) = &d.command {
|
||||
let trimmed = cmd.trim();
|
||||
if trimmed != cmd
|
||||
|| trimmed.is_empty()
|
||||
|| trimmed.len() > 256
|
||||
|| trimmed.chars().any(|c| c.is_whitespace() || c.is_control() || "|&;<>$`()".contains(c))
|
||||
|| (trimmed.contains(['/', '\\']) && !Path::new(trimmed).is_absolute())
|
||||
{
|
||||
return Err(format!(
|
||||
"{what}: `command` must be a 1–256 byte program name or absolute path without whitespace or shell syntax"
|
||||
));
|
||||
}
|
||||
}
|
||||
if !d.args.is_empty() && d.command.is_none() {
|
||||
return Err(format!("{what}: `args` requires `command`"));
|
||||
}
|
||||
if d.args.len() > 64 || d.args.iter().any(|a| a.len() > 4096 || a.contains('\0')) {
|
||||
return Err(format!("{what}: at most 64 arguments of up to 4096 bytes without NUL"));
|
||||
}
|
||||
if let Some(adapter) = &d.debug_adapter
|
||||
&& (adapter.is_empty() || adapter.len() > 128 || adapter.chars().any(|c| c.is_whitespace() || c == '\0'))
|
||||
{
|
||||
return Err(format!("{what}: `debugAdapter` is 1–128 bytes without whitespace"));
|
||||
}
|
||||
if let Some(cmd) = &d.prepare_command {
|
||||
declared_command(pkg, RUN_CONFIG_TYPES, cmd)?;
|
||||
}
|
||||
if let Some(prefix) = &d.match_config_prefix
|
||||
&& (prefix.len() > 128 || prefix.contains('\0'))
|
||||
{
|
||||
return Err(format!("{what}: `matchConfigPrefix` is up to 128 bytes without NUL"));
|
||||
}
|
||||
if d.defaults.len() > 64
|
||||
|| d.defaults
|
||||
.iter()
|
||||
.any(|(k, v)| k.is_empty() || k.len() > 128 || k.contains('\0') || v.len() > 16384 || v.contains('\0'))
|
||||
{
|
||||
return Err(format!("{what}: `defaults` allows at most 64 entries"));
|
||||
}
|
||||
|
||||
let mut files = super::web::web_files(pkg, &d.web, &what)?;
|
||||
let mut assets = Vec::new();
|
||||
if let Some(icon) = &d.icon {
|
||||
if icon.ends_with(".svg") {
|
||||
let path = PathBuf::from(icon);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
files.push(path);
|
||||
assets.push((format!("runConfigIcon/{}", d.id), svg));
|
||||
} else if icon.trim().is_empty() || icon.len() > 128 || icon.chars().any(char::is_control) {
|
||||
return Err(format!("{what}: `icon` is 1–128 bytes without controls"));
|
||||
}
|
||||
}
|
||||
if let Some(dark) = &d.icon_dark {
|
||||
if !d.icon.as_deref().is_some_and(|i| i.ends_with(".svg")) || !dark.ends_with(".svg") {
|
||||
return Err(format!("{what}: `iconDark` requires an .svg `icon` and an .svg path"));
|
||||
}
|
||||
let path = PathBuf::from(dark);
|
||||
let svg = super::icons::read_icon(pkg, &path, super::icons::MAX_SVG)?;
|
||||
files.push(path);
|
||||
assets.push((format!("runConfigIconDark/{}", d.id), svg));
|
||||
}
|
||||
|
||||
let mut out = UiDecl::new(d.id.clone(), d.label.clone(), json(&d)?);
|
||||
out.files = files;
|
||||
out.assets = assets;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct FileIconDecl {
|
||||
@@ -1853,6 +2007,96 @@ modal = false",
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_config_types_validate_api_fields_icons_and_collisions() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("web")).unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("icons")).unwrap();
|
||||
std::fs::write(dir.path().join("web/form.html"), "<form></form>").unwrap();
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M0 0h16v16H0z"/></svg>"#;
|
||||
std::fs::write(dir.path().join("icons/tomcat.svg"), svg).unwrap();
|
||||
std::fs::write(dir.path().join("icons/tomcat_dark.svg"), svg).unwrap();
|
||||
|
||||
let minimal = r#"id = "acme.tomcat"
|
||||
name = "Tomcat"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.20"
|
||||
|
||||
[[contributes.runConfigTypes]]
|
||||
id = "smart-tomcat"
|
||||
label = "SmartTomcat"
|
||||
web = "web/form.html"
|
||||
"#;
|
||||
let check = |source: &str| {
|
||||
let manifest = ide_extension::Manifest::parse(source)?;
|
||||
let decl = manifest.declarations(RUN_CONFIG_TYPES).into_iter().next().unwrap();
|
||||
run_config_type(&Package::new(manifest, dir.path().to_path_buf()), decl)
|
||||
};
|
||||
|
||||
let valid = check(minimal).unwrap();
|
||||
assert_eq!((valid.key.as_str(), valid.label.as_str()), ("smart-tomcat", "SmartTomcat"));
|
||||
assert_eq!(valid.files, [PathBuf::from("web/form.html")]);
|
||||
assert!(valid.assets.is_empty());
|
||||
|
||||
let full = format!(
|
||||
"{minimal}\
|
||||
description = \"Local Tomcat runner\"\n\
|
||||
group = \"Servers\"\n\
|
||||
icon = \"icons/tomcat.svg\"\n\
|
||||
iconDark = \"icons/tomcat_dark.svg\"\n\
|
||||
layout = \"full\"\n\
|
||||
height = 420\n\
|
||||
command = \"java\"\n\
|
||||
args = [\"-jar\", \"bootstrap.jar\"]\n\
|
||||
debugAdapter = \"java-debug\"\n\
|
||||
terminal = false\n\
|
||||
ownsWorkingDirectory = true\n\
|
||||
ownsEnvironment = true\n\
|
||||
prepareCommand = \"prepare\"\n\
|
||||
matchConfigPrefix = \"smart-tomcat:\"\n\
|
||||
defaults = {{ httpPort = \"8080\" }}\n\
|
||||
\n\
|
||||
[[contributes.commands]]\n\
|
||||
id = \"prepare\"\n\
|
||||
title = \"Prepare\"\n"
|
||||
);
|
||||
let valid_full = check(&full).unwrap();
|
||||
assert_eq!(valid_full.json["layout"], "full");
|
||||
assert_eq!(valid_full.json["height"], 420);
|
||||
assert_eq!(valid_full.json["ownsWorkingDirectory"], true);
|
||||
assert_eq!(valid_full.json["ownsEnvironment"], true);
|
||||
assert_eq!(valid_full.json["defaults"]["httpPort"], "8080");
|
||||
assert_eq!(
|
||||
valid_full.assets.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(),
|
||||
["runConfigIcon/smart-tomcat", "runConfigIconDark/smart-tomcat"]
|
||||
);
|
||||
|
||||
for (bad, error) in [
|
||||
(minimal.replace("^1.20", "^1.19"), "1.20"),
|
||||
(minimal.replace(r#"label = "SmartTomcat""#, r#"label = " ""#), "`label`"),
|
||||
(format!("{minimal}layout = \"modal\"\n"), "`layout`"),
|
||||
(format!("{minimal}height = 119\n"), "120–1200"),
|
||||
(format!("{minimal}height = 1201\n"), "120–1200"),
|
||||
(format!("{minimal}args = [\"--port\"]\n"), "requires `command`"),
|
||||
(format!("{minimal}command = \"java -jar\"\n"), "`command`"),
|
||||
(format!("{minimal}command = \"./bin/tool\"\n"), "`command`"),
|
||||
(format!("{minimal}prepareCommand = \"missing\"\n"), "not declared"),
|
||||
(format!("{minimal}icon = \"terminal\"\niconDark = \"icons/tomcat_dark.svg\"\n"), "`iconDark`"),
|
||||
(format!("{minimal}defaults = {{ \"\" = \"1\" }}\n"), "`defaults`"),
|
||||
(minimal.replace("web/form.html", "web/missing.html"), "no such file"),
|
||||
(format!("{minimal}\n[[contributes.views]]\nid = \"smart-tomcat\"\ntitle = \"V\"\n"), "already declares"),
|
||||
(
|
||||
format!(
|
||||
"{minimal}\n[[contributes.dialogs]]\nid = \"smart-tomcat\"\ntitle = \"D\"\nweb = \"web/form.html\"\nwidth = 400\nheight = 300\n"
|
||||
),
|
||||
"already declares",
|
||||
),
|
||||
] {
|
||||
let err = check(&bad).unwrap_err();
|
||||
assert!(err.contains(error), "{bad}\n→ {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_anything_validates_api_prefix_title_and_code() {
|
||||
let source = "id = \"go\"\nname = \"Go\"\nversion = \"0.1.0\"\nengines.openidea = \"^1.18\"\nwasm = \"p.wasm\"\n\n[[contributes.runAnything]]\nprefix = \"task\"\n";
|
||||
|
||||
@@ -919,3 +919,257 @@ async fn run_target_validation_gates_launches_and_preserves_selection() {
|
||||
);
|
||||
plugins.shutdown();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn plugin_run_config_types_enforce_process_grants_for_run_debug_and_stop() {
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost};
|
||||
use ide_plugin::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::default(),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
plugins.set_workspace(Some(Arc::new(f.workspace())));
|
||||
f.host.set_plugin_host(&plugins);
|
||||
|
||||
let pkg = f._tmp.path().join("custom-run-plugin");
|
||||
std::fs::create_dir_all(pkg.join("web")).unwrap();
|
||||
std::fs::write(pkg.join("web/form.html"), "<form></form>").unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
r#"id = "run-form-test"
|
||||
name = "Run Form Test"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.20"
|
||||
|
||||
[capabilities]
|
||||
optional = ["process:custom-tool", "process:custom-stop"]
|
||||
|
||||
[[contributes.runConfigTypes]]
|
||||
id = "custom"
|
||||
label = "Custom Tool"
|
||||
web = "web/form.html"
|
||||
debugAdapter = "debugpy"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
plugins.install_from_dir(&pkg, &Consent::default()).unwrap();
|
||||
|
||||
let tool = f._tmp.path().join("custom-tool-bin");
|
||||
std::fs::write(
|
||||
&tool,
|
||||
"#!/bin/sh\nif [ \"$1\" = \"--sleep\" ]; then\n echo \"sleeping\"\n sleep 30\n exit 0\nfi\necho \"pinned-custom-tool:$1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let stop_tool = f._tmp.path().join("custom-stop-bin");
|
||||
std::fs::write(&stop_tool, "#!/bin/sh\nprintf 'stopped' > \"$1\"\n").unwrap();
|
||||
std::fs::set_permissions(&stop_tool, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
|
||||
let make_config = |command: &str, stop_command: Option<&str>| ide_run::RunConfig {
|
||||
id: "user:custom-1".into(),
|
||||
name: "Custom Tool".into(),
|
||||
kind: "plugin:run-form-test:custom".into(),
|
||||
command: command.into(),
|
||||
args: vec!["--hello".into()],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: Some("debugpy".into()),
|
||||
allow_parallel: false,
|
||||
extras: ide_run::RunExtras { stop_command: stop_command.map(str::to_owned), ..Default::default() },
|
||||
};
|
||||
|
||||
// 1. Without `process:custom-tool` granted: Run, Debug, and saved overrides are all refused.
|
||||
let ungranted = make_config("custom-tool", None);
|
||||
let err =
|
||||
ide_host::ops::run::run_start(&f.host, "main", ungranted.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied, "{err}");
|
||||
|
||||
let shell_err = ide_host::ops::run::run_start(
|
||||
&f.host,
|
||||
"main",
|
||||
make_config("/bin/sh", None),
|
||||
ide_host::ops::Channel::new(|_| {}),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(shell_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{shell_err}");
|
||||
|
||||
let dbg_err = plugins.prepare_debug_run("main", ungranted.clone()).unwrap_err();
|
||||
assert_eq!(dbg_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{dbg_err}");
|
||||
let debug_launch = |program: &std::path::Path| ide_dap::LaunchConfig {
|
||||
name: ungranted.name.clone(),
|
||||
adapter: "debugpy".into(),
|
||||
request: "launch".into(),
|
||||
program: None,
|
||||
args: vec![],
|
||||
cwd: Some(f.root.clone().into()),
|
||||
env: Default::default(),
|
||||
extra_json: Some(
|
||||
serde_json::json!({ "__openideaPluginRun": { "config": ungranted, "program": program } }).to_string(),
|
||||
),
|
||||
};
|
||||
|
||||
let malformed = ide_run::RunConfig { kind: "plugin:run-form-test".into(), ..ungranted.clone() };
|
||||
assert!(
|
||||
ide_host::ops::run::run_start(&f.host, "main", malformed.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(plugins.prepare_debug_run("main", malformed).is_err());
|
||||
|
||||
let unknown_type = ide_run::RunConfig { kind: "plugin:run-form-test:missing".into(), ..ungranted.clone() };
|
||||
assert!(
|
||||
ide_host::ops::run::run_start(&f.host, "main", unknown_type.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(plugins.prepare_debug_run("main", unknown_type).is_err());
|
||||
|
||||
let saved_detected = ide_run::RunConfig {
|
||||
id: "plugin:run-form-test:saved".into(),
|
||||
kind: "plugin".into(),
|
||||
detected: false,
|
||||
..ungranted.clone()
|
||||
};
|
||||
let saved_err =
|
||||
ide_host::ops::run::run_start(&f.host, "main", saved_detected, ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(saved_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{saved_err}");
|
||||
|
||||
// 2. Grant & pin `process:custom-tool`: Run and Debug resolve the pinned executable,
|
||||
// while env/cwd escapes are still rejected.
|
||||
plugins.choose_program("run-form-test", "process:custom-tool", Some(&f.root), Some(&tool)).unwrap();
|
||||
let canonical_tool = dunce::canonicalize(&tool).unwrap();
|
||||
|
||||
let output = Arc::new(parking_lot::Mutex::new(String::new()));
|
||||
let captured = output.clone();
|
||||
let run = ide_host::ops::run::run_start(
|
||||
&f.host,
|
||||
"main",
|
||||
ungranted.clone(),
|
||||
ide_host::ops::Channel::new(move |chunk| {
|
||||
if let ide_run::OutputChunk::Stdout { text } = chunk {
|
||||
captured.lock().push_str(&text);
|
||||
}
|
||||
}),
|
||||
None,
|
||||
)
|
||||
.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;
|
||||
}
|
||||
assert!(output.lock().contains("pinned-custom-tool:--hello"), "{}", output.lock());
|
||||
|
||||
let prepared_dbg = plugins.prepare_debug_run("main", ungranted.clone()).unwrap();
|
||||
assert_eq!(std::path::Path::new(&prepared_dbg.command), canonical_tool);
|
||||
assert_eq!(prepared_dbg.debug_adapter.as_deref(), Some("debugpy"));
|
||||
|
||||
let mut bad_env = ungranted.clone();
|
||||
bad_env.env.insert("LD_PRELOAD".into(), "/tmp/evil.so".into());
|
||||
assert!(
|
||||
ide_host::ops::run::run_start(&f.host, "main", bad_env.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(plugins.prepare_debug_run("main", bad_env).is_err());
|
||||
|
||||
let outside_dir = f._tmp.path().join("outside");
|
||||
std::fs::create_dir_all(&outside_dir).unwrap();
|
||||
let mut bad_cwd = ungranted.clone();
|
||||
bad_cwd.cwd = Some(outside_dir.into());
|
||||
assert!(
|
||||
ide_host::ops::run::run_start(&f.host, "main", bad_cwd.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(plugins.prepare_debug_run("main", bad_cwd).is_err());
|
||||
|
||||
// 3. Stop command enforcement: requires grant, rejects shell syntax, and re-checks grant at Stop time.
|
||||
let ungranted_stop = make_config("custom-tool", Some("custom-stop marker.txt"));
|
||||
let stop_err =
|
||||
ide_host::ops::run::run_start(&f.host, "main", ungranted_stop, ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(stop_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{stop_err}");
|
||||
|
||||
let shell_stop = make_config("custom-tool", Some("custom-tool; touch evil"));
|
||||
let shell_stop_err =
|
||||
ide_host::ops::run::run_start(&f.host, "main", shell_stop, ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(shell_stop_err.kind, ide_core::error::ErrorKind::InvalidInput, "{shell_stop_err}");
|
||||
|
||||
plugins.choose_program("run-form-test", "process:custom-stop", Some(&f.root), Some(&stop_tool)).unwrap();
|
||||
let mut sleep_cfg = make_config("custom-tool", Some("custom-stop stopped.txt"));
|
||||
sleep_cfg.args = vec!["--sleep".into()];
|
||||
let sleep_run =
|
||||
ide_host::ops::run::run_start(&f.host, "main", sleep_cfg, ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
ide_host::ops::run::run_stop(&f.host, "main", sleep_run.id).unwrap();
|
||||
for _ in 0..100 {
|
||||
if f.host.processes.list().iter().any(|r| r.id == sleep_run.id && !r.running) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(f.host.processes.list().iter().any(|r| r.id == sleep_run.id && !r.running));
|
||||
assert_eq!(std::fs::read_to_string(f.root.join("stopped.txt")).unwrap(), "stopped");
|
||||
|
||||
// Revoking `process:custom-stop` after Start prevents the stop command from running on Stop.
|
||||
let mut revoked_stop_cfg = make_config("custom-tool", Some("custom-stop revoked.txt"));
|
||||
revoked_stop_cfg.args = vec!["--sleep".into()];
|
||||
let revoked_run =
|
||||
ide_host::ops::run::run_start(&f.host, "main", revoked_stop_cfg, ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap();
|
||||
plugins.set_capability("run-form-test", "process:custom-stop", false).unwrap();
|
||||
ide_host::ops::run::run_stop(&f.host, "main", revoked_run.id).unwrap();
|
||||
for _ in 0..100 {
|
||||
if f.host.processes.list().iter().any(|r| r.id == revoked_run.id && !r.running) {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
|
||||
}
|
||||
assert!(f.host.processes.list().iter().any(|r| r.id == revoked_run.id && !r.running));
|
||||
assert!(!f.root.join("revoked.txt").exists());
|
||||
|
||||
// 4. Revoking `process:custom-tool` immediately blocks subsequent Run and Debug launches.
|
||||
plugins.set_capability("run-form-test", "process:custom-tool", false).unwrap();
|
||||
let debug_err =
|
||||
ide_host::ops::debug::debug_start(&f.host, "main", debug_launch(&canonical_tool)).await.unwrap_err();
|
||||
assert_eq!(debug_err.kind, ide_core::error::ErrorKind::PermissionDenied, "{debug_err}");
|
||||
assert_eq!(
|
||||
ide_host::ops::run::run_start(&f.host, "main", ungranted.clone(), ide_host::ops::Channel::new(|_| {}), None)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
ide_core::error::ErrorKind::PermissionDenied
|
||||
);
|
||||
assert_eq!(
|
||||
plugins.prepare_debug_run("main", ungranted).unwrap_err().kind,
|
||||
ide_core::error::ErrorKind::PermissionDenied
|
||||
);
|
||||
|
||||
plugins.shutdown();
|
||||
}
|
||||
@@ -8187,3 +8187,80 @@ fn restricting_a_project_without_its_plugins_announces_nothing() {
|
||||
host.restrict_project(tmp.path());
|
||||
assert!(!events.lock().iter().any(|(_, e)| matches!(e, PluginEvent::CommandsChanged)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_config_types_serve_web_pages_assets_and_view_messages() {
|
||||
let f = fixture(Limits::default());
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let pkg = tmp.path().join("custom-run");
|
||||
copy_dir(&sample("jobs"), &pkg);
|
||||
std::fs::create_dir_all(pkg.join("web/assets")).unwrap();
|
||||
std::fs::create_dir_all(pkg.join("icons")).unwrap();
|
||||
std::fs::write(pkg.join("web/form.html"), "<html><body>Form</body></html>").unwrap();
|
||||
std::fs::write(pkg.join("web/assets/app.js"), "console.log('run-config');").unwrap();
|
||||
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><rect width="16" height="16"/></svg>"#;
|
||||
std::fs::write(pkg.join("icons/run.svg"), svg).unwrap();
|
||||
std::fs::write(pkg.join("icons/run_dark.svg"), svg).unwrap();
|
||||
std::fs::write(
|
||||
pkg.join("plugin.toml"),
|
||||
r#"id = "jobs"
|
||||
name = "Custom Run"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.20"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-view:jobs", "on-command:*"]
|
||||
|
||||
[capabilities]
|
||||
required = ["process:jobs"]
|
||||
|
||||
[[contributes.runConfigTypes]]
|
||||
id = "jobs"
|
||||
label = "Custom Job"
|
||||
group = "Servers"
|
||||
icon = "icons/run.svg"
|
||||
iconDark = "icons/run_dark.svg"
|
||||
web = "web/form.html"
|
||||
layout = "full"
|
||||
prepareCommand = "prepare"
|
||||
|
||||
[[contributes.commands]]
|
||||
id = "prepare"
|
||||
title = "Prepare"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let info = f.install(&pkg);
|
||||
assert_eq!(info.status, PluginStatus::Inactive, "{:?}", info.error);
|
||||
|
||||
let items = f.host.ui_items("runConfigTypes");
|
||||
assert_eq!(items.len(), 1);
|
||||
assert_eq!((items[0].plugin_id.as_str(), items[0].key.as_str()), ("jobs", "jobs"));
|
||||
assert_eq!(items[0].decl["label"], "Custom Job");
|
||||
assert_eq!(items[0].decl["layout"], "full");
|
||||
|
||||
let light = f.host.assets("jobs", "runConfigIcon/jobs").unwrap();
|
||||
assert_eq!(light.len(), 1);
|
||||
assert!(light[0].1.contains("<rect"));
|
||||
let dark = f.host.assets("jobs", "runConfigIconDark/jobs").unwrap();
|
||||
assert_eq!(dark.len(), 1);
|
||||
|
||||
let page = f.host.web_page("jobs", "jobs").unwrap();
|
||||
let (rev, entry) = page.path.strip_prefix("jobs/").unwrap().split_once('/').unwrap();
|
||||
assert_eq!(entry, "web/form.html");
|
||||
let html = f.host.web_file("jobs", &format!("{rev}/web/form.html")).unwrap();
|
||||
assert_eq!(html.mime, "text/html; charset=utf-8");
|
||||
let js = f.host.web_file("jobs", &format!("{rev}/web/assets/app.js")).unwrap();
|
||||
assert_eq!(js.mime, "text/javascript; charset=utf-8");
|
||||
|
||||
f.take_events();
|
||||
f.host.view_event("jobs", "jobs", ide_plugin::ViewEvent::Message { text: "sync-form".into() }, f.inv()).unwrap();
|
||||
let reply = f.take_events().into_iter().find_map(|(_, e)| match e {
|
||||
PluginEvent::ViewMessage { plugin_id, view, message } if plugin_id == "jobs" && view == "jobs" => Some(message),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(reply.as_deref(), Some("sync-form"));
|
||||
|
||||
f.host.set_enabled("jobs", false).unwrap();
|
||||
assert!(f.host.web_page("jobs", "jobs").is_err());
|
||||
}
|
||||
@@ -11,6 +11,17 @@ use std::sync::Arc;
|
||||
/// Id prefix of externally detected configurations (`plugin:<plugin>:<id>`).
|
||||
pub const EXTERNAL_PREFIX: &str = "plugin:";
|
||||
|
||||
/// True for any configuration owned by a plugin (`kind == "plugin"`,
|
||||
/// `kind == "plugin:<plugin>:<type>"`, or a `plugin:` id with optional `workspace:<key>:` prefix).
|
||||
pub fn is_plugin_owned(config: &RunConfig) -> bool {
|
||||
let raw_id = config
|
||||
.id
|
||||
.strip_prefix("workspace:")
|
||||
.and_then(|rest| rest.split_once(':'))
|
||||
.map_or(config.id.as_str(), |(_, rest)| rest);
|
||||
config.kind == "plugin" || config.kind.starts_with(EXTERNAL_PREFIX) || raw_id.starts_with(EXTERNAL_PREFIX)
|
||||
}
|
||||
|
||||
pub trait ExternalDetection: Send + Sync {
|
||||
/// Configurations for the project at `root`; ids start with [`EXTERNAL_PREFIX`].
|
||||
fn detect(&self, root: &Path) -> Vec<RunConfig>;
|
||||
@@ -90,4 +101,28 @@ mod tests {
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied);
|
||||
assert!(err.message.contains("not allowed"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_custom_type_config_cannot_start_without_host_authorization() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let custom = RunConfig {
|
||||
id: "user:1".into(),
|
||||
name: "Custom Plugin Config".into(),
|
||||
kind: "plugin:acme:custom".into(),
|
||||
command: "sh".into(),
|
||||
args: vec!["-c".into(), "true".into()],
|
||||
cwd: None,
|
||||
env: Default::default(),
|
||||
detected: false,
|
||||
is_test: false,
|
||||
debug_adapter: None,
|
||||
allow_parallel: false,
|
||||
extras: Default::default(),
|
||||
};
|
||||
assert!(is_plugin_owned(&custom));
|
||||
let err = ProcessManager::new()
|
||||
.start(tmp.path(), &custom, &StartOptions::default(), Arc::new(ide_core::NullSink), Box::new(|_| {}))
|
||||
.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::PermissionDenied);
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ pub use detect::cmake::cache as cmake_cache;
|
||||
pub use detect::cmake::presets::{listed as cmake_listed_profiles, load as cmake_presets, profiles as cmake_profiles};
|
||||
pub use detect::cmake::toolchain as cmake_toolchain;
|
||||
pub use detect::cmake::{build_configs as cmake_build_configs, file_api as cmake_file_api, prepare as prepare_cmake};
|
||||
pub use process::{DetachedProcessKills, ProcessManager, StartOptions};
|
||||
pub use process::{DetachedProcessKills, DirectStop, ProcessManager, StartOptions};
|
||||
|
||||
use ide_core::{IdeResult, RunId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -284,7 +284,7 @@ pub struct RunAttach {
|
||||
pub buffered: Vec<OutputChunk>,
|
||||
}
|
||||
|
||||
pub use external::{EXTERNAL_PREFIX, ExternalDetection, set_external_detection};
|
||||
pub use external::{EXTERNAL_PREFIX, ExternalDetection, is_plugin_owned, set_external_detection};
|
||||
|
||||
/// Kinds whose command is a Python interpreter (or a runner of one): they get the project
|
||||
/// interpreter, `PYTHONUNBUFFERED` and the interpreter paths on `PYTHONPATH`.
|
||||
|
||||
@@ -83,9 +83,35 @@ struct LaunchEnv {
|
||||
vars: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A shell-free stop command (executable + argv) authorized by the host.
|
||||
#[derive(Clone)]
|
||||
pub struct DirectStop {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub display: String,
|
||||
/// Re-verified right before executing the stop command (e.g. plugin `process:` grant & pin).
|
||||
pub verify: Option<Arc<dyn Fn() -> Result<PathBuf, String> + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DirectStop {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DirectStop")
|
||||
.field("program", &self.program)
|
||||
.field("args", &self.args)
|
||||
.field("display", &self.display)
|
||||
.field("verify", &self.verify.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
enum StopKind {
|
||||
Shell(String),
|
||||
Direct(DirectStop),
|
||||
}
|
||||
|
||||
/// A configuration's stop command and where it runs.
|
||||
struct StopCommand {
|
||||
line: String,
|
||||
kind: StopKind,
|
||||
cwd: PathBuf,
|
||||
env: LaunchEnv,
|
||||
}
|
||||
@@ -147,6 +173,10 @@ pub struct StartOptions {
|
||||
pub capture_junit_reports: bool,
|
||||
/// The conda environment of a Python run's interpreter, activated for the run.
|
||||
pub conda_prefix: Option<PathBuf>,
|
||||
/// Shell-free stop command (argv) authorized by the host (used for plugin-owned configs).
|
||||
pub direct_stop: Option<DirectStop>,
|
||||
/// Set by `ide-host` after authorizing a plugin-owned run configuration.
|
||||
pub plugin_authorized: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
@@ -417,10 +447,29 @@ impl ProcessManager {
|
||||
if config.command.trim().is_empty() {
|
||||
return Err(IdeError::invalid("run configuration has no command"));
|
||||
}
|
||||
let approved = match crate::external::approved(config) {
|
||||
Some(Ok(c)) => Some(c),
|
||||
Some(Err(e)) => return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)),
|
||||
None => None,
|
||||
let approved = if crate::external::is_plugin_owned(config) {
|
||||
if options.plugin_authorized {
|
||||
None
|
||||
} else if config.detected && config.id.starts_with(crate::external::EXTERNAL_PREFIX) {
|
||||
if config.extras.stop_command.as_deref().is_some_and(|s| !s.trim().is_empty()) {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
"plugin stop commands must be authorized by the plugin host",
|
||||
));
|
||||
}
|
||||
match crate::external::approved(config) {
|
||||
Some(Ok(c)) => Some(c),
|
||||
Some(Err(e)) => return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)),
|
||||
None => None,
|
||||
}
|
||||
} else {
|
||||
return Err(IdeError::new(
|
||||
ide_core::error::ErrorKind::PermissionDenied,
|
||||
"plugin run configurations must be authorized by the plugin host",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let config = approved.as_ref().unwrap_or(config);
|
||||
let plan = crate::go::plan(root, config)?;
|
||||
@@ -435,6 +484,9 @@ impl ProcessManager {
|
||||
}
|
||||
crate::detect::cmake::prepare(config, &cwd)?;
|
||||
let mut inv = invocation(config, &cwd);
|
||||
if (options.plugin_authorized || approved.is_some()) && inv.shell {
|
||||
return Err(IdeError::invalid("plugin run configurations must launch an executable directly"));
|
||||
}
|
||||
let extras = &config.extras;
|
||||
if extras.emulate_terminal && extras.stdin_file.is_some() {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
@@ -459,11 +511,15 @@ impl ProcessManager {
|
||||
Some(file) => tee_output(&resolve_cwd(root, Some(Path::new(file))), on_output)?,
|
||||
None => on_output,
|
||||
};
|
||||
let stop = extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand {
|
||||
line: line.to_owned(),
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
});
|
||||
let stop = if let Some(direct) = options.direct_stop.clone() {
|
||||
Some(StopCommand { kind: StopKind::Direct(direct), cwd: cwd.clone(), env: env.clone() })
|
||||
} else {
|
||||
extras.stop_command.as_deref().map(str::trim).filter(|l| !l.is_empty()).map(|line| StopCommand {
|
||||
kind: StopKind::Shell(line.to_owned()),
|
||||
cwd: cwd.clone(),
|
||||
env: env.clone(),
|
||||
})
|
||||
};
|
||||
// A terminal re-encodes output itself; pipes carry the process's bytes as they are.
|
||||
let notice =
|
||||
if extras.emulate_terminal { None } else { match_console_encoding(&mut inv, &mut env, config, options) };
|
||||
@@ -1183,11 +1239,34 @@ fn apply_env(cmd: &mut Command, env: &LaunchEnv) {
|
||||
cmd.envs(&env.vars);
|
||||
}
|
||||
|
||||
/// Runs `stop.line` through the platform shell and waits for it (bounded), echoing it
|
||||
/// and any error output to the console.
|
||||
/// Runs `stop` and waits for it (bounded), echoing it and any error output to the console.
|
||||
fn run_stop_command(stop: &StopCommand, entry: &Entry) {
|
||||
entry.emit_output(OutputChunk::System { text: format!("{}\n", stop.line) });
|
||||
let inv = shell_invocation(&stop.line, cfg!(windows), std::env::var("COMSPEC").ok());
|
||||
let (inv, display) = match &stop.kind {
|
||||
StopKind::Shell(line) => (shell_invocation(line, cfg!(windows), std::env::var("COMSPEC").ok()), line.clone()),
|
||||
StopKind::Direct(direct) => {
|
||||
let program = match &direct.verify {
|
||||
Some(verify) => match verify() {
|
||||
Ok(pinned) => pinned,
|
||||
Err(reason) => {
|
||||
entry.emit_output(OutputChunk::Stderr { text: format!("Stop command refused: {reason}\n") });
|
||||
return;
|
||||
}
|
||||
},
|
||||
None => direct.program.clone(),
|
||||
};
|
||||
(
|
||||
Invocation {
|
||||
program,
|
||||
args: direct.args.clone(),
|
||||
raw_args: false,
|
||||
shell: false,
|
||||
display: direct.display.clone(),
|
||||
},
|
||||
direct.display.clone(),
|
||||
)
|
||||
}
|
||||
};
|
||||
entry.emit_output(OutputChunk::System { text: format!("{display}\n") });
|
||||
let mut cmd = Command::new(&inv.program);
|
||||
ide_core::process::prepare(&mut cmd);
|
||||
ide_core::process::own_group(&mut cmd);
|
||||
|
||||
@@ -102,38 +102,39 @@ The user approves **required** capabilities as a whole when installing. **Option
|
||||
|
||||
Each contribution point is a table (`[contributes.settings]`) or an array of tables (`[[contributes.commands]]`). Contributions are live as soon as the plugin is enabled, before its code loads.
|
||||
|
||||
| Point | Declaration | Code needed | Guide |
|
||||
| ------------------- | ----------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
|
||||
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
|
||||
| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) |
|
||||
| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) |
|
||||
| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) |
|
||||
| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) |
|
||||
| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) |
|
||||
| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) |
|
||||
| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) |
|
||||
| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
|
||||
| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
|
||||
| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) |
|
||||
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) |
|
||||
| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) |
|
||||
| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) |
|
||||
| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) |
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) |
|
||||
| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) |
|
||||
| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) |
|
||||
| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) |
|
||||
| Point | Declaration | Code needed | Guide |
|
||||
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) |
|
||||
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) |
|
||||
| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) |
|
||||
| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) |
|
||||
| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) |
|
||||
| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) |
|
||||
| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) |
|
||||
| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) |
|
||||
| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) |
|
||||
| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) |
|
||||
| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) |
|
||||
| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
|
||||
| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
|
||||
| `runConfigTypes` | `id`, `label`, `web`, `layout?`, `prepareCommand?`, `matchConfigPrefix?` (API 1.20; requires `process:<program>` grants at Run/Debug/Stop) | no | [README: Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) |
|
||||
| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) |
|
||||
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) |
|
||||
| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) |
|
||||
| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) |
|
||||
| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) |
|
||||
| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) |
|
||||
| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) |
|
||||
| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) |
|
||||
| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) |
|
||||
|
||||
Item ids (commands, views, themes, …) match `[a-z0-9][a-z0-9._-]*`, at most 64 characters. Menus, shortcuts and status bar items refer to the plugin's own declared commands; inside the IDE a command's action id is `plugin.<plugin id>.<command id>`.
|
||||
|
||||
|
||||
@@ -102,38 +102,39 @@ optional = ["net:api.openai.com", "secrets"]
|
||||
|
||||
每个贡献点是一张表(`[contributes.settings]`)或一个表数组(`[[contributes.commands]]`)。插件启用后贡献立即生效,不需要等代码加载。
|
||||
|
||||
| 贡献点 | 声明字段 | 需要代码 | 指南 |
|
||||
| ------------------- | ------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
|
||||
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
|
||||
| `providers` | `kinds`、`languages` | 是 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `documentIndexers` | `extensions` | 是 | [索引](/zh/plugins/guides/indexing) |
|
||||
| `endpoints` | `files`(API 1.3) | 是 | [README:Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) |
|
||||
| `searchCategories` | `id`、`title`(API 1.13) | 是 | [自定义搜索分类](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) |
|
||||
| `views` | `id`、`title`、`icon?`、`location`、`web?`、`group?`、`when?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `customEditors` | `id`、`title`、`patterns`、`priority`、`layout?`、`web?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `markerIcons` | `id`、`icon`、`iconDark?`、`markers?`、`tooltip?`(API 1.3):装订区标记图标 | 否 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `editorPanels` | `id`、`web`、`width`、`when?`(API 1.9;需要 `editor.read`) | 否 | [README:Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) |
|
||||
| `overlays` | `id`、`web`、`width`、`height`、`anchor?`、`when?`、`interactive?`(API 1.18) | 否 | [README:Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) |
|
||||
| `runAnything` | `prefix`、`title?`(API 1.18) | 否 | [README:Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
|
||||
| `dialogs` | `id`、`title`、`web`、`width`、`height`(API 1.18) | 否 | [README:Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
|
||||
| `fileIcons` | `id`、`patterns`、`icon`、`iconDark?` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
|
||||
| `fileTemplates` | `id`、`name`、`extension`、`path`;API 1.3:`fileName`、`variables` | 否 | [文件操作](/zh/plugins/guides/file-actions) |
|
||||
| `snippets` | `language`、`path`(API 1.4) | 否 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `commitChecks` | `id`、`title` | 是 | [README:Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) |
|
||||
| `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) |
|
||||
| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) |
|
||||
| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) |
|
||||
| `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
|
||||
| `languages` | `path`(`languages/<id>.toml` 格式的文件) | 否 | [添加语言](/zh/languages/adding) |
|
||||
| 贡献点 | 声明字段 | 需要代码 | 指南 |
|
||||
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `commands` | `id`、`title`、`category?`、`when?`、`icon?` | 执行时需要 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `menus` | `menu`、`command`、`when?`、`view?`、`submenu?` | 否 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `keymaps` | `command`、`key`、`mac?`、`when?`(仅 Escape) | 否 | [命令与动作](/zh/plugins/guides/commands) |
|
||||
| `statusBar` | `id`、`text`、`tooltip?`、`command?`、`align?`、`priority?` | 否 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `settings` | `schema`(JSON 文件)或 `pages`(API 1.3)、`title?` | 否 | [生命周期与事件](/zh/plugins/lifecycle) |
|
||||
| `secrets` | `name`、`label`、`description?` | 使用时需要 | [权限与能力](/zh/plugins/capabilities) |
|
||||
| `providers` | `kinds`、`languages` | 是 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `documentIndexers` | `extensions` | 是 | [索引](/zh/plugins/guides/indexing) |
|
||||
| `endpoints` | `files`(API 1.3) | 是 | [README:Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) |
|
||||
| `searchCategories` | `id`、`title`(API 1.13) | 是 | [自定义搜索分类](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) |
|
||||
| `views` | `id`、`title`、`icon?`、`location`、`web?`、`group?`、`when?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `customEditors` | `id`、`title`、`patterns`、`priority`、`layout?`、`web?` | 无 `web` 时需要 | [视图与装饰](/zh/plugins/guides/views) |
|
||||
| `markerIcons` | `id`、`icon`、`iconDark?`、`markers?`、`tooltip?`(API 1.3):装订区标记图标 | 否 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `editorPanels` | `id`、`web`、`width`、`when?`(API 1.9;需要 `editor.read`) | 否 | [README:Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) |
|
||||
| `overlays` | `id`、`web`、`width`、`height`、`anchor?`、`when?`、`interactive?`(API 1.18) | 否 | [README:Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) |
|
||||
| `runAnything` | `prefix`、`title?`(API 1.18) | 否 | [README:Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) |
|
||||
| `dialogs` | `id`、`title`、`web`、`width`、`height`(API 1.18) | 否 | [README:Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) |
|
||||
| `runConfigTypes` | `id`、`label`、`web`、`layout?`、`prepareCommand?`、`matchConfigPrefix?`(API 1.20;Run/Debug/Stop 均需 `process:<program>` 授权) | 否 | [README:Custom run configuration forms](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-run-configuration-forms) |
|
||||
| `fileIcons` | `id`、`patterns`、`icon`、`iconDark?` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
|
||||
| `fileTemplates` | `id`、`name`、`extension`、`path`;API 1.3:`fileName`、`variables` | 否 | [文件操作](/zh/plugins/guides/file-actions) |
|
||||
| `snippets` | `language`、`path`(API 1.4) | 否 | [语言功能](/zh/plugins/guides/language-features) |
|
||||
| `commitChecks` | `id`、`title` | 是 | [README:Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) |
|
||||
| `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) |
|
||||
| `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) |
|
||||
| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) |
|
||||
| `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) |
|
||||
| `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) |
|
||||
| `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) |
|
||||
| `iconThemes` | `id`、`label`、`path` | 否 | [图标主题](/zh/plugins/guides/icon-themes) |
|
||||
| `languages` | `path`(`languages/<id>.toml` 格式的文件) | 否 | [添加语言](/zh/languages/adding) |
|
||||
|
||||
条目 id(命令、视图、主题等)匹配 `[a-z0-9][a-z0-9._-]*`,不超过 64 个字符。菜单、快捷键和状态栏项只能引用插件自己声明的命令;在 IDE 内部,命令的操作 id 是 `plugin.<plugin id>.<command id>`。
|
||||
|
||||
|
||||
@@ -160,6 +160,7 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
|
||||
| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no |
|
||||
| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no |
|
||||
| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no |
|
||||
| `runConfigTypes` | `id`, `label`, `web`, `layout?` (`embedded` / `full`), `height?`, `icon?`, `iconDark?`, `group?`, `command?`, `args?`, `prepareCommand?`, `matchConfigPrefix?`, `defaults?` — a custom Run/Debug Configurations form (`openidea.runConfig`; API 1.20; _Custom run configuration forms_) | no |
|
||||
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
|
||||
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no |
|
||||
| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes |
|
||||
@@ -2625,6 +2626,50 @@ IDE, so a dialog needs no capability. Only a dialog's page has `openidea.dialog`
|
||||
For something that stays open beside the editor without taking the keyboard,
|
||||
use an [overlay](#overlays) or a tool window.
|
||||
|
||||
#### Custom run configuration forms
|
||||
|
||||
With API 1.20 (`engines.openidea = "^1.20"`), `[[contributes.runConfigTypes]]`
|
||||
contributes a run configuration type whose settings form in **Run | Edit
|
||||
Configurations…** is rendered by a package web page (`?openidea=run-config`):
|
||||
|
||||
```toml
|
||||
[[contributes.runConfigTypes]]
|
||||
id = "smart-tomcat"
|
||||
label = "SmartTomcat"
|
||||
group = "Servers"
|
||||
icon = "icons/tomcat.svg"
|
||||
iconDark = "icons/tomcat_dark.svg"
|
||||
web = "web/run-config.html"
|
||||
layout = "embedded" # "embedded" (default) or "full" (replaces everything below Name)
|
||||
height = 360 # embedded height in pixels, 120–1200
|
||||
ownsWorkingDirectory = false
|
||||
ownsEnvironment = false
|
||||
prepareCommand = "prepare" # optional command invoked before Run/Debug; returns a JSON patch
|
||||
matchConfigPrefix = "" # optional id prefix for matching plugin:<id>:<config> entries
|
||||
```
|
||||
|
||||
Inside the page, `openidea.runConfig` provides `get()`, `patch(patch)`,
|
||||
`setErrors(errors)`, `setHeight(height)`, and `onChange(fn)` to read and update
|
||||
the staged `RunConfig` draft (including `params`, `command`, `args`, `cwd`, `env`,
|
||||
`debugAdapter`, and `name`), surface validation errors that block OK/Apply/Run,
|
||||
and resize embedded forms.
|
||||
|
||||
**Process grants and host launch checks.** Every launch (Run, Debug, and any
|
||||
`stopCommand`) goes through host-owned plugin authorization:
|
||||
|
||||
- Declare and obtain `process:<program>` for both the executable launched on
|
||||
Run/Debug (`command`, whether set in the manifest, form `patch()`, or
|
||||
`prepareCommand`) and any program named by `stopCommand`. The host resolves
|
||||
the exact pinned binary via the grant ledger before starting or debugging.
|
||||
- `stopCommand` is parsed as `<program> [args...]` without a shell, invokes the
|
||||
approved binary directly, and re-verifies its `process:` grant and file pin
|
||||
at Stop time (rejected if revoked or changed, though process termination still
|
||||
proceeds).
|
||||
- `env` may only add non-inherited variables (replacing inherited variables such
|
||||
as `PATH` or loader variables such as `LD_PRELOAD` / `DYLD_INSERT_LIBRARIES`
|
||||
is refused, capped at 64 entries), and `cwd` must stay inside the trusted
|
||||
project root.
|
||||
|
||||
### Web frame PTYs (API 1.3)
|
||||
|
||||
Packages requiring `engines.openidea = "^1.3"` can exchange JSON strings through
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
provideNotificationService,
|
||||
provideToolWindowService,
|
||||
useDebugRunSessions,
|
||||
type ToolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { registerDebugActions } from "../actions";
|
||||
import { resetSessions, useDebug } from "../state";
|
||||
|
||||
const ipc = vi.hoisted(() => ({
|
||||
pluginPrepareDebugRun: vi.fn(),
|
||||
debugStart: vi.fn(async () => ({ status: "ok" as const, data: 77 })),
|
||||
debugStop: vi.fn(async () => ({ status: "ok" as const, data: null })),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/ipc", async (original) => {
|
||||
const real = await original<typeof import("@/platform/ipc")>();
|
||||
return { ...real, isTauri: () => true, commands: { ...real.commands, ...ipc } };
|
||||
});
|
||||
|
||||
const customConfig: RunConfig = {
|
||||
id: "user:tomcat-1",
|
||||
name: "Custom Python",
|
||||
kind: "plugin:acme.custom:runner",
|
||||
command: "python3",
|
||||
args: ["app.py"],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: "debugpy",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
resetSessions();
|
||||
useDebugRunSessions.setState({ sessions: [] });
|
||||
useProject.setState({ project: { root: "/p" } as never });
|
||||
provideNotificationService({ notify: vi.fn() });
|
||||
provideToolWindowService({ show: vi.fn() } as unknown as ToolWindowService);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("routes plugin:<plugin>:<type> configs through pluginPrepareDebugRun and retains the original config", async () => {
|
||||
ipc.pluginPrepareDebugRun.mockResolvedValueOnce({
|
||||
status: "ok",
|
||||
data: { ...customConfig, command: "/approved/python3" },
|
||||
});
|
||||
const dispose = registerDebugActions();
|
||||
try {
|
||||
await executeAction("debug.startConfig", customConfig);
|
||||
expect(ipc.pluginPrepareDebugRun).toHaveBeenCalledWith(customConfig);
|
||||
expect(ipc.debugStart).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
adapter: "debugpy",
|
||||
extraJson: expect.stringContaining('"/approved/python3"'),
|
||||
}),
|
||||
);
|
||||
const launch = vi.mocked(ipc.debugStart).mock.calls[0] as unknown as [{ extraJson: string }];
|
||||
expect(JSON.parse(launch[0].extraJson).__openideaPluginRun).toEqual({
|
||||
config: customConfig,
|
||||
program: "/approved/python3",
|
||||
});
|
||||
expect(useDebug.getState().sessions[77]?.runConfig).toEqual(customConfig);
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("does not start debugging when pluginPrepareDebugRun rejects due to missing grant", async () => {
|
||||
ipc.pluginPrepareDebugRun.mockResolvedValueOnce({
|
||||
status: "error",
|
||||
error: { kind: "permissionDenied", message: "process:custom-tool was not granted" },
|
||||
});
|
||||
const dispose = registerDebugActions();
|
||||
try {
|
||||
await executeAction("debug.startConfig", customConfig);
|
||||
expect(ipc.pluginPrepareDebugRun).toHaveBeenCalledWith(customConfig);
|
||||
expect(ipc.debugStart).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
dispose();
|
||||
}
|
||||
});
|
||||
@@ -152,6 +152,10 @@ function withExtra(launch: LaunchConfig, more: Record<string, unknown> | undefin
|
||||
return { ...launch, extraJson: JSON.stringify({ ...extra, ...more }) };
|
||||
}
|
||||
|
||||
function withPluginRun(launch: LaunchConfig, config: RunConfig, program: string): LaunchConfig {
|
||||
return withExtra(launch, { __openideaPluginRun: { config, program } });
|
||||
}
|
||||
|
||||
function errorText(e: unknown) {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
@@ -478,19 +482,26 @@ async function startConfig(arg: unknown) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (isRemoteConfig(config)) {
|
||||
const pluginConfig =
|
||||
config.kind === "plugin" || config.kind.startsWith("plugin:") || /^(?:workspace:[^:]+:)?plugin:/.test(config.id)
|
||||
? config
|
||||
: null;
|
||||
if (!pluginConfig && isRemoteConfig(config)) {
|
||||
await startRemote(config, root, show);
|
||||
return;
|
||||
}
|
||||
if (isBrowserConfig(config)) {
|
||||
if (!pluginConfig && isBrowserConfig(config)) {
|
||||
await startBrowser(config, root, show);
|
||||
return;
|
||||
}
|
||||
if (isJavaDebuggable(config)) {
|
||||
if (!pluginConfig && isJavaDebuggable(config)) {
|
||||
await startJavaConfig(config, root, origin ?? config, show);
|
||||
return;
|
||||
}
|
||||
if (config.kind === "plugin") config = await call(commands.pluginPrepareDebugRun(config));
|
||||
const sessionOrigin = origin ?? config;
|
||||
if (pluginConfig) {
|
||||
config = await call(commands.pluginPrepareDebugRun(pluginConfig));
|
||||
}
|
||||
const dotnet = config.kind === "dotnet" && config.debugAdapter === "netcoredbg";
|
||||
const prepared = dotnet ? await call(commands.runDotnetResolve(config, true)) : config;
|
||||
// php-debug starts the PHP chosen in Settings unless the command names one.
|
||||
@@ -512,7 +523,10 @@ async function startConfig(arg: unknown) {
|
||||
await maybeEditorService()
|
||||
?.saveAll()
|
||||
.catch(() => undefined);
|
||||
await startSession(launch, { runConfig: origin ?? config, show });
|
||||
await startSession(pluginConfig ? withPluginRun(launch, pluginConfig, config.command) : launch, {
|
||||
runConfig: sessionOrigin,
|
||||
show,
|
||||
});
|
||||
await xdebugCheck;
|
||||
}
|
||||
|
||||
@@ -613,7 +627,7 @@ export function registerDebugActions(): () => void {
|
||||
const off = useDebug.subscribe(observe);
|
||||
try {
|
||||
await maybeEditorService()?.saveAll();
|
||||
id = await startSession(launch, { runConfig: config });
|
||||
id = await startSession(withPluginRun(launch, a.config, config.command), { runConfig: a.config });
|
||||
if (id === null) {
|
||||
off();
|
||||
throw new Error("Debug session did not start");
|
||||
|
||||
@@ -0,0 +1,309 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import type { PluginInfo } from "@/bindings";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { resetRuns, useRun } from "@/features/run/store";
|
||||
import { EditConfigsOverlay } from "@/features/run/EditConfigsDialog";
|
||||
import { typeForConfig } from "@/features/run/types";
|
||||
import { useRunConfigTypes } from "@/workbench/contributions";
|
||||
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
|
||||
import { usePlugins } from "../store";
|
||||
import { FRAME_TAG, frameDocument } from "../views/frame";
|
||||
import {
|
||||
applyRunConfigPatch,
|
||||
pluginRunConfigKind,
|
||||
projectRunConfigType,
|
||||
sanitizeRunConfigErrors,
|
||||
type RunConfigTypeDecl,
|
||||
} from "../views/runConfigForm";
|
||||
|
||||
function bridgeAt(search: string) {
|
||||
const script = /<script>([\s\S]*)<\/script>/.exec(frameDocument("", { dark: true, vars: {} }))![1]!;
|
||||
const sent: Array<Record<string, unknown>> = [];
|
||||
const parent = { postMessage: (m: Record<string, unknown>) => void sent.push(m) };
|
||||
const listeners: Record<string, (e: unknown) => void> = {};
|
||||
const frameWindow: Record<string, unknown> = {
|
||||
parent,
|
||||
addEventListener: (type: string, fn: (e: unknown) => void) => void (listeners[type] = fn),
|
||||
};
|
||||
new Function("window", "document", "location", script)(
|
||||
frameWindow,
|
||||
{ documentElement: document.createElement("html") },
|
||||
{ search },
|
||||
);
|
||||
return {
|
||||
api: frameWindow.openidea as Record<string, unknown>,
|
||||
sent,
|
||||
message: (data: unknown, source: unknown = parent) => listeners.message?.({ data, source }),
|
||||
};
|
||||
}
|
||||
|
||||
const baseConfig = (overrides: Partial<RunConfig> = {}): RunConfig => ({
|
||||
id: "user:1",
|
||||
name: "Tomcat Dev",
|
||||
kind: pluginRunConfigKind("acme.tomcat", "smart-tomcat"),
|
||||
command: "",
|
||||
args: [],
|
||||
cwd: null,
|
||||
env: {},
|
||||
detected: false,
|
||||
isTest: false,
|
||||
debugAdapter: "java-debug",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetRuns();
|
||||
useRunConfigTypes.setState({ types: new Map() });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setPluginsBackend(null);
|
||||
usePlugins.setState({ plugins: [] });
|
||||
useRunConfigTypes.setState({ types: new Map() });
|
||||
resetRuns();
|
||||
});
|
||||
|
||||
describe("frame bridge: openidea.runConfig", () => {
|
||||
it("is exposed only on ?openidea=run-config pages and forwards calls and updates", () => {
|
||||
expect(bridgeAt("").api.runConfig).toBeUndefined();
|
||||
expect(bridgeAt("?openidea=dialog").api.runConfig).toBeUndefined();
|
||||
expect(bridgeAt("?openidea=overlay").api.runConfig).toBeUndefined();
|
||||
|
||||
const { api, sent, message } = bridgeAt("?openidea=run-config");
|
||||
const runConfig = api.runConfig as {
|
||||
get(): Promise<unknown>;
|
||||
patch(p: unknown): Promise<unknown>;
|
||||
setErrors(e: unknown): Promise<unknown>;
|
||||
setHeight(h: number): Promise<unknown>;
|
||||
onChange(fn: (s: unknown) => void): void;
|
||||
};
|
||||
const seen: unknown[] = [];
|
||||
runConfig.onChange((snap) => seen.push(snap));
|
||||
|
||||
void runConfig.get();
|
||||
void runConfig.patch({ params: { httpPort: "8081" } });
|
||||
void runConfig.setErrors({ httpPort: "Invalid port" });
|
||||
void runConfig.setHeight(480);
|
||||
|
||||
expect(sent.map((m) => m.op)).toEqual([
|
||||
"runConfig.get",
|
||||
"runConfig.patch",
|
||||
"runConfig.setErrors",
|
||||
"runConfig.setHeight",
|
||||
]);
|
||||
|
||||
const snapshot = { id: "user:1", name: "Updated" };
|
||||
message({ tag: FRAME_TAG, runConfig: snapshot });
|
||||
expect(seen).toEqual([snapshot]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("runConfig patch & error sanitization", () => {
|
||||
it("merges params, deletes null params, and validates fields", () => {
|
||||
const initial = baseConfig({ params: { httpPort: "8080", obsolete: "1" }, env: { A: "1" } });
|
||||
const patched = applyRunConfigPatch(
|
||||
initial,
|
||||
{
|
||||
name: "App Server",
|
||||
command: "java",
|
||||
args: ["-jar", "bootstrap.jar"],
|
||||
cwd: "webapp",
|
||||
env: { JAVA_OPTS: "-Xmx512m" },
|
||||
params: { httpPort: "9090", obsolete: null, contextPath: "/app" },
|
||||
isTest: true,
|
||||
allowParallel: true,
|
||||
emulateTerminal: false,
|
||||
stopCommand: "catalina stop",
|
||||
},
|
||||
false,
|
||||
);
|
||||
expect(patched).toMatchObject({
|
||||
name: "App Server",
|
||||
command: "java",
|
||||
args: ["-jar", "bootstrap.jar"],
|
||||
cwd: "webapp",
|
||||
env: { JAVA_OPTS: "-Xmx512m" },
|
||||
params: { httpPort: "9090", contextPath: "/app" },
|
||||
isTest: true,
|
||||
allowParallel: true,
|
||||
emulateTerminal: false,
|
||||
stopCommand: "catalina stop",
|
||||
});
|
||||
|
||||
// Template patches cannot rename the template.
|
||||
expect(applyRunConfigPatch(initial, { name: "Ignored" }, true).name).toBe("Tomcat Dev");
|
||||
|
||||
expect(() => applyRunConfigPatch(initial, { env: { "BAD=KEY": "1" } }, false)).toThrow(/invalid env/);
|
||||
expect(() => applyRunConfigPatch(initial, { command: "java\nrm" }, false)).toThrow(/control/);
|
||||
expect(() => applyRunConfigPatch(initial, { params: { bad: "a\0b" } }, false)).toThrow(/control/);
|
||||
|
||||
expect(sanitizeRunConfigErrors({ httpPort: "Required", empty: " " })).toEqual({ httpPort: "Required" });
|
||||
expect(sanitizeRunConfigErrors(null)).toEqual({});
|
||||
expect(() => sanitizeRunConfigErrors(["bad"])).toThrow(/object/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("plugin runConfigTypes integration", () => {
|
||||
const embeddedDecl: RunConfigTypeDecl = {
|
||||
id: "smart-tomcat",
|
||||
label: "SmartTomcat",
|
||||
group: "Servers",
|
||||
icon: "icons/tomcat.svg",
|
||||
iconDark: "icons/tomcat_dark.svg",
|
||||
web: "web/form.html",
|
||||
layout: "embedded",
|
||||
height: 300,
|
||||
prepareCommand: "prepare",
|
||||
matchConfigPrefix: "srv:",
|
||||
defaults: { httpPort: "8080" },
|
||||
};
|
||||
|
||||
it("loads SVG icons, renders embedded form, handles patch/errors/height, and runs prepareCommand", async () => {
|
||||
const runCommand = vi.fn(async (_p: string, _c: string, arg: string | null) => {
|
||||
const parsed = JSON.parse(arg ?? "{}") as { params?: Record<string, string> };
|
||||
return JSON.stringify({
|
||||
name: "MustBeIgnoredAtLaunch",
|
||||
command: "/usr/bin/java",
|
||||
args: [`-Dport=${parsed.params?.httpPort ?? "8080"}`, "org.apache.catalina.startup.Bootstrap"],
|
||||
});
|
||||
});
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6"/></svg>`;
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([]),
|
||||
webPageUrl: async () => "about:blank",
|
||||
assets: async (_p, prefix) =>
|
||||
prefix === "runConfigIcon/smart-tomcat"
|
||||
? [["runConfigIcon/smart-tomcat", svg]]
|
||||
: prefix === "runConfigIconDark/smart-tomcat"
|
||||
? [["runConfigIconDark/smart-tomcat", svg]]
|
||||
: [],
|
||||
runCommand,
|
||||
});
|
||||
usePlugins.setState({ plugins: [{ id: "acme.tomcat", hasCode: true, capabilities: [] } as unknown as PluginInfo] });
|
||||
|
||||
const dispose = projectRunConfigType("acme.tomcat", embeddedDecl);
|
||||
await waitFor(() => {
|
||||
expect(useRunConfigTypes.getState().types.get(pluginRunConfigKind("acme.tomcat", "smart-tomcat"))?.icon).toBe(
|
||||
"ext:runConfigIcon/acme.tomcat/smart-tomcat",
|
||||
);
|
||||
});
|
||||
|
||||
// Dynamic `kind: "plugin"` config matches via matchConfigPrefix.
|
||||
const dynamicCfg = baseConfig({
|
||||
id: "plugin:acme.tomcat:srv:main",
|
||||
kind: "plugin",
|
||||
detected: true,
|
||||
params: { httpPort: "8080" },
|
||||
});
|
||||
const matched = typeForConfig(dynamicCfg);
|
||||
expect(matched?.id).toBe(pluginRunConfigKind("acme.tomcat", "smart-tomcat"));
|
||||
|
||||
// PrepareLaunch invokes prepareCommand and keeps original name.
|
||||
const prepared = await matched!.prepareLaunch!(dynamicCfg);
|
||||
expect(runCommand).toHaveBeenCalledWith("acme.tomcat", "prepare", expect.any(String), null, []);
|
||||
expect(prepared.name).toBe("Tomcat Dev");
|
||||
expect(prepared.command).toBe("/usr/bin/java");
|
||||
expect(prepared.args).toEqual(["-Dport=8080", "org.apache.catalina.startup.Bootstrap"]);
|
||||
|
||||
// Open EditConfigsOverlay with a user config of this type.
|
||||
const userCfg = baseConfig({ id: "user:tomcat-1", params: { httpPort: "8080" } });
|
||||
useRun.setState({ configs: [userCfg], editorOpen: true, editTarget: userCfg.id });
|
||||
render(<EditConfigsOverlay />);
|
||||
|
||||
const frame = await waitFor(() => {
|
||||
const f = document.querySelector<HTMLIFrameElement>("iframe");
|
||||
expect(f).not.toBeNull();
|
||||
return f!;
|
||||
});
|
||||
expect(frame.getAttribute("src")).toBe("about:blank?openidea=run-config");
|
||||
// Embedded layout keeps common fields visible.
|
||||
expect(screen.getByLabelText("Working directory")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Environment variables")).toBeInTheDocument();
|
||||
|
||||
const posted: Array<{ reply?: number; value?: unknown; runConfig?: unknown }> = [];
|
||||
vi.spyOn(frame.contentWindow!, "postMessage").mockImplementation((msg: unknown) => {
|
||||
posted.push(msg as { reply?: number; value?: unknown; runConfig?: unknown });
|
||||
});
|
||||
|
||||
const callFrame = (callId: number, op: string, args: Record<string, unknown> = {}) => {
|
||||
act(() => {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: { tag: FRAME_TAG, call: callId, op, args },
|
||||
source: frame.contentWindow,
|
||||
}),
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
callFrame(1, "runConfig.get");
|
||||
await waitFor(() => expect(posted.find((m) => m.reply === 1)?.value).toMatchObject({ name: "Tomcat Dev" }));
|
||||
|
||||
callFrame(2, "runConfig.setHeight", { height: 520 });
|
||||
await waitFor(() => expect(frame.parentElement?.style.height).toBe("520px"));
|
||||
|
||||
callFrame(3, "runConfig.setErrors", { errors: { httpPort: "Port already in use" } });
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("Fix the highlighted fields")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "OK" })).toBeDisabled();
|
||||
});
|
||||
|
||||
callFrame(4, "runConfig.setErrors", { errors: {} });
|
||||
callFrame(5, "runConfig.patch", { patch: { params: { httpPort: "8082" }, command: "java" } });
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText("Fix the highlighted fields")).toBeNull();
|
||||
expect(screen.getByRole("button", { name: "OK" })).toBeEnabled();
|
||||
expect(screen.getByRole("button", { name: "Apply" })).toBeEnabled();
|
||||
});
|
||||
|
||||
// External edit (Name input) notifies the frame.
|
||||
posted.length = 0;
|
||||
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "Tomcat Prod" } });
|
||||
await waitFor(() => {
|
||||
expect(posted.some((m) => (m.runConfig as { name?: string } | undefined)?.name === "Tomcat Prod")).toBe(true);
|
||||
});
|
||||
|
||||
dispose();
|
||||
expect(useRunConfigTypes.getState().types.size).toBe(0);
|
||||
});
|
||||
|
||||
it("supports full layout and ownsWorkingDirectory / ownsEnvironment", async () => {
|
||||
setPluginsBackend({
|
||||
...createMemoryPluginsBackend([]),
|
||||
webPageUrl: async () => "about:blank",
|
||||
});
|
||||
usePlugins.setState({
|
||||
plugins: [{ id: "acme.tomcat", hasCode: false, capabilities: [] } as unknown as PluginInfo],
|
||||
});
|
||||
|
||||
const dispose = projectRunConfigType("acme.tomcat", {
|
||||
id: "full-tomcat",
|
||||
label: "Full Tomcat",
|
||||
web: "web/full.html",
|
||||
layout: "full",
|
||||
ownsWorkingDirectory: true,
|
||||
ownsEnvironment: true,
|
||||
});
|
||||
const cfg = baseConfig({
|
||||
id: "user:full",
|
||||
kind: pluginRunConfigKind("acme.tomcat", "full-tomcat"),
|
||||
command: "java",
|
||||
});
|
||||
useRun.setState({ configs: [cfg], editorOpen: true, editTarget: cfg.id });
|
||||
render(<EditConfigsOverlay />);
|
||||
|
||||
const frame = await waitFor(() => {
|
||||
const f = document.querySelector<HTMLIFrameElement>("iframe");
|
||||
expect(f).not.toBeNull();
|
||||
return f!;
|
||||
});
|
||||
expect(frame.getAttribute("src")).toBe("about:blank?openidea=run-config");
|
||||
expect(screen.getByLabelText("Name")).toBeInTheDocument();
|
||||
expect(screen.queryByLabelText("Working directory")).toBeNull();
|
||||
expect(screen.queryByLabelText("Environment variables")).toBeNull();
|
||||
expect(screen.queryByLabelText("Run on")).toBeNull();
|
||||
|
||||
dispose();
|
||||
});
|
||||
});
|
||||
@@ -81,6 +81,7 @@ const TEXT_KEYS: Record<string, readonly string[]> = {
|
||||
markerIcons: ["tooltip"],
|
||||
customEditors: ["title"],
|
||||
dialogs: ["title"],
|
||||
runConfigTypes: ["label", "description", "group"],
|
||||
runAnything: ["title"],
|
||||
statusBar: ["text", "tooltip"],
|
||||
settings: ["title"],
|
||||
|
||||
@@ -50,6 +50,7 @@ const VIEW_ONLY_POINTS: ReadonlyArray<[string, string]> = [
|
||||
["editorPanels", "Editor Panels"],
|
||||
["overlays", "Overlays"],
|
||||
["dialogs", "Dialogs"],
|
||||
["runConfigTypes", "Run Configuration Types"],
|
||||
["runAnything", "Run Anything"],
|
||||
["markerIcons", "Marker Icons"],
|
||||
["fileIcons", "File Icons"],
|
||||
|
||||
@@ -68,6 +68,7 @@ import { layoutActions, layoutWrapper } from "./views/editorLayout";
|
||||
import { editorPanelUpdates, projectEditorPanel, type EditorPanelDecl } from "./views/editorPanel";
|
||||
import { projectOverlay, type OverlayDecl } from "./views/overlay";
|
||||
import { projectDialog, type DialogDecl } from "./views/dialog";
|
||||
import { projectRunConfigType, type RunConfigTypeDecl } from "./views/runConfigForm";
|
||||
import { projectRunAnything, type RunAnythingDecl } from "./runAnything";
|
||||
import { registerContentActions } from "./views/contentActions";
|
||||
import {
|
||||
@@ -635,6 +636,10 @@ export function defineViewUiPoints(): () => void {
|
||||
title: "Dialogs",
|
||||
project: ({ pluginId, decl }) => projectDialog(pluginId, decl),
|
||||
}),
|
||||
defineUiPoint<RunConfigTypeDecl>("runConfigTypes", {
|
||||
title: "Run Configuration Types",
|
||||
project: ({ pluginId, decl }) => projectRunConfigType(pluginId, decl),
|
||||
}),
|
||||
defineUiPoint<RunAnythingDecl>("runAnything", {
|
||||
title: "Run Anything",
|
||||
project: ({ pluginId, decl }) => projectRunAnything(pluginId, decl),
|
||||
|
||||
@@ -173,12 +173,23 @@ export const EDITOR_PANEL_QUERY = "openidea=editor-panel";
|
||||
export const OVERLAY_QUERY = "openidea=overlay";
|
||||
/** The query that gives a plugin dialog's page `openidea.dialog` (frame-bridge.js). */
|
||||
export const DIALOG_QUERY = "openidea=dialog";
|
||||
/** The query that gives a custom run-config form's page `openidea.runConfig` (frame-bridge.js). */
|
||||
export const RUN_CONFIG_QUERY = "openidea=run-config";
|
||||
|
||||
/** A plugin dialog's frame: its page can close the dialog (`openidea.dialog.close()`). */
|
||||
export interface FrameDialog {
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** A custom run configuration form's frame (`openidea.runConfig`). */
|
||||
export interface FrameRunConfig {
|
||||
get(): unknown;
|
||||
patch(patch: unknown): unknown;
|
||||
setErrors(errors: unknown): void;
|
||||
setHeight(height: number): void;
|
||||
subscribe(listener: (state: unknown) => void): () => void;
|
||||
}
|
||||
|
||||
/** Where an overlay floats: one of nine anchors of the window, and its size in pixels. */
|
||||
export interface OverlayPlacement {
|
||||
anchor: string;
|
||||
@@ -291,6 +302,8 @@ export interface WebViewProps {
|
||||
overlay?: FrameOverlay | null;
|
||||
/** A plugin dialog's page: it can close the dialog, and Escape there closes it. */
|
||||
pluginDialog?: FrameDialog | null;
|
||||
/** A custom run-configuration form (`[[contributes.runConfigTypes]]`). */
|
||||
runConfig?: FrameRunConfig | null;
|
||||
}
|
||||
|
||||
export function WebView({
|
||||
@@ -304,6 +317,7 @@ export function WebView({
|
||||
editor = null,
|
||||
overlay = null,
|
||||
pluginDialog = null,
|
||||
runConfig = null,
|
||||
}: WebViewProps) {
|
||||
const plugin = usePlugins((s) => s.plugins.find((p) => p.id === pluginId));
|
||||
const page = usePageUrl(pluginId, view, plugin);
|
||||
@@ -345,6 +359,7 @@ export function WebView({
|
||||
// The document's changes made elsewhere.
|
||||
useEffect(() => document?.subscribe((state) => post({ document: state })), [document, post]);
|
||||
useEffect(() => editor?.subscribe((event) => post(event)), [editor, post]);
|
||||
useEffect(() => runConfig?.subscribe((state) => post({ runConfig: state })), [runConfig, post]);
|
||||
|
||||
useEffect(() => {
|
||||
let dialog = false;
|
||||
@@ -518,6 +533,24 @@ export function WebView({
|
||||
if (!overlay) throw new Error("this view is not an overlay");
|
||||
return [op === "overlay.get" ? overlay.get() : overlay.place(args)];
|
||||
}
|
||||
case "runConfig.get": {
|
||||
if (!runConfig) throw new Error("this view is not a run configuration form");
|
||||
return [runConfig.get()];
|
||||
}
|
||||
case "runConfig.patch": {
|
||||
if (!runConfig) throw new Error("this view is not a run configuration form");
|
||||
return [runConfig.patch(args.patch)];
|
||||
}
|
||||
case "runConfig.setErrors": {
|
||||
if (!runConfig) throw new Error("this view is not a run configuration form");
|
||||
runConfig.setErrors(args.errors);
|
||||
return [null];
|
||||
}
|
||||
case "runConfig.setHeight": {
|
||||
if (!runConfig) throw new Error("this view is not a run configuration form");
|
||||
runConfig.setHeight(finite(args.height, "height"));
|
||||
return [null];
|
||||
}
|
||||
case "saveFile":
|
||||
case "openFile": {
|
||||
// One dialog at a time per frame.
|
||||
@@ -597,7 +630,7 @@ export function WebView({
|
||||
window.removeEventListener("pagehide", onUnload);
|
||||
currentFrame?.removeEventListener("load", onLoad);
|
||||
};
|
||||
}, [pluginId, view, document, doc, eventEditor, editor, overlay, pluginDialog, hasCode, post, page]);
|
||||
}, [pluginId, view, document, doc, eventEditor, editor, overlay, pluginDialog, runConfig, hasCode, post, page]);
|
||||
|
||||
// An overlay floats over the workbench: no spinner or error card in its place.
|
||||
if (overlay && (!page || "error" in page)) return null;
|
||||
@@ -613,7 +646,15 @@ export function WebView({
|
||||
{page.error}
|
||||
</EmptyState>
|
||||
);
|
||||
const frameQuery = editor ? EDITOR_PANEL_QUERY : overlay ? OVERLAY_QUERY : pluginDialog ? DIALOG_QUERY : null;
|
||||
const frameQuery = editor
|
||||
? EDITOR_PANEL_QUERY
|
||||
: overlay
|
||||
? OVERLAY_QUERY
|
||||
: pluginDialog
|
||||
? DIALOG_QUERY
|
||||
: runConfig
|
||||
? RUN_CONFIG_QUERY
|
||||
: null;
|
||||
// No `allow-same-origin`: an opaque origin without access to the IDE. `onLoad` sends the theme.
|
||||
const iframe = (
|
||||
<iframe
|
||||
|
||||
@@ -15,13 +15,15 @@
|
||||
* its requests only from the frames of editor panels. Overlays
|
||||
* (`[[contributes.overlays]]`) load theirs with `?openidea=overlay` and get
|
||||
* `openidea.overlay` the same way, and dialogs (`[[contributes.dialogs]]`,
|
||||
* `?openidea=dialog`) `openidea.dialog`.
|
||||
* `?openidea=dialog`) `openidea.dialog`, and run-configuration forms
|
||||
* (`[[contributes.runConfigTypes]]`, `?openidea=run-config`) `openidea.runConfig`.
|
||||
*/
|
||||
(initialTheme) => {
|
||||
const TAG = "openidea-view";
|
||||
const listeners = [];
|
||||
const themeListeners = [];
|
||||
const documentListeners = [];
|
||||
const runConfigListeners = [];
|
||||
const editorListeners = {
|
||||
target: [],
|
||||
viewport: [],
|
||||
@@ -34,6 +36,7 @@
|
||||
const editorPanel = /(?:^|[?&])openidea=editor-panel(?:&|$)/.test(location.search.slice(1));
|
||||
const overlayFrame = /(?:^|[?&])openidea=overlay(?:&|$)/.test(location.search.slice(1));
|
||||
const dialogFrame = /(?:^|[?&])openidea=dialog(?:&|$)/.test(location.search.slice(1));
|
||||
const runConfigFrame = /(?:^|[?&])openidea=run-config(?:&|$)/.test(location.search.slice(1));
|
||||
const pending = new Map();
|
||||
const root = document.documentElement;
|
||||
let theme = null;
|
||||
@@ -122,6 +125,8 @@
|
||||
if (p) "error" in m ? p.reject(new Error(String(m.error))) : p.resolve(m.value);
|
||||
} else if (m.document) {
|
||||
for (const l of documentListeners) safely(l, m.document);
|
||||
} else if (runConfigFrame && m.runConfig && typeof m.runConfig === "object") {
|
||||
for (const l of runConfigListeners) safely(l, m.runConfig);
|
||||
} else if (editorPanel && typeof m.editor === "string") {
|
||||
// Only those lists: not `constructor` and the like.
|
||||
const list = editorListeners[m.editor];
|
||||
@@ -203,6 +208,15 @@
|
||||
place: ({ anchor, width, height } = {}) => call("overlay.place", { anchor, width, height }),
|
||||
});
|
||||
|
||||
/** The run configuration being edited (`[[contributes.runConfigTypes]]`). */
|
||||
const runConfigApi = Object.freeze({
|
||||
get: () => call("runConfig.get"),
|
||||
patch: (patch) => call("runConfig.patch", { patch }),
|
||||
setErrors: (errors) => call("runConfig.setErrors", { errors }),
|
||||
setHeight: (height) => call("runConfig.setHeight", { height: Number(height) }),
|
||||
onChange: listen(runConfigListeners),
|
||||
});
|
||||
|
||||
window.openidea = Object.freeze({
|
||||
/** To the plugin's code (`ViewEvent::Message`). */
|
||||
postMessage: (text) => window.parent.postMessage({ tag: TAG, text: String(text) }, "*"),
|
||||
@@ -231,5 +245,6 @@
|
||||
...(editorPanel ? { editor: editorApi } : {}),
|
||||
...(overlayFrame ? { overlay: overlayApi } : {}),
|
||||
...(dialogFrame ? { dialog: Object.freeze({ close: () => call("dialog.close") }) } : {}),
|
||||
...(runConfigFrame ? { runConfig: runConfigApi } : {}),
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
.embedded {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.embedded > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
}
|
||||
.full {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.full > * {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerExternalIcons } from "@/ui";
|
||||
import {
|
||||
registerRunConfigType,
|
||||
type RunConfigFormProps,
|
||||
type RunConfigTypeContribution,
|
||||
} from "@/workbench/contributions";
|
||||
import { pluginsBackend } from "../backend";
|
||||
import { WebView, type FrameRunConfig } from "./WebView";
|
||||
import styles from "./runConfigForm.module.css";
|
||||
|
||||
const DEFAULT_EMBEDDED_HEIGHT = 360;
|
||||
const MIN_EMBEDDED_HEIGHT = 120;
|
||||
const MAX_EMBEDDED_HEIGHT = 2400;
|
||||
|
||||
export interface RunConfigTypeDecl {
|
||||
id: string;
|
||||
label: string;
|
||||
description?: string | null;
|
||||
group?: string | null;
|
||||
icon?: string | null;
|
||||
iconDark?: string | null;
|
||||
web: string;
|
||||
layout?: "embedded" | "full" | null;
|
||||
height?: number | null;
|
||||
command?: string | null;
|
||||
args?: string[];
|
||||
debugAdapter?: string | null;
|
||||
terminal?: boolean | null;
|
||||
ownsWorkingDirectory?: boolean;
|
||||
ownsEnvironment?: boolean;
|
||||
prepareCommand?: string | null;
|
||||
matchConfigPrefix?: string | null;
|
||||
defaults?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface RunConfigFormSnapshot {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: string;
|
||||
typeId: string;
|
||||
command: string;
|
||||
args: string[];
|
||||
cwd: string | null;
|
||||
env: Record<string, string>;
|
||||
params: Record<string, string>;
|
||||
debugAdapter: string | null;
|
||||
isTest: boolean;
|
||||
allowParallel: boolean;
|
||||
emulateTerminal: boolean;
|
||||
stopCommand: string | null;
|
||||
detected: boolean;
|
||||
template: boolean;
|
||||
projectRoot: string | null;
|
||||
}
|
||||
|
||||
export function pluginRunConfigKind(pluginId: string, typeId: string): string {
|
||||
return `plugin:${pluginId}:${typeId}`;
|
||||
}
|
||||
|
||||
export function runConfigSnapshot(
|
||||
config: RunConfig,
|
||||
typeId: string,
|
||||
template: boolean,
|
||||
projectRoot: string | null,
|
||||
): RunConfigFormSnapshot {
|
||||
return {
|
||||
id: config.id,
|
||||
name: config.name,
|
||||
kind: config.kind,
|
||||
typeId,
|
||||
command: config.command,
|
||||
args: [...config.args],
|
||||
cwd: config.cwd ?? null,
|
||||
env: { ...config.env },
|
||||
params: { ...(config.params ?? {}) },
|
||||
debugAdapter: config.debugAdapter ?? null,
|
||||
isTest: config.isTest,
|
||||
allowParallel: !!config.allowParallel,
|
||||
emulateTerminal: !!config.emulateTerminal,
|
||||
stopCommand: config.stopCommand ?? null,
|
||||
detected: config.detected,
|
||||
template,
|
||||
projectRoot,
|
||||
};
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function requireText(value: unknown, field: string, maxLen: number, rejectNewlines = false): string {
|
||||
if (typeof value !== "string") throw new Error(`${field} must be a string`);
|
||||
if (value.length > maxLen) throw new Error(`${field} is too long`);
|
||||
if (value.includes("\0") || (rejectNewlines && /[\r\n]/.test(value))) {
|
||||
throw new Error(`${field} contains invalid control characters`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function applyRunConfigPatch(config: RunConfig, rawPatch: unknown, template: boolean): RunConfig {
|
||||
if (!isPlainObject(rawPatch)) throw new Error("patch must be an object");
|
||||
const next: RunConfig = {
|
||||
...config,
|
||||
args: [...config.args],
|
||||
env: { ...config.env },
|
||||
params: { ...(config.params ?? {}) },
|
||||
};
|
||||
|
||||
if (!template && "name" in rawPatch) {
|
||||
next.name = requireText(rawPatch.name, "name", 256);
|
||||
}
|
||||
if ("command" in rawPatch) {
|
||||
next.command = requireText(rawPatch.command, "command", 4096, true);
|
||||
}
|
||||
if ("args" in rawPatch) {
|
||||
if (!Array.isArray(rawPatch.args) || rawPatch.args.length > 256) {
|
||||
throw new Error("args must be an array of at most 256 strings");
|
||||
}
|
||||
next.args = rawPatch.args.map((item, i) => requireText(item, `args[${i}]`, 32768));
|
||||
}
|
||||
if ("cwd" in rawPatch) {
|
||||
if (rawPatch.cwd === null) next.cwd = null;
|
||||
else {
|
||||
const cwd = requireText(rawPatch.cwd, "cwd", 4096);
|
||||
next.cwd = cwd.trim() ? cwd : null;
|
||||
}
|
||||
}
|
||||
if ("env" in rawPatch) {
|
||||
if (!isPlainObject(rawPatch.env)) throw new Error("env must be an object");
|
||||
const entries = Object.entries(rawPatch.env);
|
||||
if (entries.length > 64) throw new Error("env may contain at most 64 variables");
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of entries) {
|
||||
if (!k || k.length > 256 || /[=\s\0]/.test(k)) throw new Error(`invalid env variable name: ${k}`);
|
||||
env[k] = requireText(v, `env.${k}`, 32768);
|
||||
}
|
||||
next.env = env;
|
||||
}
|
||||
if ("params" in rawPatch) {
|
||||
if (!isPlainObject(rawPatch.params)) throw new Error("params must be an object");
|
||||
const params: Record<string, string> = { ...(next.params ?? {}) };
|
||||
for (const [k, v] of Object.entries(rawPatch.params)) {
|
||||
if (!k || k.length > 256 || k.includes("\0")) throw new Error(`invalid param key: ${k}`);
|
||||
if (v === null || v === undefined) delete params[k];
|
||||
else params[k] = requireText(v, `params.${k}`, 65536);
|
||||
}
|
||||
if (Object.keys(params).length > 256) throw new Error("params may contain at most 256 keys");
|
||||
next.params = params;
|
||||
}
|
||||
if ("debugAdapter" in rawPatch) {
|
||||
if (rawPatch.debugAdapter === null) next.debugAdapter = null;
|
||||
else {
|
||||
const adapter = requireText(rawPatch.debugAdapter, "debugAdapter", 128);
|
||||
if (/\s/.test(adapter)) throw new Error("debugAdapter cannot contain whitespace");
|
||||
next.debugAdapter = adapter || null;
|
||||
}
|
||||
}
|
||||
if ("isTest" in rawPatch) {
|
||||
if (typeof rawPatch.isTest !== "boolean") throw new Error("isTest must be a boolean");
|
||||
next.isTest = rawPatch.isTest;
|
||||
}
|
||||
if ("allowParallel" in rawPatch) {
|
||||
if (typeof rawPatch.allowParallel !== "boolean") throw new Error("allowParallel must be a boolean");
|
||||
next.allowParallel = rawPatch.allowParallel;
|
||||
}
|
||||
if ("emulateTerminal" in rawPatch) {
|
||||
if (typeof rawPatch.emulateTerminal !== "boolean") throw new Error("emulateTerminal must be a boolean");
|
||||
next.emulateTerminal = rawPatch.emulateTerminal;
|
||||
}
|
||||
if ("stopCommand" in rawPatch) {
|
||||
if (rawPatch.stopCommand === null) next.stopCommand = null;
|
||||
else {
|
||||
const stop = requireText(rawPatch.stopCommand, "stopCommand", 4096);
|
||||
next.stopCommand = stop.trim() ? stop : null;
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function sanitizeRunConfigErrors(raw: unknown): Record<string, string> {
|
||||
if (raw === null || raw === undefined) return {};
|
||||
if (!isPlainObject(raw)) throw new Error("errors must be an object");
|
||||
const entries = Object.entries(raw);
|
||||
if (entries.length > 32) throw new Error("errors may contain at most 32 entries");
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of entries) {
|
||||
if (!k || k.length > 128 || k.includes("\0")) throw new Error(`invalid error key: ${k}`);
|
||||
const message = requireText(v, `errors.${k}`, 512);
|
||||
if (message.trim()) out[k] = message;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function PluginRunConfigForm({
|
||||
pluginId,
|
||||
decl,
|
||||
config,
|
||||
template = false,
|
||||
onChange,
|
||||
onFormErrors,
|
||||
}: RunConfigFormProps & { pluginId: string; decl: RunConfigTypeDecl }) {
|
||||
const projectRoot = useProject((s) => s.project?.root ?? null);
|
||||
const isFull = decl.layout === "full";
|
||||
const [height, setHeight] = useState(() => decl.height ?? DEFAULT_EMBEDDED_HEIGHT);
|
||||
|
||||
const configRef = useRef(config);
|
||||
const templateRef = useRef(template);
|
||||
const projectRootRef = useRef(projectRoot);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const onFormErrorsRef = useRef(onFormErrors);
|
||||
const listenersRef = useRef<Set<(state: unknown) => void>>(new Set());
|
||||
const lastEmittedRef = useRef("");
|
||||
|
||||
useEffect(() => {
|
||||
configRef.current = config;
|
||||
templateRef.current = template;
|
||||
projectRootRef.current = projectRoot;
|
||||
onChangeRef.current = onChange;
|
||||
onFormErrorsRef.current = onFormErrors;
|
||||
});
|
||||
|
||||
const frameRunConfig = useMemo<FrameRunConfig>(
|
||||
() => ({
|
||||
get() {
|
||||
const snap = runConfigSnapshot(configRef.current, decl.id, templateRef.current, projectRootRef.current);
|
||||
lastEmittedRef.current = JSON.stringify(snap);
|
||||
return snap;
|
||||
},
|
||||
patch(raw) {
|
||||
const next = applyRunConfigPatch(configRef.current, raw, templateRef.current);
|
||||
configRef.current = next;
|
||||
const snap = runConfigSnapshot(next, decl.id, templateRef.current, projectRootRef.current);
|
||||
lastEmittedRef.current = JSON.stringify(snap);
|
||||
onChangeRef.current(next);
|
||||
return snap;
|
||||
},
|
||||
setErrors(raw) {
|
||||
onFormErrorsRef.current?.(sanitizeRunConfigErrors(raw));
|
||||
},
|
||||
setHeight(nextHeight) {
|
||||
if (!Number.isFinite(nextHeight)) throw new Error("height must be a number");
|
||||
setHeight(Math.max(MIN_EMBEDDED_HEIGHT, Math.min(MAX_EMBEDDED_HEIGHT, Math.round(nextHeight))));
|
||||
},
|
||||
subscribe(listener) {
|
||||
listenersRef.current.add(listener);
|
||||
return () => listenersRef.current.delete(listener);
|
||||
},
|
||||
}),
|
||||
[decl.id],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const snap = runConfigSnapshot(config, decl.id, template, projectRoot);
|
||||
const serialized = JSON.stringify(snap);
|
||||
if (serialized === lastEmittedRef.current) return;
|
||||
lastEmittedRef.current = serialized;
|
||||
for (const listener of listenersRef.current) listener(snap);
|
||||
}, [config, decl.id, template, projectRoot]);
|
||||
|
||||
return (
|
||||
<div className={isFull ? styles.full : styles.embedded} style={isFull ? undefined : { height }}>
|
||||
<WebView pluginId={pluginId} view={decl.id} label={decl.label} runConfig={frameRunConfig} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Projects a `[[contributes.runConfigTypes]]` declaration into `useRunConfigTypes`. */
|
||||
export function projectRunConfigType(pluginId: string, decl: RunConfigTypeDecl): () => void {
|
||||
const kind = pluginRunConfigKind(pluginId, decl.id);
|
||||
const initialIcon = decl.icon && !decl.icon.endsWith(".svg") ? decl.icon : "terminal";
|
||||
const matchPrefix = decl.matchConfigPrefix != null ? `plugin:${pluginId}:${decl.matchConfigPrefix}` : null;
|
||||
|
||||
function Form(props: RunConfigFormProps) {
|
||||
return <PluginRunConfigForm pluginId={pluginId} decl={decl} {...props} />;
|
||||
}
|
||||
|
||||
const baseContribution: RunConfigTypeContribution = {
|
||||
id: kind,
|
||||
label: decl.label,
|
||||
icon: initialIcon,
|
||||
description: decl.description ?? undefined,
|
||||
group: decl.group ?? undefined,
|
||||
defaults: decl.defaults,
|
||||
fields: [],
|
||||
customForm: Form,
|
||||
customFormLayout: decl.layout === "full" ? "full" : "embedded",
|
||||
ownsWorkingDirectory: decl.ownsWorkingDirectory || undefined,
|
||||
ownsEnvironment: decl.ownsEnvironment || undefined,
|
||||
commandOptional: !!decl.prepareCommand,
|
||||
terminal: decl.terminal ?? undefined,
|
||||
debugAdapter: decl.debugAdapter ?? undefined,
|
||||
commandLine: () => (decl.command ? { command: decl.command, args: [...(decl.args ?? [])] } : null),
|
||||
matches: matchPrefix !== null ? (c) => c.kind === "plugin" && c.id.startsWith(matchPrefix) : undefined,
|
||||
prepareLaunch: decl.prepareCommand
|
||||
? async (config) => {
|
||||
const projectRoot = useProject.getState().project?.root ?? null;
|
||||
const snap = runConfigSnapshot(config, decl.id, false, projectRoot);
|
||||
const reply = await pluginsBackend().runCommand(
|
||||
pluginId,
|
||||
decl.prepareCommand!,
|
||||
JSON.stringify(snap),
|
||||
null,
|
||||
[],
|
||||
);
|
||||
if (!reply?.trim()) return config;
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(reply);
|
||||
} catch {
|
||||
throw new Error(`Invalid launch configuration returned by '${decl.prepareCommand}'`);
|
||||
}
|
||||
return applyRunConfigPatch(config, parsed, true);
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
|
||||
let disposed = false;
|
||||
let unregisterType = registerRunConfigType(baseContribution);
|
||||
let unregisterIcons = () => {};
|
||||
|
||||
if (decl.icon?.endsWith(".svg")) {
|
||||
const lightAsset = `runConfigIcon/${decl.id}`;
|
||||
const darkAsset = `runConfigIconDark/${decl.id}`;
|
||||
Promise.all([
|
||||
pluginsBackend().assets(pluginId, lightAsset),
|
||||
decl.iconDark ? pluginsBackend().assets(pluginId, darkAsset) : Promise.resolve([]),
|
||||
])
|
||||
.then(([lightAssets, darkAssets]) => {
|
||||
if (disposed) return;
|
||||
const lightSvg = lightAssets.find(([id]) => id === lightAsset)?.[1];
|
||||
if (!lightSvg) return;
|
||||
const darkSvg = darkAssets.find(([id]) => id === darkAsset)?.[1];
|
||||
const name = `ext:runConfigIcon/${pluginId}/${decl.id}`;
|
||||
unregisterIcons();
|
||||
unregisterIcons = registerExternalIcons(
|
||||
darkSvg
|
||||
? [
|
||||
[name, lightSvg],
|
||||
[`${name}_dark`, darkSvg],
|
||||
]
|
||||
: [[name, lightSvg]],
|
||||
);
|
||||
unregisterType();
|
||||
unregisterType = registerRunConfigType({ ...baseContribution, icon: name });
|
||||
})
|
||||
.catch((e: unknown) => console.warn(`plugin ${pluginId}: runConfig icon ${decl.id}`, e));
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
unregisterType();
|
||||
unregisterIcons();
|
||||
};
|
||||
}
|
||||
@@ -209,6 +209,7 @@ export interface ConfigFormProps {
|
||||
/** Editing a configuration template (no name, storage or compound members). */
|
||||
template?: boolean;
|
||||
onChange: (next: RunConfig) => void;
|
||||
onFormErrors?: (errors: ConfigErrors) => void;
|
||||
/** Bumped by ⌥M to open the Modify options menu. */
|
||||
modifyRequest: number;
|
||||
}
|
||||
@@ -313,7 +314,16 @@ function CwdMacroButton({
|
||||
);
|
||||
}
|
||||
|
||||
export function ConfigForm({ config, all, type, errors, template, onChange, modifyRequest }: ConfigFormProps) {
|
||||
export function ConfigForm({
|
||||
config,
|
||||
all,
|
||||
type,
|
||||
errors,
|
||||
template,
|
||||
onChange,
|
||||
onFormErrors,
|
||||
modifyRequest,
|
||||
}: ConfigFormProps) {
|
||||
const openByDefault = useWorkflowSettings((s) => s.run.showOnStart);
|
||||
const runTargets = useRunTargets();
|
||||
const tx = useTx();
|
||||
@@ -352,6 +362,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
}
|
||||
|
||||
const compound = config.kind === COMPOUND;
|
||||
const fullCustomForm = config.kind === "tomcat" || (!!type?.customForm && type.customFormLayout === "full");
|
||||
const buildPolicyApplies = (c: RunConfig) => isJvmApplication(c) || c.kind === "maven" || c.kind === "gradle";
|
||||
// Compound and debug-only types (Remote JVM Debug) start no process of their own.
|
||||
const noProcess = compound || !!type?.debugOnly;
|
||||
@@ -436,15 +447,17 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
(id) => (!noProcess || id === "openToolWindow" || id === "focusToolWindow") && optionSet(config, id, openByDefault),
|
||||
);
|
||||
|
||||
const CustomForm = type?.customForm;
|
||||
|
||||
return (
|
||||
<div className={clsx(styles.configFields, config.kind === "tomcat" && styles.configFieldsTomcat)}>
|
||||
<div className={clsx(styles.configFields, fullCustomForm && styles.configFieldsTomcat)}>
|
||||
{config.detected && !template && (
|
||||
<div className={styles.notice}>
|
||||
<T>Detected from the project. Changes are saved as a user configuration that overrides it.</T>
|
||||
</div>
|
||||
)}
|
||||
{!template && (
|
||||
<div className={clsx(styles.formHeader, config.kind === "tomcat" && styles.formHeaderTomcat)}>
|
||||
<div className={clsx(styles.formHeader, fullCustomForm && styles.formHeaderTomcat)}>
|
||||
<Field label={config.kind === "tomcat" ? "Name:" : "Name"} error={errors.name}>
|
||||
<div className={styles.nameControl}>
|
||||
<Input
|
||||
@@ -467,6 +480,15 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
)}
|
||||
{config.kind === "tomcat" ? (
|
||||
<TomcatSettings config={config} all={all} onChange={onChange} />
|
||||
) : CustomForm && type?.customFormLayout === "full" ? (
|
||||
<CustomForm
|
||||
config={config}
|
||||
all={all}
|
||||
errors={errors}
|
||||
template={template}
|
||||
onChange={onChange}
|
||||
onFormErrors={onFormErrors}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.formSettings}>
|
||||
{!noProcess && (
|
||||
@@ -494,7 +516,7 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
</Field>
|
||||
)}
|
||||
<div className={styles.formSection}>
|
||||
<span className={styles.formSectionTitle}>{tx(kindLabel(config.kind))}</span>
|
||||
<span className={styles.formSectionTitle}>{tx(type?.label ?? kindLabel(config.kind))}</span>
|
||||
<button
|
||||
ref={modifyRef}
|
||||
type="button"
|
||||
@@ -515,7 +537,16 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
/>
|
||||
</div>
|
||||
|
||||
{compound ? (
|
||||
{CustomForm ? (
|
||||
<CustomForm
|
||||
config={config}
|
||||
all={all}
|
||||
errors={errors}
|
||||
template={template}
|
||||
onChange={onChange}
|
||||
onFormErrors={onFormErrors}
|
||||
/>
|
||||
) : compound ? (
|
||||
template ? null : (
|
||||
<CompoundMembers
|
||||
config={config}
|
||||
@@ -609,52 +640,56 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
</div>
|
||||
</Field>
|
||||
)}
|
||||
<Field
|
||||
label="Environment variables"
|
||||
error={errors.env}
|
||||
hint="Separate variables with semicolon: VAR=value; VAR1=value1"
|
||||
>
|
||||
<div className={styles.inputWithButton}>
|
||||
<Input
|
||||
mono
|
||||
aria-label="Environment variables"
|
||||
value={envText ?? formatEnv(config.env)}
|
||||
invalid={!!errors.env}
|
||||
onChange={(e) => {
|
||||
setEnvText(e.target.value);
|
||||
update({ env: Object.fromEntries(parseEnv(e.target.value).map((r) => [r.key, r.value])) });
|
||||
}}
|
||||
onBlur={() => setEnvText(null)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="list"
|
||||
size="small"
|
||||
iconSize={14}
|
||||
title="Edit Environment Variables"
|
||||
onClick={() => setEnvOpen(true)}
|
||||
/>
|
||||
{isTauri() && !isRemoteWindow() && (
|
||||
{!type?.ownsEnvironment && (
|
||||
<Field
|
||||
label="Environment variables"
|
||||
error={errors.env}
|
||||
hint="Separate variables with semicolon: VAR=value; VAR1=value1"
|
||||
>
|
||||
<div className={styles.inputWithButton}>
|
||||
<Input
|
||||
mono
|
||||
aria-label="Environment variables"
|
||||
value={envText ?? formatEnv(config.env)}
|
||||
invalid={!!errors.env}
|
||||
onChange={(e) => {
|
||||
setEnvText(e.target.value);
|
||||
update({ env: Object.fromEntries(parseEnv(e.target.value).map((r) => [r.key, r.value])) });
|
||||
}}
|
||||
onBlur={() => setEnvText(null)}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
icon="list"
|
||||
size="small"
|
||||
iconSize={14}
|
||||
title="Browse for .env Files"
|
||||
onClick={() =>
|
||||
void choosePaths({ multiple: true, from: root }).then((picked) => {
|
||||
const current = config.envFiles ?? [];
|
||||
const added = picked.map((p) => projectRelative(root, p)).filter((f) => !current.includes(f));
|
||||
if (added.length) update({ envFiles: [...current, ...added] });
|
||||
})
|
||||
}
|
||||
title="Edit Environment Variables"
|
||||
onClick={() => setEnvOpen(true)}
|
||||
/>
|
||||
{isTauri() && !isRemoteWindow() && (
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
iconSize={14}
|
||||
title="Browse for .env Files"
|
||||
onClick={() =>
|
||||
void choosePaths({ multiple: true, from: root }).then((picked) => {
|
||||
const current = config.envFiles ?? [];
|
||||
const added = picked
|
||||
.map((p) => projectRelative(root, p))
|
||||
.filter((f) => !current.includes(f));
|
||||
if (added.length) update({ envFiles: [...current, ...added] });
|
||||
})
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{config.includeSystemEnv === false && (
|
||||
<span className={styles.chooserMuted}>
|
||||
<T>System environment variables are not passed</T>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{config.includeSystemEnv === false && (
|
||||
<span className={styles.chooserMuted}>
|
||||
<T>System environment variables are not passed</T>
|
||||
</span>
|
||||
)}
|
||||
</Field>
|
||||
</Field>
|
||||
)}
|
||||
{isShown("envFiles") && (
|
||||
<Field label='Paths to ".env" files' hint="Relative to the project root; separate with semicolon">
|
||||
<Input
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Sidebar rows: type groups, their folders (first), then loose configurations; collapsed nodes hide their children. */
|
||||
import { useRunTargets } from "@/platform/pluginRunTargets";
|
||||
import { useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type DragEvent, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { call, commands, isTauri, type RunConfig, type RunImportSource } from "@/platform/ipc";
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import { importConfigs, importLabel } from "./importConfigs";
|
||||
import { targetName } from "./remote";
|
||||
import { saveEditedConfigs, selectConfig, useRun } from "./store";
|
||||
import { blankTemplate, COMPOUND, missingParams, newConfigOfType, templateId, typeFor } from "./types";
|
||||
import { blankTemplate, COMPOUND, missingParams, newConfigOfType, templateId, typeFor, typeForConfig } from "./types";
|
||||
import { cacheRunTemplates } from "./runTemplates";
|
||||
import styles from "./Run.module.css";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -132,6 +132,23 @@ function EditConfigsDialog() {
|
||||
// "Modify Run Configuration…": the would-be configuration is saved on OK even when unedited.
|
||||
const [dirty, setDirty] = useState(() => useRun.getState().editDirty);
|
||||
const [removedDetectedIds, setRemovedDetectedIds] = useState<string[]>([]);
|
||||
const [formErrorsById, setFormErrorsById] = useState<Record<string, ConfigErrors>>({});
|
||||
const setFormErrors = useCallback((id: string, next: ConfigErrors) => {
|
||||
setFormErrorsById((prev) => {
|
||||
const existing = prev[id];
|
||||
const keys = Object.keys(next);
|
||||
if (keys.length === 0) {
|
||||
if (!existing) return prev;
|
||||
const copy = { ...prev };
|
||||
delete copy[id];
|
||||
return copy;
|
||||
}
|
||||
if (existing && Object.keys(existing).length === keys.length && keys.every((k) => existing[k] === next[k])) {
|
||||
return prev;
|
||||
}
|
||||
return { ...prev, [id]: next };
|
||||
});
|
||||
}, []);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const runTargets = useRunTargets();
|
||||
const [adding, setAdding] = useState<{ x: number; y: number } | null>(null);
|
||||
@@ -204,14 +221,19 @@ function EditConfigsDialog() {
|
||||
const out: Record<string, ConfigErrors> = {};
|
||||
for (const c of draft) {
|
||||
if (c.detected) continue;
|
||||
const e: ConfigErrors = { ...validateConfig(c, draft), ...missingParams(c) };
|
||||
if (Object.keys(missingParams(c)).length) delete e.command;
|
||||
const type = typeForConfig(c, types);
|
||||
const paramErrs = missingParams(c, type);
|
||||
const formErrs = formErrorsById[c.id] ?? {};
|
||||
const e: ConfigErrors = { ...validateConfig(c, draft), ...paramErrs, ...formErrs };
|
||||
if (Object.keys(paramErrs).length || Object.keys(formErrs).length) delete e.command;
|
||||
if (hasErrors(e)) out[c.id] = e;
|
||||
}
|
||||
return out;
|
||||
}, [draft]);
|
||||
}, [draft, formErrorsById, types]);
|
||||
const invalid = Object.keys(errorsById).length > 0;
|
||||
const errors = (current && errorsById[current.id]) ?? {};
|
||||
const currentType = current ? typeForConfig(current, types) : undefined;
|
||||
const currentTemplateType = currentTemplate ? typeFor(currentTemplate.kind) : undefined;
|
||||
|
||||
const replace = (next: RunConfig) => {
|
||||
setDraft((d) => upsertConfig(d, next));
|
||||
@@ -260,6 +282,7 @@ function EditConfigsDialog() {
|
||||
const index = draft.findIndex((c) => c.id === current.id);
|
||||
const next = removeConfig(draft, current.id);
|
||||
setDraft(next);
|
||||
setFormErrors(current.id, {});
|
||||
const neighbour = next[Math.min(index, next.length - 1)];
|
||||
setSelection(neighbour ? { type: "config", id: neighbour.id } : null);
|
||||
setDirty(true);
|
||||
@@ -670,7 +693,9 @@ function EditConfigsDialog() {
|
||||
<div
|
||||
className={clsx(
|
||||
styles.editForm,
|
||||
mode === "configs" && current?.kind === "tomcat" && styles.editFormTomcat,
|
||||
((mode === "configs" && (current?.kind === "tomcat" || currentType?.customFormLayout === "full")) ||
|
||||
(mode === "templates" && currentTemplateType?.customFormLayout === "full")) &&
|
||||
styles.editFormTomcat,
|
||||
)}
|
||||
>
|
||||
{mode === "templates" ? (
|
||||
@@ -683,7 +708,7 @@ function EditConfigsDialog() {
|
||||
key={`template:${currentTemplate.kind}`}
|
||||
config={currentTemplate}
|
||||
all={draft}
|
||||
type={typeFor(currentTemplate.kind)}
|
||||
type={currentTemplateType}
|
||||
errors={{}}
|
||||
template
|
||||
modifyRequest={modifyRequest}
|
||||
@@ -700,10 +725,11 @@ function EditConfigsDialog() {
|
||||
key={current.id}
|
||||
config={current}
|
||||
all={draft}
|
||||
type={typeFor(current.kind)}
|
||||
type={currentType}
|
||||
errors={errors}
|
||||
modifyRequest={modifyRequest}
|
||||
onChange={replace}
|
||||
onFormErrors={(errs) => setFormErrors(current.id, errs)}
|
||||
/>
|
||||
) : selection?.type === "folder" ? (
|
||||
<FolderName
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
import { formatArgs } from "@/platform/commandLine";
|
||||
/** Run configuration helpers: grouping, overriding, validation and argument parsing. */
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useRunConfigTypes } from "@/workbench/contributions";
|
||||
import { useRunConfigTypes, type RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
|
||||
function matchingType(config: Pick<RunConfig, "kind"> & { id?: string }): RunConfigTypeContribution | undefined {
|
||||
const types = useRunConfigTypes.getState().types;
|
||||
const exact = types.get(config.kind);
|
||||
if (exact) return exact;
|
||||
if (config.kind === "plugin" && config.id?.startsWith("plugin:")) {
|
||||
for (const t of types.values()) {
|
||||
if (t.matches?.(config as RunConfig)) return t;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const KIND_LABELS: Record<string, string> = {
|
||||
npm: "npm",
|
||||
@@ -108,7 +120,7 @@ export function kindLabel(kind: string): string {
|
||||
return type?.label ?? KIND_LABELS[kind] ?? (kind ? kind[0]!.toUpperCase() + kind.slice(1) : "Other");
|
||||
}
|
||||
|
||||
export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {
|
||||
export function configIcon(config: Pick<RunConfig, "kind" | "isTest"> & { id?: string }): string {
|
||||
if (config.isTest) return "check";
|
||||
switch (config.kind) {
|
||||
case "compound":
|
||||
@@ -195,7 +207,7 @@ export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {
|
||||
case "dart-command":
|
||||
return "file-dart";
|
||||
default:
|
||||
return useRunConfigTypes.getState().types.get(config.kind)?.icon ?? "terminal";
|
||||
return matchingType(config)?.icon ?? "terminal";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -323,8 +335,10 @@ export function validateConfig(config: RunConfig, all: readonly RunConfig[] = []
|
||||
else if (compoundCycle(config, all)) errors.compound = "A compound configuration can't include itself";
|
||||
else if (children.some((id) => !all.some((c) => c.id === id)))
|
||||
errors.compound = "Some configurations no longer exist";
|
||||
} else if (!config.command.trim() && !useRunConfigTypes.getState().types.get(config.kind)?.debugOnly)
|
||||
errors.command = "Command is required";
|
||||
} else {
|
||||
const type = matchingType(config);
|
||||
if (!config.command.trim() && !type?.debugOnly && !type?.commandOptional) errors.command = "Command is required";
|
||||
}
|
||||
for (const t of config.beforeLaunch ?? []) {
|
||||
if (
|
||||
(t.kind === "run" || (t.kind === "build" && t.target)) &&
|
||||
|
||||
@@ -80,7 +80,7 @@ import { runBeforeLaunch } from "./beforeLaunch";
|
||||
import { compoundChildren, createdConfigs } from "./configs";
|
||||
import { targetDebuggable, remoteDebugBlocked } from "./remote";
|
||||
import { debugOnTarget } from "./targetDebug";
|
||||
import { isDebugOnly, registerBuiltinTypes } from "./types";
|
||||
import { isDebugOnly, registerBuiltinTypes, typeForConfig } from "./types";
|
||||
import { isZigBuildStep, zigDebugTarget } from "./zigDebug";
|
||||
import { junitType } from "./junitType";
|
||||
import {
|
||||
@@ -218,6 +218,28 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
return notifyCwdError(config, e);
|
||||
}
|
||||
if (!(await prepareLaunch(config, chain, show))) return;
|
||||
const originalConfig = config;
|
||||
const typePrepare = typeForConfig(config)?.prepareLaunch;
|
||||
let typePrepared = false;
|
||||
if (typePrepare && (config.kind.startsWith("plugin:") || typeForConfig(config)?.matches)) {
|
||||
try {
|
||||
config = await typePrepare(config);
|
||||
typePrepared = true;
|
||||
} catch (error) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
level: "error",
|
||||
title: `Cannot run '${config.name}'`,
|
||||
body: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
const debugArg = typePrepared
|
||||
? { config, origin: originalConfig, ...(show === false ? { show: false } : {}) }
|
||||
: show === false
|
||||
? { config, show: false }
|
||||
: config;
|
||||
if (config.kind === UNITY_CONFIG_KIND) return showUnityAttach(config);
|
||||
// Python on an SSH / Docker / Compose target: debugpy there, the debugger attaches.
|
||||
if (targetDebuggable(config) && getAction("debug.attach")) {
|
||||
@@ -226,7 +248,7 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
}
|
||||
// A plugin configuration whose debugger attaches to a process the run starts.
|
||||
if (attachesToChild(config) && getAction("debug.attach")) {
|
||||
await debugAttachingToChild(config, { show, prepared: true });
|
||||
await debugAttachingToChild(config, { show, prepared: true, typePrepared });
|
||||
return;
|
||||
}
|
||||
// An Xcode scheme: the app is launched suspended on the simulator and lldb-dap attaches to it.
|
||||
@@ -236,7 +258,7 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
}
|
||||
// Remote JVM Debug, Go Remote…: the debugger attaches, nothing is launched here.
|
||||
if (isDebugOnly(config) && getAction("debug.startConfig")) {
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
await executeAction("debug.startConfig", debugArg);
|
||||
return;
|
||||
}
|
||||
// A single compiled file (rustc / clang / zig): build with debug info, then debug the binary.
|
||||
@@ -283,7 +305,7 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
}
|
||||
}
|
||||
if (getAction("debug.startConfig")) {
|
||||
await executeAction("debug.startConfig", show === false ? { config, show: false } : config);
|
||||
await executeAction("debug.startConfig", debugArg);
|
||||
return;
|
||||
}
|
||||
notifications().notify({
|
||||
@@ -293,7 +315,7 @@ async function debugLaunch(config: RunConfig, chain: readonly string[], show?: b
|
||||
body: tx`Running '${config.name}' without the debugger.`,
|
||||
key: "run-no-debugger",
|
||||
});
|
||||
await startRun(config, undefined, undefined, { prepared: true, show });
|
||||
await startRun(config, undefined, undefined, { prepared: true, typePrepared, show });
|
||||
}
|
||||
|
||||
async function debugSelected() {
|
||||
|
||||
@@ -16,7 +16,12 @@ export function attachesToChild(config: RunConfig): boolean {
|
||||
/** Starts the run, then attaches; resolves with the run's session once it started (null when it didn't). */
|
||||
export async function debugAttachingToChild(
|
||||
config: RunConfig,
|
||||
options: { show?: boolean; prepared?: boolean; onExit?: (code: number | null, stopped: boolean) => void } = {},
|
||||
options: {
|
||||
show?: boolean;
|
||||
prepared?: boolean;
|
||||
typePrepared?: boolean;
|
||||
onExit?: (code: number | null, stopped: boolean) => void;
|
||||
} = {},
|
||||
): Promise<RunSession | null> {
|
||||
const session = await startRun(config, undefined, undefined, options);
|
||||
const runId = session?.runId ?? null;
|
||||
|
||||
@@ -74,7 +74,7 @@ import { buildCMake, isCMakeBuild } from "./cmake";
|
||||
import { compoundChildren } from "./configs";
|
||||
import { remoteLabel, startWithRemedies } from "./remote";
|
||||
import { TerminalOutput } from "./terminalOutput";
|
||||
import { typeFor } from "./types";
|
||||
import { typeFor, typeForConfig } from "./types";
|
||||
import { agentName } from "./agentConfig";
|
||||
import { loadRunTemplates } from "./runTemplates";
|
||||
import { startedServer } from "@/platform/serverPort";
|
||||
@@ -955,6 +955,8 @@ interface StartRunOptions {
|
||||
onExit?: (exitCode: number | null, stopped: boolean) => void;
|
||||
/** Before launch tasks already ran (or must not run). */
|
||||
prepared?: boolean;
|
||||
/** Type-level `prepareLaunch` already ran before fallback to `startRun`. */
|
||||
typePrepared?: boolean;
|
||||
/** Configurations whose launch led to this one (before launch tasks, compounds): breaks cycles. */
|
||||
chain?: readonly string[];
|
||||
/** Runs before the stop signal when the user stops this run (run executors). */
|
||||
@@ -1203,9 +1205,10 @@ async function startRunIn(
|
||||
launch = resolved;
|
||||
}
|
||||
// `npm run` scripts running Cypress pass the test selection the way the installed Cypress takes it, too.
|
||||
const prepare =
|
||||
typeFor(launch.kind)?.prepareLaunch ??
|
||||
(frameworkFor(launch) === "cypress" ? typeFor("cypress")?.prepareLaunch : undefined);
|
||||
const prepare = options.typePrepared
|
||||
? undefined
|
||||
: (typeForConfig(launch)?.prepareLaunch ??
|
||||
(frameworkFor(launch) === "cypress" ? typeFor("cypress")?.prepareLaunch : undefined));
|
||||
if (prepare) {
|
||||
launch = await prepare(launch, {
|
||||
report: (text, kind = "system") => {
|
||||
|
||||
@@ -656,6 +656,21 @@ export function typeFor(kind: string): RunConfigTypeContribution | undefined {
|
||||
return useRunConfigTypes.getState().types.get(kind);
|
||||
}
|
||||
|
||||
/** Resolves the contribution for `config`, matching `kind: "plugin"` entries via `matches`. */
|
||||
export function typeForConfig(
|
||||
config: Pick<RunConfig, "id" | "kind">,
|
||||
map = useRunConfigTypes.getState().types,
|
||||
): RunConfigTypeContribution | undefined {
|
||||
const exact = map.get(config.kind);
|
||||
if (exact) return exact;
|
||||
if (config.kind === "plugin" && config.id.startsWith("plugin:")) {
|
||||
for (const t of map.values()) {
|
||||
if (t.matches?.(config as RunConfig)) return t;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Only Debug applies to `c` (Remote JVM Debug, Go Remote…): it attaches and launches no process. */
|
||||
export const isDebugOnly = (c: Pick<RunConfig, "kind">, type = typeFor(c.kind)) => !!type?.debugOnly;
|
||||
|
||||
@@ -663,8 +678,9 @@ export const isDebugOnly = (c: Pick<RunConfig, "kind">, type = typeFor(c.kind))
|
||||
* The params the type form edits for `config`: its own, else derived from its command
|
||||
* line; null when the type can't reproduce that command line (edited as a plain command).
|
||||
*/
|
||||
export function formParams(config: RunConfig, type = typeFor(config.kind)): Record<string, string> | null {
|
||||
export function formParams(config: RunConfig, type = typeForConfig(config)): Record<string, string> | null {
|
||||
if (!type) return null;
|
||||
if (type.customForm) return { ...(config.params ?? {}) };
|
||||
if (config.params && Object.keys(config.params).length && (type.id !== "go" || config.params.goKind))
|
||||
return { ...config.params };
|
||||
if (type.id === COMPOUND) return {};
|
||||
@@ -686,7 +702,10 @@ export function formParams(config: RunConfig, type = typeFor(config.kind)): Reco
|
||||
export function withParams(config: RunConfig, params: Record<string, string>, type = typeFor(config.kind)): RunConfig {
|
||||
const line = type?.commandLine(params);
|
||||
const { stopCommand: _previous, ...rest } = config;
|
||||
if (!line) return { ...rest, params, command: "", args: [] };
|
||||
if (!line) {
|
||||
if (type?.customForm) return { ...rest, params };
|
||||
return { ...rest, params, command: "", args: [] };
|
||||
}
|
||||
return {
|
||||
...rest,
|
||||
...(config.kind === "dotnet" && config.beforeLaunch === undefined
|
||||
@@ -829,6 +848,11 @@ export function newConfigOfType(
|
||||
const v = template[key];
|
||||
if (v !== undefined) (copied as Record<string, unknown>)[key] = structuredClone(v);
|
||||
}
|
||||
if (type.customForm) {
|
||||
if (template.command) copied.command = template.command;
|
||||
if (template.args.length) copied.args = [...template.args];
|
||||
if (template.stopCommand !== undefined) copied.stopCommand = template.stopCommand;
|
||||
}
|
||||
}
|
||||
const params = { ...newConfigDefaults(type), ...(template?.params ?? {}) };
|
||||
const next = withParams({ ...base, ...copied }, params, type);
|
||||
|
||||
@@ -1182,6 +1182,7 @@
|
||||
"Editor Panels": "Editor Panels",
|
||||
"Overlays": "Overlays",
|
||||
"Dialogs": "Dialogs",
|
||||
"Run Configuration Types": "Run Configuration Types",
|
||||
"this data source does not list databases": "this data source does not list databases",
|
||||
"commit or roll back before clearing the selected database": "commit or roll back before clearing the selected database",
|
||||
"connect_timeout must be greater than zero": "connect_timeout must be greater than zero",
|
||||
|
||||
@@ -981,6 +981,7 @@
|
||||
"Editor Panels": "编辑器面板",
|
||||
"Overlays": "浮层",
|
||||
"Dialogs": "对话框",
|
||||
"Run Configuration Types": "运行配置类型",
|
||||
"this data source does not list databases": "此数据源不支持列出数据库",
|
||||
"commit or roll back before clearing the selected database": "清除所选数据库前,请先提交或回滚事务",
|
||||
"connect_timeout must be greater than zero": "connect_timeout 必须大于零",
|
||||
|
||||
@@ -1984,6 +1984,15 @@ export interface RunConfigTypeField {
|
||||
browse?: "file" | "directory" | ((params: Readonly<Record<string, string>>) => "file" | "directory");
|
||||
}
|
||||
|
||||
export interface RunConfigFormProps {
|
||||
config: RunConfig;
|
||||
all: readonly RunConfig[];
|
||||
errors: Partial<Record<string, string>>;
|
||||
template?: boolean;
|
||||
onChange: (next: RunConfig) => void;
|
||||
onFormErrors?: (errors: Record<string, string>) => void;
|
||||
}
|
||||
|
||||
export interface RunConfigTypeContribution {
|
||||
/** Stored as `RunConfig.kind`. */
|
||||
id: string;
|
||||
@@ -1995,6 +2004,10 @@ export interface RunConfigTypeContribution {
|
||||
/** Params of a new configuration (before templates apply). */
|
||||
defaults?: Readonly<Record<string, string>>;
|
||||
fields: readonly RunConfigTypeField[];
|
||||
/** Custom form component replacing the declarative `fields` (or the entire form when `customFormLayout === "full"`). */
|
||||
customForm?: ComponentType<RunConfigFormProps>;
|
||||
/** `"embedded"` keeps the Run on / Modify options / common fields; `"full"` replaces everything below Name. */
|
||||
customFormLayout?: "embedded" | "full";
|
||||
/**
|
||||
* What is launched for `params`; null when the type runs no process itself (Compound).
|
||||
* `stop`: a shell command line run on Stop before the process is signalled (`docker stop …`).
|
||||
@@ -2011,6 +2024,12 @@ export interface RunConfigTypeContribution {
|
||||
paramsFrom?(config: RunConfig): Record<string, string> | null;
|
||||
/** The type's fields set the working directory (no separate field). */
|
||||
ownsWorkingDirectory?: boolean;
|
||||
/** The type's fields set environment variables (no separate field). */
|
||||
ownsEnvironment?: boolean;
|
||||
/** Custom form may defer computing `command` until launch (`prepareLaunch`). */
|
||||
commandOptional?: boolean;
|
||||
/** Matches dynamic `kind: "plugin"` configurations owned by this type. */
|
||||
matches?(config: RunConfig): boolean;
|
||||
/** "Emulate terminal in output console" applies (default true). */
|
||||
terminal?: boolean;
|
||||
/** Adjusts what is launched right before it starts (e.g. the environment selecting a Docker daemon). */
|
||||
|
||||
Reference in new issue
Заблокувати користувача