diff --git a/Cargo.lock b/Cargo.lock index 6f1b98b05..2aaa98404 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4598,6 +4598,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tracing", + "url", "wasmtime", "wasmtime-wasi", "wat", diff --git a/crates/ide-extension/src/capability.rs b/crates/ide-extension/src/capability.rs index 9b4848611..da2b2aaad 100644 --- a/crates/ide-extension/src/capability.rs +++ b/crates/ide-extension/src/capability.rs @@ -32,8 +32,12 @@ pub enum Capability { InputEvents, /// The system clipboard, from the plugin's web views. Clipboard, - /// HTTP(S) to one host (`*.example.com` matches subdomains). + /// HTTPS (and loopback HTTP) to one host (`*.example.com` matches subdomains). Net(String), + /// Unencrypted HTTP to one host. + NetHttp(String), + /// A local socket or named pipe on the project machine. + Ipc(String), /// Run one external program. Full code execution: never fine-grained. Process(String), /// Read files outside the project under one path. @@ -62,10 +66,11 @@ impl Capability { | Self::ProjectWrite | Self::VcsWrite | Self::Net(_) + | Self::NetHttp(_) | Self::Secrets | Self::InputEvents | Self::Clipboard => Risk::Medium, - Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High, + Self::Ipc(_) | Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High, } } @@ -92,6 +97,12 @@ impl Capability { "Copy to the clipboard from its commands, and read and write it from its web views".into() } Self::Net(host) => format!("Connect to {host} (from the machine the project is on)"), + Self::NetHttp(host) => { + format!("Connect to {host} over unencrypted HTTP (from the machine the project is on)") + } + Self::Ipc(path) => { + format!("Connect to local socket {path} — equivalent to running arbitrary code on the project machine") + } Self::Process(bin) => format!("Run {bin} — equivalent to running arbitrary code on this machine"), Self::FsRead(path) => format!("Read files under {path}, outside the project"), Self::FsWrite(path) => format!("Change files under {path}, outside the project"), @@ -100,8 +111,14 @@ impl Capability { /// Whether `self`, granted, also covers `wanted` (`net:*.x.com` covers `net:a.x.com`). pub fn covers(&self, wanted: &Capability) -> bool { + if self == wanted { + return true; + } match (self, wanted) { - (Self::Net(pattern), Self::Net(host)) => host_matches(pattern, host), + (Self::Ipc(pattern), Self::Ipc(path)) => ipc_matches(pattern, path), + (Self::Net(pattern), Self::Net(host)) | (Self::NetHttp(pattern), Self::NetHttp(host)) => { + host_matches(pattern, host) + } (Self::FsRead(base), Self::FsRead(path)) | (Self::FsWrite(base), Self::FsWrite(path)) => { std::path::Path::new(path).starts_with(std::path::Path::new(base)) } @@ -120,6 +137,75 @@ pub fn host_matches(pattern: &str, host: &str) -> bool { } } +/// Validates a socket path; a grant may use `*` in its last segment only. +pub fn validate_ipc_name(name: &str, pattern: bool) -> Result<(), String> { + let pipe = name.starts_with(r"\\.\pipe\"); + let unix = name.starts_with('/') + || name.starts_with("~/") + || name.starts_with("$TMPDIR/") + || name.starts_with("$XDG_RUNTIME_DIR/"); + let parts: Vec<_> = name.strip_prefix(r"\\.\pipe\").unwrap_or(name).split(if pipe { '\\' } else { '/' }).collect(); + if !(pipe || unix) + || name.contains(['\0', '?']) + || name.len() > 4096 + || parts.last().is_none_or(|p| p.is_empty()) + || parts.iter().any(|p| matches!(*p, "." | "..")) + || parts[..parts.len().saturating_sub(1)].iter().any(|p| p.contains('*')) + || (!pattern && name.contains('*')) + { + return Err( + "ipc: use an absolute socket path or \\\\.\\pipe\\name; only the last grant segment may contain '*'".into(), + ); + } + Ok(()) +} + +/// Expands the three supported host-local prefixes; no shell is involved. +pub fn expand_ipc_name(name: &str) -> Result { + validate_ipc_name(name, true)?; + for (prefix, key) in [("~/", "HOME"), ("$TMPDIR/", "TMPDIR"), ("$XDG_RUNTIME_DIR/", "XDG_RUNTIME_DIR")] { + if let Some(rest) = name.strip_prefix(prefix) { + let base = std::env::var(key).map_err(|_| format!("{key} is not set"))?; + let expanded = format!("{}/{rest}", base.trim_end_matches('/')); + validate_ipc_name(&expanded, true)?; + return Ok(expanded); + } + } + Ok(name.into()) +} + +fn ipc_matches(pattern: &str, name: &str) -> bool { + let (Ok(pattern), Ok(name)) = (expand_ipc_name(pattern), expand_ipc_name(name)) else { return false }; + if validate_ipc_name(&name, false).is_err() { + return false; + } + let separator = if pattern.starts_with(r"\\.\pipe\") { '\\' } else { '/' }; + let (Some((parent, pattern)), Some((other, name))) = (pattern.rsplit_once(separator), name.rsplit_once(separator)) + else { + return false; + }; + if parent != other { + return false; + } + let mut rest = name; + let mut pieces = pattern.split('*'); + let first = pieces.next().unwrap_or_default(); + let Some(tail) = rest.strip_prefix(first) else { return false }; + rest = tail; + let pieces: Vec<_> = pieces.collect(); + if pieces.is_empty() { + return rest.is_empty(); + } + for (i, piece) in pieces.iter().enumerate() { + if i + 1 == pieces.len() { + return rest.ends_with(piece); + } + let Some(at) = rest.find(piece) else { return false }; + rest = &rest[at + piece.len()..]; + } + true +} + impl fmt::Display for Capability { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { @@ -135,6 +221,8 @@ impl fmt::Display for Capability { Self::InputEvents => f.write_str("events.input"), Self::Clipboard => f.write_str("clipboard"), Self::Net(h) => write!(f, "net:{h}"), + Self::NetHttp(h) => write!(f, "net.http:{h}"), + Self::Ipc(p) => write!(f, "ipc:{p}"), Self::Process(b) => write!(f, "process:{b}"), Self::FsRead(p) => write!(f, "fs.read:{p}"), Self::FsWrite(p) => write!(f, "fs.write:{p}"), @@ -153,7 +241,7 @@ impl FromStr for Capability { return Err(format!("capability {s:?} needs a value after ':'")); } return match kind { - "net" => { + "net" | "net.http" => { let host = arg.strip_prefix("*.").unwrap_or(arg); let valid = !host.is_empty() && host.len() <= 253 @@ -162,7 +250,19 @@ impl FromStr for Capability { && label.len() <= 63 && label.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') }); - if valid { Ok(Self::Net(arg.to_ascii_lowercase())) } else { Err(format!("invalid host in {s:?}")) } + if valid { + Ok(if kind == "net" { + Self::Net(arg.to_ascii_lowercase()) + } else { + Self::NetHttp(arg.to_ascii_lowercase()) + }) + } else { + Err(format!("invalid host in {s:?}")) + } + } + "ipc" => { + validate_ipc_name(arg, true)?; + Ok(Self::Ipc(arg.to_owned())) } "process" => { if arg.contains(['/', '\\']) && !std::path::Path::new(arg).is_absolute() { @@ -292,3 +392,35 @@ mod tests { assert!(!Capability::FsRead("/etc".into()).covers(&Capability::FsRead("/etcx".into()))); } } + +#[cfg(test)] +mod api14_tests { + use super::*; + #[test] + fn http_grants_do_not_imply_https_and_socket_patterns_stay_in_one_directory() { + let http: Capability = "net.http:*.example.com".parse().unwrap(); + assert_eq!(http.to_string(), "net.http:*.example.com"); + assert_eq!(http.risk(), Risk::Medium); + assert!(http.describe().contains("unencrypted")); + assert!(http.covers(&"net.http:a.example.com".parse().unwrap())); + assert!(!http.covers(&"net:a.example.com".parse().unwrap())); + assert!(!"net:*.example.com".parse::().unwrap().covers(&"net.http:a.example.com".parse().unwrap())); + let socket: Capability = "ipc:/tmp/discord-ipc-*-socket".parse().unwrap(); + assert_eq!(socket.risk(), Risk::High); + assert!(socket.covers(&Capability::Ipc("/tmp/discord-ipc-42-socket".into()))); + assert!(!socket.covers(&Capability::Ipc("/tmp/discord-ipc-dir/evil-socket".into()))); + assert!(!socket.covers(&Capability::Ipc("/tmp/../tmp/discord-ipc-42-socket".into()))); + assert_eq!("ipc:$TMPDIR/discord-ipc-*".parse::().unwrap().to_string(), "ipc:$TMPDIR/discord-ipc-*"); + assert!( + r"ipc:\\.\pipe\discord-*" + .parse::() + .unwrap() + .covers(&Capability::Ipc(r"\\.\pipe\discord-0".into())) + ); + for invalid in + ["ipc:relative", "ipc:/tmp/*/socket", "ipc:/tmp/../socket", "ipc:/tmp/", "ipc:/tmp/socket?", "net.http:a b"] + { + assert!(invalid.parse::().is_err(), "{invalid}"); + } + } +} diff --git a/crates/ide-extension/src/ledger.rs b/crates/ide-extension/src/ledger.rs index 89a9f9f6c..95c17cd50 100644 --- a/crates/ide-extension/src/ledger.rs +++ b/crates/ide-extension/src/ledger.rs @@ -59,6 +59,12 @@ pub struct Grant { /// `process:` → the program confirmed for it. #[serde(default)] pub binaries: BTreeMap, + /// Project root → process grant → the executable approved for that project. + #[serde(default)] + pub project_binaries: BTreeMap>, + /// Explicit global executable choices, retained for the next re-approval. + #[serde(default)] + pub program_choices: BTreeMap, /// Migrated from 0.1: capabilities not granted yet are asked for on first /// use instead of blocking the plugin from loading. #[serde(default)] @@ -248,6 +254,9 @@ impl Ledger { } else { if let Capability::Process(_) = cap { grant.binaries.remove(&s); + for binaries in grant.project_binaries.values_mut() { + binaries.remove(&s); + } } grant.granted.remove(&s) } @@ -260,6 +269,58 @@ impl Ledger { } } + /// The user's explicit global executable choice, if any. + pub fn program_choice(&self, subject: &Subject, cap: &Capability) -> Option<&Path> { + self.grants.get(subject)?.program_choices.get(&cap.to_string()).map(PathBuf::as_path) + } + /// Remembers or resets an explicit global executable choice after confirmation. + pub fn set_program_choice(&mut self, subject: &Subject, cap: &Capability, path: Option<&Path>) { + if let Some(grant) = self.grants.get_mut(subject) { + if let Some(path) = path { + grant.program_choices.insert(cap.to_string(), path.into()); + } else { + grant.program_choices.remove(&cap.to_string()); + } + } + } + + /// Updates a project-specific program choice after user confirmation. + pub fn set_project_binary( + &mut self, + subject: &Subject, + cap: &Capability, + root: &Path, + binary: Option, + ) { + if let Some(grant) = self.grants.get_mut(subject) { + if let Some(binary) = binary { + grant.project_binaries.entry(root.into()).or_default().insert(cap.to_string(), binary); + } else if let Some(binaries) = grant.project_binaries.get_mut(root) { + binaries.remove(&cap.to_string()); + } + } + } + /// The project override when present, otherwise the global approved program. + pub fn check_binary_in_project( + &self, + subject: &Subject, + cap: &Capability, + root: Option<&Path>, + ) -> Result { + let grant = self.grants.get(subject).ok_or_else(|| format!("{cap} was not granted"))?; + if !grant.has(cap) { + return Err(format!("{cap} was not granted")); + } + if let Some(bin) = root.and_then(|root| grant.project_binaries.get(root)).and_then(|b| b.get(&cap.to_string())) + { + return match file_hash(&bin.path) { + Ok(hash) if hash == bin.hash => Ok(bin.path.clone()), + _ => Err(format!("{} changed or is missing; confirm {cap} again", bin.path.display())), + }; + } + self.check_binary(subject, cap) + } + /// Checks a `process:` grant at call time: the program confirmed for it, /// unchanged since. Errors name what to do. pub fn check_binary(&self, subject: &Subject, cap: &Capability) -> Result { @@ -306,6 +367,16 @@ pub fn by_risk(caps: &[Capability]) -> Vec<(Risk, Vec)> { groups.into_iter().map(|(r, v)| (r.0, v)).collect() } +/// Pins an explicitly selected executable, retaining a multicall shim's filename. +pub fn approve_program(path: &Path) -> Result { + if !path.is_absolute() || !is_executable(path) { + return Err("choose an absolute executable file".into()); + } + let path = canonical_dir(path); + let hash = file_hash(&path).map_err(|e| e.to_string())?; + Ok(BinaryGrant { path, hash }) +} + /// Resolves a `process:` program to an absolute path once, at grant time: /// absolute names are taken as is, others are looked up in `path_var`. /// The directory is canonicalized but the file name kept as found: `cargo`, diff --git a/crates/ide-extension/src/lib.rs b/crates/ide-extension/src/lib.rs index 7ff7738db..c466abda2 100644 --- a/crates/ide-extension/src/lib.rs +++ b/crates/ide-extension/src/lib.rs @@ -24,7 +24,7 @@ mod registry; mod ui; mod when; -pub use capability::{Capability, CapabilityInfo, Risk, host_matches}; +pub use capability::{Capability, CapabilityInfo, Risk, expand_ipc_name, host_matches, validate_ipc_name}; pub use index::ContributionIndex; pub use manifest::{ ActivationEvent, CATEGORIES, Capabilities, ENGINE_VERSION, EVENT_KINDS, LEGACY_API, MANIFEST_FILE, MAX_CATEGORIES, diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index 4f07c6e7c..d1ad752ad 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -32,7 +32,7 @@ use std::path::{Component, Path, PathBuf}; pub const MANIFEST_FILE: &str = "plugin.toml"; /// The plugin API (engine) version this host implements. -pub const ENGINE_VERSION: &str = "1.3.0"; +pub const ENGINE_VERSION: &str = "1.4.0"; /// The 0.1 API, still accepted for contribution-only packages and 0.1 components. pub const LEGACY_API: &str = "0.1"; /// Marketplace categories, in the order they are shown. @@ -144,8 +144,17 @@ impl ActivationEvent { /// Workbench event kinds (`on-event:`, WIT `events.event-kind`). /// `scheduled` comes from `on-schedule` instead. -pub const EVENT_KINDS: &[&str] = - &["file-opened", "file-saved", "files-changed", "editor-focused", "action-performed", "vcs-changed"]; +pub const EVENT_KINDS: &[&str] = &[ + "file-closed", + "settings-changed", + "input-mode-changed", + "file-opened", + "file-saved", + "files-changed", + "editor-focused", + "action-performed", + "vcs-changed", +]; impl std::fmt::Display for ActivationEvent { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -317,6 +326,9 @@ impl Manifest { check_relative(icon, "icon")?; } for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) { + if matches!(cap, Capability::NetHttp(_) | Capability::Ipc(_)) { + self.needs_api(&format!("capability `{cap}`"), 4)?; + } if matches!(cap, Capability::ProjectWrite | Capability::FsWrite(_)) { self.needs_api(&format!("capability `{cap}`"), 3)?; } @@ -332,6 +344,10 @@ impl Manifest { } let mut seen = BTreeSet::new(); for event in &self.activation { + if matches!(event, ActivationEvent::Event(kind) if matches!(kind.as_str(), "file-closed" | "settings-changed" | "input-mode-changed")) + { + self.needs_api(&format!("`{event}`"), 4)?; + } if matches!(event, ActivationEvent::Event(kind) if kind == "files-changed") { self.needs_api("`on-event:files-changed`", 3)?; } @@ -655,3 +671,30 @@ mod tests { assert!(!engine_compatible("0.10", true)); } } + +#[cfg(test)] +mod api14_tests { + use super::*; + #[test] + fn new_capabilities_and_activations_require_api_1_4() { + for declaration in [ + "[capabilities]\nrequired = [\"net.http:example.com\"]", + "[capabilities]\noptional = [\"ipc:$TMPDIR/test-*\"]", + "activation = [\"on-event:file-closed\"]", + "activation = [\"on-event:settings-changed\"]", + "activation = [\"on-event:input-mode-changed\"]", + ] { + for engine in ["^1.0", "^1.3", "^1.4"] { + let manifest = format!( + "id = 'test'\nname = 'Test'\nversion = '0.1.0'\nwasm = 'plugin.wasm'\nengines.openidea = '{engine}'\n{declaration}\n" + ); + let parsed = Manifest::parse(&manifest); + if engine == "^1.4" { + parsed.unwrap(); + } else { + assert!(parsed.unwrap_err().contains("new in plugin API 1.4")); + } + } + } + } +} diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 0b2824730..30bc34d7c 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -4,6 +4,7 @@ use super::{CommitAnswer, CommitRequest, CommitSelection, PluginContextKey, PluginEvent, PluginEventSink}; use ide_core::ipc_path::to_ipc; use ide_core::{CancellationToken, TextEdit}; +use ide_extension::Capability; use ide_extension::Package; use ide_language::ProgramPin; use ide_plugin::{ @@ -157,6 +158,34 @@ pub(super) fn net_runtime() -> &'static tokio::runtime::Runtime { }) } +#[derive(Debug)] +struct RedirectDenied(String); +impl std::fmt::Display for RedirectDenied { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} is not granted for this redirect", self.0) + } +} +impl std::error::Error for RedirectDenied {} + +fn network_error(error: reqwest::Error) -> HostError { + let mut source: Option<&(dyn std::error::Error + 'static)> = Some(&error); + while let Some(e) = source { + if let Some(denied) = e.downcast_ref::() { + return HostError::Denied(denied.0.clone()); + } + source = e.source(); + } + HostError::Failed(error.to_string()) +} + +fn redirect_capability(from: &reqwest::Url, to: &reqwest::Url) -> Result { + if from.scheme() == "https" && to.scheme() == "http" { + ide_plugin::net_host(to.as_str()).map(Capability::NetHttp) + } else { + ide_plugin::net_capability(to.as_str()) + } +} + /// Replaces `{{secret:}}` in `value` with the plugin's secrets. fn fill_secrets(value: &str, lookup: impl Fn(&str) -> Option) -> Result { let mut out = String::with_capacity(value.len()); @@ -191,6 +220,7 @@ struct PromptEntry { enum Waiter { Prompt(std::sync::mpsc::SyncSender>>), Commit(std::sync::mpsc::SyncSender), + Command(std::sync::mpsc::SyncSender), } /// A process a plugin started and has not released (API 1.3 `process.start`). @@ -405,6 +435,11 @@ fn append_process_env(command: &mut StdCommand, env: &[(String, String)]) -> Res Ok(()) } +/// Approved project-specific programs. +pub(super) type ProjectPins = Arc>>; + +type SettingSnapshots = BTreeMap<(Option, String), BTreeMap>; + /// State shared by the host and every plugin's [`PluginApi`]. pub(super) struct Shared { pub sink: Arc, @@ -416,13 +451,18 @@ pub(super) struct Shared { /// (plugin, handle id) → the processes it started and has not released. processes: Mutex>>, next_process: AtomicU64, + connections: super::ipc::Connections, + pub loopbacks: RwLock>, process_shutdowns: Mutex>>, prompts: Mutex>, /// Plugins being stopped: their calls may not open new prompts (taken before `prompts`). prompts_blocked: Mutex>, next_prompt: AtomicU64, /// (plugin, item id) → item, for windows opened later. + output: Mutex>, status: Mutex>, + setting_snapshots: Mutex, + window_status: Mutex>, /// (scope, plugin, key) → JSON value. contexts: Mutex>, closed_clients: Mutex>, @@ -433,6 +473,8 @@ pub(super) struct Shared { pub secrets: RwLock>, /// (plugin, `process:` capability) → the approved program. pub pins: Arc>>, + pub project_pins: ProjectPins, + pub event_editors: RwLock>, /// Validated UI declarations (settings schemas, declared views). pub ui: Arc, /// The UI language the windows report (BCP 47). @@ -463,16 +505,23 @@ impl Shared { workspace: RwLock::new(None), secrets: RwLock::new(Arc::new(FileSecretStore { dir: data_dir.clone() })), pins, + project_pins: Arc::default(), + event_editors: RwLock::default(), data_dir, tasks: Mutex::default(), next_task: AtomicU64::new(1), processes: Mutex::default(), next_process: AtomicU64::new(1), + connections: super::ipc::Connections::default(), + loopbacks: RwLock::new(Arc::new(super::auth::Loopbacks::default())), process_shutdowns: Mutex::default(), prompts: Mutex::default(), prompts_blocked: Mutex::default(), next_prompt: AtomicU64::new(1), status: Mutex::default(), + output: Mutex::default(), + window_status: Mutex::default(), + setting_snapshots: Mutex::default(), contexts: Mutex::default(), closed_clients: Mutex::default(), subscriptions: Mutex::default(), @@ -518,6 +567,45 @@ impl Shared { self.status.lock().iter().map(|((p, id), item)| (p.clone(), id.clone(), item.clone())).collect() } + pub fn changed_settings(self: &Arc, pkg: &Package, client: Option<&str>) -> Vec { + let root = client.and_then(|c| self.project_of(c)); + let api = PluginApi { pkg: pkg.clone(), shared: self.clone() }; + let mut current = BTreeMap::new(); + for item in self.ui.items(super::ui_points::SETTINGS, Some(pkg.id())) { + if let Some(properties) = item.decl.get("properties").and_then(|p| p.as_array()) { + for property in properties { + if let Some(key) = property.get("key").and_then(|k| k.as_str()) + && let Some(value) = api.setting(root.as_deref(), key) + { + current.insert(key.into(), value); + } + } + } + } + let previous = + self.setting_snapshots.lock().insert((client.map(str::to_owned), pkg.id().into()), current.clone()); + previous + .map(|old| current.into_iter().filter(|(k, v)| old.get(k) != Some(v)).map(|(k, _)| k).collect()) + .unwrap_or_default() + } + + pub fn status_snapshot(&self, client: &str) -> Vec { + let mut items: Vec<_> = self + .status_items() + .into_iter() + .map(|(plugin_id, id, item)| super::PluginStatusItem { plugin_id, id, item, window: false }) + .collect(); + items.extend(self.window_status.lock().iter().filter(|((w, ..), _)| w == client).map( + |((_, plugin_id, id), item)| super::PluginStatusItem { + plugin_id: plugin_id.clone(), + id: id.clone(), + item: item.clone(), + window: true, + }, + )); + items + } + pub fn context_keys(&self, client: Option<&str>) -> Vec { let contexts = self.contexts.lock(); let mut keys: BTreeMap<(&str, &str), &str> = BTreeMap::new(); @@ -542,6 +630,10 @@ impl Shared { self.prompts.lock().retain(|_, entry| entry.client != client); drop(closed); self.contexts.lock().retain(|(scope, ..), _| scope.as_deref() != Some(client)); + self.loopbacks.read().forget_window(client); + self.window_status.lock().retain(|(window, ..), _| window != client); + self.event_editors.write().remove(client); + self.setting_snapshots.lock().retain(|(window, _), _| window.as_deref() != Some(client)); let mine: Vec<_> = { let mut processes = self.processes.lock(); let keys: Vec<_> = processes @@ -598,6 +690,21 @@ impl Shared { /// subscriptions go only with `subscriptions`, as they survive restarts. pub fn clear_plugin(&self, plugin: &str, subscriptions: bool) { self.kill_processes(plugin); + self.connections.clear(plugin); + self.setting_snapshots.lock().retain(|(_, p), _| p != plugin); + let channels: Vec<_> = { + let mut output = self.output.lock(); + let keys: Vec<_> = output.keys().filter(|(p, _)| p == plugin).cloned().collect(); + for key in &keys { + output.remove(key); + } + keys + }; + for (_, channel) in channels { + self.sink.emit(None, PluginEvent::OutputChanged { plugin_id: plugin.into(), channel, text: None }); + } + + self.loopbacks.read().clear(plugin); let removed: Vec = { let mut status = self.status.lock(); let ids: Vec = status.keys().filter(|(p, _)| p == plugin).map(|(_, id)| id.clone()).collect(); @@ -609,6 +716,18 @@ impl Shared { for id in removed { self.sink.emit(None, PluginEvent::StatusItemChanged { plugin_id: plugin.to_owned(), id, item: None }); } + let removed: Vec<_> = { + let mut items = self.window_status.lock(); + let keys: Vec<_> = items.keys().filter(|(_, p, _)| p == plugin).cloned().collect(); + for key in &keys { + items.remove(key); + } + keys + }; + for (window, _, id) in removed { + self.sink + .emit(Some(&window), PluginEvent::WindowStatusItemChanged { plugin_id: plugin.into(), id, item: None }); + } self.withdraw_prompts(plugin); let removed: Vec<(Option, String)> = { let mut contexts = self.contexts.lock(); @@ -699,6 +818,16 @@ impl Shared { } /// A window answered a [`CommitRequest`]. + pub fn answer_command(&self, client: &str, id: u64, answer: super::CommandAnswer) -> bool { + let mut prompts = self.prompts.lock(); + if !matches!(prompts.get(&id), Some(PromptEntry { client: window, answer: Waiter::Command(_), .. }) if window == client) + { + return false; + } + let Some(PromptEntry { answer: Waiter::Command(tx), .. }) = prompts.remove(&id) else { return false }; + tx.try_send(answer).is_ok() + } + pub fn answer_commit(&self, id: u64, answer: CommitAnswer) -> bool { let mut prompts = self.prompts.lock(); if !matches!(prompts.get(&id), Some(PromptEntry { answer: Waiter::Commit(_), .. })) { @@ -802,7 +931,17 @@ impl PluginApi { /// The program approved for the (already checked) `process:` grant, /// verified right before it starts. + #[cfg(test)] fn approved_program(&self, program: &str) -> Result { + self.approved_program_in_project(program, None) + } + + fn approved_program_in_project(&self, program: &str, root: Option<&Path>) -> Result { + if let Some(pin) = root.and_then(|root| { + self.shared.project_pins.read().get(&(self.id().into(), format!("process:{program}"), root.into())).cloned() + }) { + return pin.verify().map(Path::to_path_buf).map_err(|e| HostError::Denied(e.to_string())); + } let cap = format!("process:{program}"); // Granted without a pinned file: the program wasn't found when it was // allowed, and installing it later approves nothing by itself. @@ -828,7 +967,7 @@ impl PluginApi { cancel: &CancellationToken, on_line: &dyn Fn(super::PluginOutputLine), ) -> Result, HostError> { - let binary = self.approved_program(program)?; + let binary = self.approved_program_in_project(program, cwd)?; let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id())); let _ = std::fs::create_dir_all(&cwd); let mut cmd = std::process::Command::new(&binary); @@ -1051,6 +1190,108 @@ fn failed(e: impl std::fmt::Display) -> HostError { } impl HostApi for PluginApi { + fn execute_command( + &self, + invocation: &ide_plugin::Invocation, + id: &str, + arg: Option, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result, HostError> { + let client = from_window(invocation.client.as_deref(), "execute commands")?; + let mut chain = invocation.command_chain.clone(); + chain.push(self.id().into()); + if chain.len() > 8 { + return Err(HostError::Invalid("command nesting limit (8)".into())); + } + for command in self.shared.ui.items(super::COMMANDS, None) { + if id == format!("plugin.{}.{}", command.plugin_id, command.key) && chain.contains(&command.plugin_id) { + return Err(HostError::Invalid("recursive plugin command".into())); + } + } + let request = self.shared.next_prompt.fetch_add(1, Ordering::Relaxed); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + { + let closed = self.shared.closed_clients.lock(); + let blocked = self.shared.prompts_blocked.lock(); + if closed.contains(client) || blocked.contains(self.id()) { + return Err(HostError::Cancelled); + } + self.shared.prompts.lock().insert( + request, + PromptEntry { plugin: self.id().into(), client: client.into(), answer: Waiter::Command(tx) }, + ); + } + self.shared.sink.emit( + Some(client), + PluginEvent::ExecuteCommand { request_id: request.to_string(), id: id.into(), arg, chain }, + ); + let deadline = Instant::now() + timeout; + loop { + match rx.recv_timeout(Duration::from_millis(20)) { + Ok(super::CommandAnswer::Value(value)) => return Ok(value), + Ok(super::CommandAnswer::NotFound) => return Err(HostError::NotFound(id.into())), + Ok(super::CommandAnswer::Failed(error)) => return Err(HostError::Failed(error)), + Err(std::sync::mpsc::RecvTimeoutError::Timeout) + if !cancel.is_cancelled() && Instant::now() < deadline => {} + Err(_) => { + self.shared.prompts.lock().remove(&request); + return Err(HostError::Cancelled); + } + } + } + } + fn output_write(&self, channel: &str, text: Option<&str>) -> Result<(), HostError> { + if channel.is_empty() || channel.len() > 128 || channel.chars().any(char::is_control) { + return Err(HostError::Invalid("output channel must be 1-128 bytes without control characters".into())); + } + let key = (self.id().to_owned(), channel.to_owned()); + let mut channels = self.shared.output.lock(); + if !channels.contains_key(&key) && channels.keys().filter(|(p, _)| p == self.id()).count() >= 32 { + return Err(HostError::Invalid("at most 32 output channels".into())); + } + let buffer = channels.entry(key).or_default(); + if let Some(text) = text { + let mut start = text.len().saturating_sub(1 << 20); + while !text.is_char_boundary(start) { + start += 1; + } + buffer.push_str(&text[start..]); + } else { + buffer.clear(); + } + let mut remove = buffer.len().saturating_sub(1 << 20); + while !buffer.is_char_boundary(remove) { + remove += 1; + } + buffer.drain(..remove); + let text = buffer.clone(); + drop(channels); + self.shared.sink.emit( + None, + PluginEvent::OutputChanged { plugin_id: self.id().into(), channel: channel.into(), text: Some(text) }, + ); + Ok(()) + } + fn output_reveal(&self, client: &str, channel: &str) -> Result<(), HostError> { + let key = (self.id().to_owned(), channel.to_owned()); + if !self.shared.output.lock().contains_key(&key) { + self.output_write(channel, None)?; + } + if self.shared.client_closed(client) { + return Err(HostError::Cancelled); + } + let text = self.shared.output.lock().get(&key).cloned().unwrap_or_default(); + self.shared.sink.emit( + Some(client), + PluginEvent::RevealOutput { plugin_id: self.id().into(), channel: channel.into(), text }, + ); + Ok(()) + } + fn require_api(&self, what: &str, minor: u64) -> Result<(), HostError> { + self.pkg.manifest.needs_api(what, minor).map_err(HostError::Invalid) + } + fn notify( &self, client: Option<&str>, @@ -1202,6 +1443,32 @@ impl HostApi for PluginApi { .emit(None, PluginEvent::StatusItemChanged { plugin_id: self.id().to_owned(), id: id.to_owned(), item }); } + fn window_status_item(&self, client: &str, id: &str, item: Option) -> Result<(), HostError> { + let closed = self.shared.closed_clients.lock(); + let blocked = self.shared.prompts_blocked.lock(); + if closed.contains(client) || blocked.contains(self.id()) { + return Err(HostError::Cancelled); + } + let key = (client.to_owned(), self.id().to_owned(), id.to_owned()); + let mut items = self.shared.window_status.lock(); + if let Some(item) = &item { + if !items.contains_key(&key) + && items.keys().filter(|(w, p, _)| w == client && p == self.id()).count() >= MAX_STATUS_ITEMS + { + return Err(HostError::Invalid("too many window status items".into())); + } + items.insert(key, item.clone()); + } else { + items.remove(&key); + } + drop(items); + self.shared.sink.emit( + Some(client), + PluginEvent::WindowStatusItemChanged { plugin_id: self.id().into(), id: id.into(), item }, + ); + Ok(()) + } + fn set_context(&self, client: Option<&str>, key: &str, value: Option) -> Result<(), HostError> { let map_key = (client.map(str::to_owned), self.id().to_owned(), key.to_owned()); { @@ -1419,25 +1686,32 @@ impl HostApi for PluginApi { } let method = reqwest::Method::from_bytes(request.method.to_ascii_uppercase().as_bytes()) .map_err(|_| HostError::Invalid(format!("method {:?}", request.method)))?; - let client = ide_http::client::shared().map_err(|e| HostError::Failed(e.message))?; - // A redirect to another host is refused after the fact (the shared - // client follows redirects). + let grants = request.grants.clone(); + let policy = reqwest::redirect::Policy::custom(move |attempt| { + if attempt.previous().len() >= 10 { + return attempt.error("too many redirects"); + } + let wanted = attempt.previous().last().map_or_else( + || ide_plugin::net_capability(attempt.url().as_str()), + |from| redirect_capability(from, attempt.url()), + ); + match wanted { + Ok(wanted) if grants.iter().any(|g| g.covers(&wanted)) => attempt.follow(), + Ok(wanted) => attempt.error(RedirectDenied(wanted.to_string())), + Err(error) => attempt.error(error), + } + }); + let client = ide_http::client::build_with_redirect(&ide_core::proxy_settings::proxy(), policy) + .map_err(|e| HostError::Failed(e.message))?; let builder = client.request(method, &request.url).headers(headers).timeout(request.timeout); let builder = match request.body { Some(body) => builder.body(body), None => builder, }; let cancel = cancel.clone(); - let host = ide_plugin::net_host(&request.url).map_err(HostError::Invalid)?; net_runtime().block_on(async move { let send = async { - let response = builder.send().await.map_err(|e| HostError::Failed(e.to_string()))?; - if ide_plugin::net_host(response.url().as_str()).ok().as_deref() != Some(host.as_str()) { - return Err(HostError::Denied(format!( - "net:{} (redirected)", - response.url().host_str().unwrap_or("?") - ))); - } + let response = builder.send().await.map_err(network_error)?; let status = response.status().as_u16(); let headers = response .headers() @@ -1465,6 +1739,55 @@ impl HostApi for PluginApi { self.shared.secrets.read().get(self.id(), name).is_some() } + fn secret_set(&self, name: &str, value: Option<&str>) -> Result<(), HostError> { + if !self.shared.ui.items(super::providers::SECRETS_POINT, Some(self.id())).iter().any(|s| s.key == name) { + return Err(HostError::NotFound(format!("undeclared secret {name:?}"))); + } + self.shared.secrets.read().set(self.id(), name, value).map_err(HostError::Failed) + } + fn begin_loopback(&self, client: &str, path: &str) -> Result<(u64, String), HostError> { + let closed = self.shared.closed_clients.lock(); + let blocked = self.shared.prompts_blocked.lock(); + if closed.contains(client) || blocked.contains(self.id()) { + return Err(HostError::Cancelled); + } + self.shared.loopbacks.read().begin(self.id(), client, path) + } + fn wait_loopback( + &self, + id: u64, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + self.shared.loopbacks.read().clone().wait(self.id(), id, timeout, cancel) + } + fn close_loopback(&self, id: u64) { + self.shared.loopbacks.read().close(self.id(), id); + } + fn ipc_connect(&self, name: &str, cancel: &CancellationToken, timeout: Duration) -> Result { + self.shared.connections.connect(self.id(), name, cancel, timeout) + } + fn ipc_write( + &self, + id: u64, + bytes: Vec, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result<(), HostError> { + self.shared.connections.write(self.id(), id, bytes, cancel, timeout) + } + fn ipc_read( + &self, + id: u64, + max: usize, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + self.shared.connections.read(self.id(), id, max, timeout, cancel) + } + fn ipc_close(&self, id: u64) { + self.shared.connections.close(self.id(), id); + } fn run_process( &self, cmd: ProcessCommand, @@ -1473,7 +1796,7 @@ impl HostApi for PluginApi { cancel: &CancellationToken, timeout: Duration, ) -> Result { - let binary = self.approved_program(&cmd.program)?; + let binary = self.approved_program_in_project(&cmd.program, cwd.or(cmd.approval_root.as_deref()))?; let cwd = self.spawn_dir(cwd); let mut command = StdCommand::new(&binary); ide_core::process::prepare(&mut command); @@ -1554,7 +1877,7 @@ impl HostApi for PluginApi { } } fn start_process(&self, cmd: ProcessCommand, cwd: Option<&Path>, client: Option<&str>) -> Result { - let binary = self.approved_program(&cmd.program)?; + let binary = self.approved_program_in_project(&cmd.program, cwd.or(cmd.approval_root.as_deref()))?; let cwd = self.spawn_dir(cwd); if client.is_some_and(|c| self.shared.closed_clients.lock().contains(c)) { return Err(HostError::Cancelled); @@ -1777,7 +2100,7 @@ impl HostApi for PluginApi { args: Vec, cwd: Option<&Path>, ) -> Result<(), HostError> { - let binary = self.approved_program(program)?; + let binary = self.approved_program_in_project(program, cwd)?; let cwd = cwd.map(Path::to_path_buf).unwrap_or_else(|| self.shared.data_dir.join(self.id())); let _ = std::fs::create_dir_all(&cwd); let event = PluginEvent::OpenTerminal { @@ -1810,7 +2133,7 @@ impl HostApi for PluginApi { log: ide_plugin::ServiceLog, ) -> Result<(), HostError> { // Fails now, rather than in the tab, when the approved file is gone or changed. - self.approved_program(&log.program)?; + self.approved_program_in_project(&log.program, self.shared.project_of(client).as_deref())?; { let mut all = self.shared.log_tabs.lock(); let tabs = all.entry((self.id().to_owned(), client.to_owned())).or_default(); @@ -2338,7 +2661,12 @@ mod tests { #[cfg(unix)] fn shell(script: &str) -> ProcessCommand { - ProcessCommand { program: "sh".into(), args: vec!["-c".into(), script.into()], env: Vec::new() } + ProcessCommand { + program: "sh".into(), + args: vec!["-c".into(), script.into()], + env: Vec::new(), + approval_root: None, + } } #[cfg(unix)] @@ -2451,6 +2779,58 @@ mod tests { matches!(api.approved_program("lint"), Err(HostError::Denied(e)) if e.contains("changed since it was approved")) ); } + #[test] + fn redirects_check_grants_before_connecting_and_downgrades_require_http() { + assert_eq!( + redirect_capability(&"https://localhost/start".parse().unwrap(), &"http://localhost/end".parse().unwrap()) + .unwrap(), + Capability::NetHttp("localhost".into()) + ); + let source = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let target = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + target.set_nonblocking(true).unwrap(); + let source_port = source.local_addr().unwrap().port(); + let target_port = target.local_addr().unwrap().port(); + let worker = std::thread::spawn(move || { + use std::io::{Read, Write}; + let (mut stream, _) = source.accept().unwrap(); + let mut buf = [0; 4096]; + let _ = stream.read(&mut buf); + write!(stream, "HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1:{target_port}/\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").unwrap(); + }); + let dir = tempfile::tempdir().unwrap(); + let api = api(dir.path(), Arc::default()); + let result = api.fetch( + HttpRequest { + method: "GET".into(), + url: format!("http://localhost:{source_port}/"), + headers: Vec::new(), + body: None, + timeout: Duration::from_secs(2), + grants: vec![Capability::Net("localhost".into())], + }, + &CancellationToken::new(), + ); + assert!(matches!(result, Err(HostError::Denied(cap)) if cap == "net:127.0.0.1")); + assert!(target.accept().is_err(), "ungranted target must never receive a connection"); + worker.join().unwrap(); + } + + #[test] + fn output_ring_keeps_utf8_and_is_withdrawn_on_stop() { + let dir = tempfile::tempdir().unwrap(); + let api = api(dir.path(), Arc::default()); + api.output_write("build", Some(&"😀".repeat(300_000))).unwrap(); + let buffer = api.shared.output.lock().get(&(api.id().into(), "build".into())).cloned().unwrap(); + assert_eq!(buffer.len(), 1 << 20); + api.output_write("build", Some("x")).unwrap(); + let buffer = api.shared.output.lock().get(&(api.id().into(), "build".into())).cloned().unwrap(); + assert!(buffer.len() <= 1 << 20 && buffer.ends_with('x')); + api.output_write("build", None).unwrap(); + assert!(api.shared.output.lock().get(&(api.id().into(), "build".into())).unwrap().is_empty()); + api.shared.clear_plugin(api.id(), true); + assert!(api.shared.output.lock().is_empty()); + } } /// The window a user action invoked the plugin from: browser tabs and clipboard writes diff --git a/crates/ide-host/src/plugins/auth.rs b/crates/ide-host/src/plugins/auth.rs new file mode 100644 index 000000000..e0a955ba4 --- /dev/null +++ b/crates/ide-host/src/plugins/auth.rs @@ -0,0 +1,205 @@ +//! One-shot OAuth redirects, always bound on the desktop's IPv4 loopback. +use ide_core::CancellationToken; +use ide_plugin::HostError; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::io::{Read, Write}; +use std::net::{Ipv4Addr, TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +pub(super) trait Service: Send + Sync { + fn begin(&self, plugin: &str, window: &str, path: &str) -> Result<(u64, String), HostError>; + fn wait( + &self, + plugin: &str, + id: u64, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError>; + fn close(&self, plugin: &str, id: u64); + fn clear(&self, plugin: &str); + fn forget_window(&self, window: &str); +} +struct Entry { + window: String, + path: String, + listener: Mutex>, + cancel: CancellationToken, +} +#[derive(Default)] +pub(super) struct Loopbacks { + next: AtomicU64, + entries: Mutex>>, +} +fn failed(e: impl std::fmt::Display) -> HostError { + HostError::Failed(e.to_string()) +} +fn respond(stream: &mut TcpStream, ok: bool) { + let body = if ok { "You can close this tab." } else { "Not found." }; + let status = if ok { "200 OK" } else { "404 Not Found" }; + let _ = write!( + stream, + "HTTP/1.1 {status}\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n{body}", + body.len() + ); +} +impl Loopbacks { + fn remove_where(&self, predicate: impl Fn(&str, &Entry) -> bool) { + self.entries.lock().retain(|(p, _), entry| { + if !predicate(p, entry) { + return true; + } + entry.cancel.cancel(); + entry.listener.lock().take(); + false + }); + } +} +impl Service for Loopbacks { + fn begin(&self, plugin: &str, window: &str, path: &str) -> Result<(u64, String), HostError> { + let path = path.trim_start_matches('/'); + if path.len() > 1024 + || path.bytes().any(|b| !(b.is_ascii_alphanumeric() || b"/-._~".contains(&b))) + || path.split('/').any(|s| matches!(s, "." | "..")) + { + return Err(HostError::Invalid("loopback path must be a URL path without query or fragment".into())); + } + let mut entries = self.entries.lock(); + if entries.keys().filter(|(p, _)| p == plugin).count() >= 2 { + return Err(HostError::Invalid("at most two open loopbacks per plugin".into())); + } + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(failed)?; + listener.set_nonblocking(true).map_err(failed)?; + let uri = format!("http://127.0.0.1:{}/{path}", listener.local_addr().map_err(failed)?.port()); + let id = self.next.fetch_add(1, Ordering::Relaxed); + entries.insert( + (plugin.into(), id), + Arc::new(Entry { + window: window.into(), + path: format!("/{path}"), + listener: Mutex::new(Some(listener)), + cancel: CancellationToken::new(), + }), + ); + Ok((id, uri)) + } + fn wait( + &self, + plugin: &str, + id: u64, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + let entry = self + .entries + .lock() + .get(&(plugin.into(), id)) + .cloned() + .ok_or_else(|| HostError::NotFound("loopback".into()))?; + let listener = + entry.listener.lock().take().ok_or_else(|| HostError::Invalid("loopback already awaited".into()))?; + let deadline = Instant::now() + timeout; + let result = (|| loop { + if cancel.is_cancelled() || entry.cancel.is_cancelled() { + return Err(HostError::Cancelled); + } + match listener.accept() { + Ok((mut stream, address)) => { + if !address.ip().is_loopback() { + continue; + } + stream.set_nonblocking(true).map_err(failed)?; + let mut head = Vec::new(); + loop { + if cancel.is_cancelled() || entry.cancel.is_cancelled() { + return Err(HostError::Cancelled); + } + if Instant::now() >= deadline { + return Ok(None); + } + let mut buf = [0; 1024]; + match stream.read(&mut buf) { + Ok(0) => break, + Ok(n) => { + head.extend_from_slice(&buf[..n]); + if head.windows(4).any(|w| w == b"\r\n\r\n") || head.len() > 8192 { + break; + } + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => { + std::thread::sleep(Duration::from_millis(5)) + } + Err(e) => return Err(failed(e)), + } + } + let line = std::str::from_utf8(&head).unwrap_or_default().lines().next().unwrap_or_default(); + let target = line.strip_prefix("GET ").and_then(|s| s.split_once(' ')).map(|(target, _)| target); + let query = target.and_then(|target| { + let (path, query) = target.split_once('?').unwrap_or((target, "")); + (path == entry.path && head.len() <= 8192).then(|| query.to_owned()) + }); + stream.set_nonblocking(false).map_err(failed)?; + stream.set_write_timeout(Some(Duration::from_millis(100))).map_err(failed)?; + respond(&mut stream, query.is_some()); + if query.is_some() { + return Ok(query); + } + } + Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {} + Err(e) => return Err(failed(e)), + } + if Instant::now() >= deadline { + return Ok(None); + } + std::thread::sleep(Duration::from_millis(5)); + })(); + self.close(plugin, id); + result + } + fn close(&self, plugin: &str, id: u64) { + let entry = self.entries.lock().remove(&(plugin.into(), id)); + if let Some(entry) = entry { + entry.cancel.cancel(); + entry.listener.lock().take(); + } + } + fn clear(&self, plugin: &str) { + self.remove_where(|p, _| p == plugin || p.starts_with("remote:") && p.ends_with(&format!(":{plugin}"))); + } + fn forget_window(&self, window: &str) { + self.remove_where(|_, entry| entry.window == window); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn one_shot_raw_query_limits_timeout_and_cleanup() { + let service = Arc::new(Loopbacks::default()); + let (id, uri) = service.begin("a", "main", "oauth/callback").unwrap(); + assert!(uri.starts_with("http://127.0.0.1:")); + let (other, _) = service.begin("a", "main", "").unwrap(); + assert!(service.begin("a", "main", "third").is_err()); + assert_eq!(service.wait("a", other, Duration::ZERO, &CancellationToken::new()).unwrap(), None); + let host = uri.strip_prefix("http://").unwrap().split('/').next().unwrap().to_owned(); + let worker = std::thread::spawn(move || { + let mut stream = TcpStream::connect(host).unwrap(); + stream.write_all(b"GET /oauth/callback?code=a%2Bb&state=x HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap(); + let mut answer = String::new(); + stream.read_to_string(&mut answer).unwrap(); + assert!(answer.contains("You can close this tab")); + }); + assert_eq!( + service.wait("a", id, Duration::from_secs(2), &CancellationToken::new()).unwrap(), + Some("code=a%2Bb&state=x".into()) + ); + worker.join().unwrap(); + assert!(service.wait("a", id, Duration::ZERO, &CancellationToken::new()).is_err()); + let (id, _) = service.begin("a", "main", "callback").unwrap(); + service.forget_window("main"); + assert!(service.wait("a", id, Duration::ZERO, &CancellationToken::new()).is_err()); + } +} diff --git a/crates/ide-host/src/plugins/index_ops.rs b/crates/ide-host/src/plugins/index_ops.rs index ef11aac62..60f09fd6a 100644 --- a/crates/ide-host/src/plugins/index_ops.rs +++ b/crates/ide-host/src/plugins/index_ops.rs @@ -113,6 +113,7 @@ pub async fn plugin_navigation_index( &project.root, crate::plugins::navigation::Snapshot { path: &path, version, text: &text, symbols: &symbols, scope }, Invocation { + command_chain: Vec::new(), client: Some(client.clone()), workspace_root: Some(project.root.clone()), editor: None, diff --git a/crates/ide-host/src/plugins/ipc.rs b/crates/ide-host/src/plugins/ipc.rs new file mode 100644 index 000000000..50612562d --- /dev/null +++ b/crates/ide-host/src/plugins/ipc.rs @@ -0,0 +1,174 @@ +//! Plugin-owned local byte streams, closed on resource drop and plugin shutdown. +use super::api::net_runtime; +use ide_core::CancellationToken; +use ide_plugin::HostError; +use parking_lot::Mutex; +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; + +trait Stream: AsyncRead + AsyncWrite + Unpin + Send {} +impl Stream for T {} +struct Connection { + stream: tokio::sync::Mutex>, + closed: CancellationToken, +} +impl Drop for Connection { + fn drop(&mut self) { + self.closed.cancel(); + } +} + +#[derive(Default)] +pub(super) struct Connections { + next: AtomicU64, + entries: Mutex>>, +} +fn failed(e: impl std::fmt::Display) -> HostError { + HostError::Failed(e.to_string()) +} +impl Connections { + pub fn connect( + &self, + plugin: &str, + name: &str, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result { + let check = |entries: &HashMap<(String, u64), Arc>| { + if entries.keys().filter(|(p, _)| p == plugin).count() >= 8 { + Err(HostError::Invalid("at most eight IPC connections per plugin".into())) + } else { + Ok(()) + } + }; + check(&self.entries.lock())?; + let stream: Box = net_runtime().block_on(async { + let connect = async { + #[cfg(unix)] + { Ok::, HostError>(Box::new(tokio::net::UnixStream::connect(name).await.map_err(failed)?)) } + #[cfg(windows)] + { Ok::, HostError>(Box::new(tokio::net::windows::named_pipe::ClientOptions::new().open(name).map_err(failed)?)) } + #[cfg(not(any(unix, windows)))] + { let _ = name; Err(HostError::Failed("local IPC unavailable".into())) } + }; + tokio::select! { + r = tokio::time::timeout(timeout, connect) => r.map_err(|_| HostError::Failed("IPC connection timed out".into()))?, + () = cancel.cancelled() => Err(HostError::Cancelled), + } + })?; + let mut entries = self.entries.lock(); + check(&entries)?; + if cancel.is_cancelled() { + return Err(HostError::Cancelled); + } + let id = self.next.fetch_add(1, Ordering::Relaxed); + entries.insert( + (plugin.into(), id), + Arc::new(Connection { stream: tokio::sync::Mutex::new(stream), closed: CancellationToken::new() }), + ); + Ok(id) + } + fn get(&self, plugin: &str, id: u64) -> Result, HostError> { + self.entries + .lock() + .get(&(plugin.into(), id)) + .cloned() + .ok_or_else(|| HostError::NotFound("IPC connection".into())) + } + pub fn write( + &self, + plugin: &str, + id: u64, + bytes: Vec, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result<(), HostError> { + let entry = self.get(plugin, id)?; + net_runtime().block_on(async { + tokio::select! { + r = tokio::time::timeout(timeout, async { entry.stream.lock().await.write_all(&bytes).await.map_err(failed) }) => r.map_err(|_| HostError::Failed("IPC write timed out".into()))?, + () = cancel.cancelled() => Err(HostError::Cancelled), + () = entry.closed.cancelled() => Err(HostError::Cancelled), + } + }) + } + pub fn read( + &self, + plugin: &str, + id: u64, + max: usize, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + let entry = self.get(plugin, id)?; + net_runtime().block_on(async { + let read = async { + let mut bytes = vec![0; max.min(1 << 20)]; + let count = entry.stream.lock().await.read(&mut bytes).await.map_err(failed)?; + bytes.truncate(count); + Ok(bytes) + }; + tokio::select! { + biased; + () = cancel.cancelled() => Err(HostError::Cancelled), + () = entry.closed.cancelled() => Err(HostError::Cancelled), + r = read => r, + () = tokio::time::sleep(timeout) => Ok(Vec::new()), + } + }) + } + pub fn close(&self, plugin: &str, id: u64) { + if let Some(entry) = self.entries.lock().remove(&(plugin.into(), id)) { + entry.closed.cancel(); + } + } + pub fn clear(&self, plugin: &str) { + self.entries.lock().retain(|(p, _), entry| { + if p != plugin { + return true; + } + entry.closed.cancel(); + false + }); + } +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + #[test] + fn echo_limit_and_shutdown() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("echo.sock"); + let listener = UnixListener::bind(&path).unwrap(); + let worker = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut bytes = [0; 4]; + stream.read_exact(&mut bytes).unwrap(); + stream.write_all(&bytes).unwrap(); + // Accept the remaining seven connections before shutdown. + for _ in 1..8 { + listener.accept().unwrap(); + } + }); + let pool = Connections::default(); + let token = CancellationToken::new(); + let timeout = Duration::from_secs(2); + let id = pool.connect("a", path.to_str().unwrap(), &token, timeout).unwrap(); + pool.write("a", id, b"echo".to_vec(), &token, timeout).unwrap(); + assert_eq!(pool.read("a", id, 4, timeout, &token).unwrap(), b"echo"); + for _ in 1..8 { + pool.connect("a", path.to_str().unwrap(), &token, timeout).unwrap(); + } + assert!(matches!(pool.connect("a", path.to_str().unwrap(), &token, timeout), Err(HostError::Invalid(_)))); + assert!(pool.read("b", id, 4, timeout, &token).is_err()); + pool.clear("a"); + assert!(pool.read("a", id, 4, timeout, &token).is_err()); + worker.join().unwrap(); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index be00ee3c1..f8040e2af 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -16,6 +16,7 @@ //! projects) and folders linked with `openidea-plugin link` (`links.json`). mod api; +mod auth; pub mod commit; pub(crate) mod diagnostics; pub mod endpoints; @@ -30,6 +31,7 @@ pub mod index_ops; mod inlay_hints; mod install; pub mod intellij; +mod ipc; mod market; pub mod navigation; mod points; @@ -1080,7 +1082,9 @@ impl PluginHost { ledger.set(&subject, &cap, granted); if granted && let Capability::Process(program) = &cap - && let Some(bin) = self.resolve_binary(program) + && let Some(bin) = ledger + .program_choice(&subject, &cap) + .map_or_else(|| self.resolve_binary(program), |path| ledger::approve_program(path).ok()) { ledger.set_binary(&subject, &cap, bin); } @@ -1097,14 +1101,74 @@ impl PluginHost { /// The program a `process:` grant allows, checked against the file /// approved for it. Errors ask the user to confirm again. pub fn program_for(&self, id: &str, program: &str) -> IdeResult { + self.program_for_project(id, program, None) + } + + /// Resolves the approved executable for the invoking project, verifying its pinned content. + pub fn program_for_project(&self, id: &str, program: &str, root: Option<&Path>) -> IdeResult { let plugin = self.get(id)?; - let cap = Capability::Process(program.to_owned()); self.ledger .lock() - .check_binary(&plugin.subject(), &cap) + .check_binary_in_project(&plugin.subject(), &Capability::Process(program.into()), root) .map_err(|e| IdeError::new(ide_core::error::ErrorKind::PermissionDenied, e)) } + /// Records a user-approved executable choice; removing it revalidates the fallback or revokes the grant. + pub fn choose_program( + &self, + id: &str, + capability: &str, + root: Option<&Path>, + path: Option<&Path>, + ) -> IdeResult { + let _guard = self.lifecycle.lock(); + let plugin = self.get(id)?; + self.check_not_uninstalling(&plugin)?; + let cap: Capability = capability.parse().map_err(IdeError::invalid)?; + let Capability::Process(program) = &cap else { + return Err(IdeError::invalid("expected a process capability")); + }; + if !plugin.manifest().declares(&cap) && !plugin.meta.lock().declared_extra.contains(&cap) { + return Err(IdeError::invalid("undeclared process capability")); + } + let binary = if let Some(path) = path { + Some(ledger::approve_program(path).map_err(IdeError::invalid)?) + } else if root.is_none() { + self.resolve_binary(program) + } else { + None + }; + { + let mut ledger = self.ledger.lock(); + let subject = plugin.subject(); + if ledger.get(&subject).is_none() { + return Err(IdeError::invalid("confirm this plugin's permissions first")); + } + if let Some(root) = root { + ledger.set_project_binary(&subject, &cap, root, binary); + if path.is_some() { + ledger.set(&subject, &cap, true); + } else if ledger.check_binary(&subject, &cap).is_err() { + ledger.set(&subject, &cap, false); + } + } else if let Some(binary) = binary { + ledger.set_program_choice(&subject, &cap, path); + ledger.set(&subject, &cap, true); + ledger.set_binary(&subject, &cap, binary); + } else { + ledger.set_program_choice(&subject, &cap, None); + ledger.set(&subject, &cap, false); + } + self.save_ledger(&ledger); + } + self.stop(&plugin); + if !self.state.lock().disabled.contains(id) { + self.start(&plugin); + } + self.changed(); + self.info_of(id) + } + fn check_uninstall_pending(&self, id: &str) -> IdeResult<()> { if install::uninstall_pending(&self.plugins_dir, id)? { return Err(IdeError::unavailable(std::io::Error::from(std::io::ErrorKind::ResourceBusy).to_string())); @@ -1457,7 +1521,11 @@ impl PluginHost { /// Plugins' `runDetectors`, for [`ide_run::set_external_detection`]. pub fn run_detection(&self) -> Arc { - Arc::new(run_detectors::PluginRunDetection { store: self.run_detectors.clone(), pins: self.pins.clone() }) + Arc::new(run_detectors::PluginRunDetection { + store: self.run_detectors.clone(), + pins: self.pins.clone(), + project_pins: self.shared.project_pins.clone(), + }) } /// The syntax of plugin languages, for [`ide_language::set_external_syntax`]. @@ -1513,6 +1581,10 @@ impl PluginHost { } /// Plugin context keys in effect for window `client`: global keys overlaid with its own. + pub fn status_snapshot(&self, client: &str) -> Vec { + self.shared.status_snapshot(client) + } + pub fn context_keys(&self, client: Option<&str>) -> Vec { self.shared.context_keys(client) } @@ -1543,6 +1615,10 @@ impl PluginHost { /// A window answered a plugin's `CommitRequested`; false when the call no /// longer waits. + pub fn answer_command(&self, client: &str, request: &str, answer: CommandAnswer) -> bool { + request.parse().is_ok_and(|id| self.shared.answer_command(client, id, answer)) + } + pub fn answer_commit(&self, request_id: &str, answer: CommitAnswer) -> bool { request_id.parse().is_ok_and(|id| self.shared.answer_commit(id, answer)) } @@ -1632,6 +1708,17 @@ impl PluginHost { /// Queues workbench events from window `client` for the plugins that want /// them; [`flush_events`](Self::flush_events) delivers them in batches. + pub fn post_window_events(&self, client: &str, events: Vec, editor: Option) { + let mut editors = self.shared.event_editors.write(); + if let Some(editor) = editor { + editors.insert(client.into(), editor.context()); + } else { + editors.remove(client); + } + drop(editors); + self.post_events(Some(client), events); + } + pub fn post_events(&self, client: Option<&str>, events: Vec) { self.post_events_from(client, events, None); } @@ -1661,7 +1748,13 @@ impl PluginHost { .as_ref() .is_none_or(|root| client.and_then(|c| self.shared.project_of(c)).as_ref() == Some(root)) }) - .cloned() + .filter_map(|e| match e { + WorkbenchEvent::SettingsChanged(_) => { + let keys = self.shared.changed_settings(&p.pkg, client); + (!keys.is_empty()).then_some(WorkbenchEvent::SettingsChanged(keys)) + } + _ => Some(e.clone()), + }) .collect(); let wanted = Self::filter_path_events(&self.shared, &p, client, &wanted, &subs); if wanted.is_empty() { @@ -1809,9 +1902,10 @@ impl PluginHost { let invocation = Invocation { workspace_root: client.as_deref().and_then(|c| self.shared.project_of(c)), client: client.clone(), - editor: None, + editor: client.as_deref().and_then(|c| self.shared.event_editors.read().get(c).cloned()), selected_paths: Vec::new(), global_settings: false, + command_chain: Vec::new(), }; let kinds: BTreeSet = queue.events.iter().map(WorkbenchEvent::kind).collect(); let filesystem = kinds.contains(&EventKind::FilesChanged); @@ -2599,8 +2693,21 @@ impl PluginHost { /// pick up a change on their next lookup. fn refresh_pins(&self, ledger: &Ledger) { let mut pins = HashMap::new(); + let mut project_pins = HashMap::new(); for plugin in self.plugins.read().values() { let subject = plugin.subject(); + if let Some(grant) = ledger.get(&subject) { + for (root, binaries) in &grant.project_binaries { + for (cap, bin) in binaries { + if grant.granted.contains(cap) { + project_pins.insert( + (plugin.id().to_owned(), cap.clone(), root.clone()), + ProgramPin { path: bin.path.clone(), hash: bin.hash.clone() }, + ); + } + } + } + } let declared = plugin.manifest().capabilities.all().cloned().chain(plugin.meta.lock().declared_extra.clone()); for cap in declared.filter(|c| matches!(c, Capability::Process(_))) { @@ -2612,6 +2719,7 @@ impl PluginHost { } } } + *self.shared.project_pins.write() = project_pins; let mut current = self.pins.write(); if *current != pins { *current = pins; @@ -2665,12 +2773,26 @@ impl PluginHost { fn record_consent(&self, request: &Request<'_>, consent: &Consent) { let accepted: Vec = request.optional.iter().filter(|c| consent.accepts(c)).cloned().collect(); + let choices: BTreeMap<_, _> = { + let ledger = self.ledger.lock(); + request + .required + .iter() + .chain(&accepted) + .filter_map(|cap| { + ledger.program_choice(&request.subject, cap).map(|p| (cap.to_string(), p.to_path_buf())) + }) + .collect() + }; let binaries: BTreeMap = request .required .iter() .chain(&accepted) .filter_map(|c| match c { - Capability::Process(program) => self.resolve_binary(program).map(|b| (c.to_string(), b)), + Capability::Process(program) => choices + .get(&c.to_string()) + .map_or_else(|| self.resolve_binary(program), |path| ledger::approve_program(path).ok()) + .map(|b| (c.to_string(), b)), _ => None, }) .collect(); diff --git a/crates/ide-host/src/plugins/remote_host.rs b/crates/ide-host/src/plugins/remote_host.rs index 74ee904dd..b1818edb7 100644 --- a/crates/ide-host/src/plugins/remote_host.rs +++ b/crates/ide-host/src/plugins/remote_host.rs @@ -22,9 +22,7 @@ //! keychain and are asked for with a `plugin_secret` request //! ([`SecretRequest`]) when a request header needs one (rule 4). -use super::{ - Consent, HostWorkspace, PluginEditor, PluginEvent, PluginHost, PluginSource, PluginStatusItem, SecretStore, -}; +use super::{Consent, HostWorkspace, PluginEditor, PluginEvent, PluginHost, PluginSource, SecretStore}; use crate::rpc::Dispatcher; use base64::Engine as _; use ide_core::{IdeError, IdeResult}; @@ -45,6 +43,32 @@ pub const SYNC_PACKAGES: &str = "plugin_sync_packages"; pub const EVENT_NOTIFICATION: &str = "plugin"; /// Server → client request ([`SecretRequest`] → `Option`). pub const SECRET_REQUEST: &str = "plugin_secret"; +/// Mutations of declared secrets, kept on the desktop. +pub const SECRET_WRITE: &str = "plugin_secret_write"; +/// OAuth listeners bound on the desktop, never the project server. +pub const AUTH_REQUEST: &str = "plugin_auth"; + +#[derive(Clone, Serialize, Deserialize)] +pub struct SecretWrite { + pub plugin: String, + pub name: String, + pub value: Option, +} + +/// A remote plugin's operation on a desktop OAuth listener. +#[derive(Clone, Serialize, Deserialize)] +pub struct AuthRequest { + pub plugin: String, + pub operation: AuthOperation, +} +#[derive(Clone, Serialize, Deserialize)] +pub enum AuthOperation { + Begin { path: String }, + Wait { id: u64, timeout_ms: u32 }, + Close { id: u64 }, + Clear, +} + /// Under the server's data directory. pub const PLUGINS_DIR: &str = "remote-plugins"; const INCOMING_DIR: &str = "remote-plugins.incoming"; @@ -109,6 +133,10 @@ pub fn forwarded(event: &PluginEvent) -> bool { event, PluginEvent::Notification { .. } | PluginEvent::StatusItemChanged { .. } + | PluginEvent::WindowStatusItemChanged { .. } + | PluginEvent::ExecuteCommand { .. } + | PluginEvent::OutputChanged { .. } + | PluginEvent::RevealOutput { .. } | PluginEvent::ContextChanged { .. } | PluginEvent::TaskStarted { .. } | PluginEvent::TaskProgress { .. } @@ -218,8 +246,19 @@ impl SecretStore for ClientSecrets { } } - fn set(&self, _: &str, _: &str, _: Option<&str>) -> Result<(), String> { - Err("secrets are stored on the desktop".into()) + fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> { + let peer = self.peer.get().ok_or("desktop disconnected")?.clone(); + let request = SecretWrite { plugin: plugin.into(), name: name.into(), value: value.map(str::to_owned) }; + let ask = async { + tokio::time::timeout(SECRET_TIMEOUT, peer.request::<_, Result<(), String>>(SECRET_WRITE, request, None)) + .await + }; + let answer = if tokio::runtime::Handle::try_current().is_ok() { + tokio::task::block_in_place(|| self.runtime.block_on(ask)) + } else { + self.runtime.block_on(ask) + }; + answer.map_err(|_| "desktop timed out".to_owned())?.map_err(|e| e.to_string())? } } @@ -237,7 +276,8 @@ impl RemotePlugins { }; let host = Arc::new(PluginHost::new(data_dir.join(PLUGINS_DIR), Arc::new(sink), Limits::default())?); host.set_workspace(Some(Arc::new(HostWorkspace(Arc::downgrade(projects))))); - host.set_secret_store(Arc::new(ClientSecrets { peer, runtime: projects.runtime.clone() })); + host.set_secret_store(Arc::new(ClientSecrets { peer: peer.clone(), runtime: projects.runtime.clone() })); + *host.shared.loopbacks.write() = Arc::new(ClientLoopbacks { peer, runtime: projects.runtime.clone() }); let trust = Arc::downgrade(projects); host.set_project_policy(Arc::new(move |root| { trust.upgrade().is_some_and(|h| h.trust.trusted(root).unwrap_or(false)) @@ -380,6 +420,7 @@ impl RemotePlugins { let paths: Option> = c.arg("paths")?; let settings_scope: Option = c.arg("settingsScope")?; let invocation = Invocation { + command_chain: c.arg::>>("commandChain")?.unwrap_or_default(), client: Some(c.window.clone()), workspace_root: c.host.project(&c.window).ok().map(|p| p.root.clone()), editor: editor.map(PluginEditor::context), @@ -401,7 +442,7 @@ impl RemotePlugins { d.add("plugin_post_events", move |c| { let h = h.clone(); async move { - alive(&h)?.post_events(Some(&c.window), c.arg("events")?); + alive(&h)?.post_window_events(&c.window, c.arg("events")?, c.arg("editor")?); Ok(()) } }); @@ -411,15 +452,9 @@ impl RemotePlugins { async move { Ok(alive(&h)?.event_kinds().into_iter().collect::>()) } }); let h = host.clone(); - d.add("plugin_status_items", move |_| { + d.add("plugin_status_items", move |c| { let h = h.clone(); - async move { - Ok(alive(&h)? - .status_items() - .into_iter() - .map(|(plugin_id, id, item)| PluginStatusItem { plugin_id, id, item }) - .collect::>()) - } + async move { Ok(alive(&h)?.status_snapshot(&c.window)) } }); let h = host.clone(); d.add("plugin_context_keys", move |c| { @@ -437,6 +472,43 @@ impl RemotePlugins { async move { Ok(alive(&h)?.answer_prompt(&c.arg::("promptId")?, c.arg("answer")?)) } }); let h = host.clone(); + d.add("plugin_choose_program", move |c| { + let h = h.clone(); + async move { + let host = alive(&h)?; + let id: String = c.arg("pluginId")?; + let cap: String = c.arg("capability")?; + let scope: SettingsScope = c.arg("scope")?; + let path: Option = c.arg("path")?; + let root = match scope { + SettingsScope::Global => None, + SettingsScope::Project => Some(c.host.project(&c.window)?.root.clone()), + }; + blocking(move || host.choose_program(&id, &cap, root.as_deref(), path.as_deref())).await + } + }); + let h = host.clone(); + d.add("plugin_program", move |c| { + let h = h.clone(); + async move { + let host = alive(&h)?; + let id: String = c.arg("pluginId")?; + let program: String = c.arg("program")?; + let scope: SettingsScope = c.arg("scope")?; + let root = match scope { + SettingsScope::Global => None, + SettingsScope::Project => Some(c.host.project(&c.window)?.root.clone()), + }; + blocking(move || host.program_for_project(&id, &program, root.as_deref()).map(ide_core::IpcPath::from)) + .await + } + }); + let h = host.clone(); + d.add("plugin_answer_command", move |c| { + let h = h.clone(); + async move { Ok(alive(&h)?.answer_command(&c.window, &c.arg::("requestId")?, c.arg("answer")?)) } + }); + let h = host.clone(); d.add("plugin_answer_commit", move |c| { let h = h.clone(); async move { Ok(alive(&h)?.answer_commit(&c.arg::("requestId")?, c.arg("answer")?)) } @@ -621,6 +693,123 @@ fn safe_relative(path: &str) -> IdeResult { Ok(p.to_path_buf()) } +struct ClientLoopbacks { + peer: Arc>, + runtime: tokio::runtime::Handle, +} +impl ClientLoopbacks { + fn request( + &self, + plugin: &str, + operation: AuthOperation, + cancel: Option, + ) -> Result { + let peer = self.peer.get().ok_or(ide_plugin::HostError::Cancelled)?.clone(); + let timeout = match &operation { + AuthOperation::Wait { timeout_ms, .. } => Duration::from_millis(u64::from(*timeout_ms)) + SECRET_TIMEOUT, + _ => SECRET_TIMEOUT, + }; + let request = AuthRequest { plugin: plugin.into(), operation }; + let ask = async { + tokio::time::timeout( + timeout, + peer.request::<_, Result>(AUTH_REQUEST, request, cancel), + ) + .await + .map_err(|_| ide_plugin::HostError::Failed("desktop OAuth request timed out".into()))? + .map_err(|e| ide_plugin::HostError::Failed(e.to_string()))? + }; + if tokio::runtime::Handle::try_current().is_ok() { + tokio::task::block_in_place(|| self.runtime.block_on(ask)) + } else { + self.runtime.block_on(ask) + } + } +} +impl super::auth::Service for ClientLoopbacks { + fn begin(&self, plugin: &str, _window: &str, path: &str) -> Result<(u64, String), ide_plugin::HostError> { + serde_json::from_value(self.request(plugin, AuthOperation::Begin { path: path.into() }, None)?) + .map_err(|e| ide_plugin::HostError::Failed(e.to_string())) + } + fn wait( + &self, + plugin: &str, + id: u64, + timeout: Duration, + cancel: &ide_core::CancellationToken, + ) -> Result, ide_plugin::HostError> { + let result = self.request( + plugin, + AuthOperation::Wait { id, timeout_ms: timeout.as_millis().min(u128::from(u32::MAX)) as u32 }, + Some(cancel.clone()), + ); + if cancel.is_cancelled() { + self.close(plugin, id); + return Err(ide_plugin::HostError::Cancelled); + } + serde_json::from_value(result?).map_err(|e| ide_plugin::HostError::Failed(e.to_string())) + } + fn close(&self, plugin: &str, id: u64) { + let _ = self.request(plugin, AuthOperation::Close { id }, None); + } + fn clear(&self, plugin: &str) { + let _ = self.request(plugin, AuthOperation::Clear, None); + } + fn forget_window(&self, _: &str) {} +} + +impl PluginHost { + /// A remote instance may mutate only declared secrets with a current grant. + pub fn remote_secret_write(&self, request: SecretWrite) -> Result<(), String> { + let plugin = self.get(&request.plugin).map_err(|e| e.message)?; + if !plugin.meta.lock().granted.iter().any(|g| g.covers(&ide_extension::Capability::Secrets)) { + return Err("secrets capability not granted".into()); + } + if !self.ui.items(super::providers::SECRETS_POINT, Some(plugin.id())).iter().any(|s| s.key == request.name) { + return Err("undeclared secret".into()); + } + if request.value.as_ref().is_some_and(|v| v.len() > 64 << 10) { + return Err("secret value too long".into()); + } + self.shared.secrets.read().set(plugin.id(), &request.name, request.value.as_deref()) + } + /// Serves a connected remote instance using this connection's actual window. + pub fn remote_auth(&self, window: &str, request: AuthRequest) -> Result { + if matches!(&request.operation, AuthOperation::Begin { .. } | AuthOperation::Wait { .. }) { + self.get(&request.plugin).map_err(|e| ide_plugin::HostError::NotFound(e.message))?; + } + let owner = format!("remote:{window}:{}", request.plugin); + let service = self.shared.loopbacks.read().clone(); + let result = match request.operation { + AuthOperation::Begin { path } => { + if self.shared.client_closed(window) { + return Err(ide_plugin::HostError::Cancelled); + } + serde_json::to_value(service.begin(&owner, window, &path)?) + } + AuthOperation::Wait { id, timeout_ms } => serde_json::to_value(service.wait( + &owner, + id, + Duration::from_millis(u64::from(timeout_ms)), + &ide_core::CancellationToken::new(), + )?), + AuthOperation::Close { id } => { + service.close(&owner, id); + Ok(serde_json::Value::Null) + } + AuthOperation::Clear => { + service.clear(&owner); + Ok(serde_json::Value::Null) + } + }; + result.map_err(|e| ide_plugin::HostError::Failed(e.to_string())) + } + /// A remote transport closed; abandon its browser listeners. + pub fn forget_remote_loopbacks(&self, window: &str) { + self.shared.loopbacks.read().forget_window(window); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-host/src/plugins/run_detectors.rs b/crates/ide-host/src/plugins/run_detectors.rs index c48b001e6..46c9cfabb 100644 --- a/crates/ide-host/src/plugins/run_detectors.rs +++ b/crates/ide-host/src/plugins/run_detectors.rs @@ -115,6 +115,7 @@ type Pins = Arc>>; pub struct PluginRunDetection { pub(crate) store: Arc, pub(crate) pins: Pins, + pub(crate) project_pins: super::api::ProjectPins, } fn config_id(plugin: &str, detector: &str) -> String { @@ -122,9 +123,10 @@ fn config_id(plugin: &str, detector: &str) -> String { } impl PluginRunDetection { - fn pin(&self, plugin: &str, d: &Detector) -> Option { + fn pin(&self, plugin: &str, d: &Detector, root: Option<&Path>) -> Option { let cap = Capability::Process(d.command.trim().to_owned()); - self.pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned() + root.and_then(|root| self.project_pins.read().get(&(plugin.into(), cap.to_string(), root.into())).cloned()) + .or_else(|| self.pins.read().get(&(plugin.to_owned(), cap.to_string())).cloned()) } } @@ -133,14 +135,16 @@ impl ExternalDetection for PluginRunDetection { let items = self.store.items.read().clone(); items .into_iter() - .filter(|(_, plugin, d)| self.pin(plugin, d).is_some() && d.files.iter().any(|f| root.join(f).exists())) + .filter(|(_, plugin, d)| { + self.pin(plugin, d, Some(root)).is_some() && d.files.iter().any(|f| root.join(f).exists()) + }) .map(|(_, plugin, d)| RunConfig { id: config_id(&plugin, &d.id), name: d.name.clone(), kind: "plugin".into(), command: d.command.trim().to_owned(), args: d.args.clone(), - cwd: None, + cwd: Some(root.to_path_buf().into()), env: Default::default(), detected: true, is_test: d.test, @@ -159,7 +163,7 @@ impl ExternalDetection for PluginRunDetection { .map(|(_, p, d)| (p.clone(), d.clone())) .ok_or_else(|| "the plugin that detected this configuration is no longer enabled".to_owned())?; drop(items); - let pin = self.pin(&plugin, &d).ok_or_else(|| { + let pin = self.pin(&plugin, &d, config.cwd.as_ref().map(|p| p.as_ref())).ok_or_else(|| { format!("allow process:{} for plugin {plugin} in Settings › Plugins to run this configuration", d.command) })?; pin.verify().map(Path::to_path_buf) diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index df58404f3..cf28a960a 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -166,6 +166,15 @@ pub struct PluginUpdate { pub enum PluginEvent { /// Plugins, their status or their contributions changed: re-fetch `plugin_list`. CommandsChanged, + /// A bounded output channel snapshot, or withdrawal when the plugin stops. + #[serde(rename_all = "camelCase")] + OutputChanged { plugin_id: String, channel: String, text: Option }, + /// Reveal a read-only Output tab in the receiving window. + #[serde(rename_all = "camelCase")] + RevealOutput { plugin_id: String, channel: String, text: String }, + /// Execute an action through the receiving window and answer over IPC. + #[serde(rename_all = "camelCase")] + ExecuteCommand { request_id: String, id: String, arg: Option, chain: Vec }, /// Cached document associations were disposed (reload, disable or failure). DocumentIndexesChanged, /// The routes `plugin_id` reports for the project `root` may have changed: @@ -187,6 +196,9 @@ pub enum PluginEvent { /// A plugin's status bar item was set (`item`) or removed. #[serde(rename_all = "camelCase")] StatusItemChanged { plugin_id: String, id: String, item: Option }, + /// An override in the receiving window; removal exposes the global item. + #[serde(rename_all = "camelCase")] + WindowStatusItemChanged { plugin_id: String, id: String, item: Option }, /// A plugin's context key was set (`value`: JSON text) or removed, in the /// emitted window (every window when the client is `None`). #[serde(rename_all = "camelCase")] @@ -340,6 +352,8 @@ pub struct PackageFile { #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase")] pub struct PluginStatusItem { + /// Whether this item overrides the global item in the requesting window. + pub window: bool, pub plugin_id: String, pub id: String, pub item: StatusItem, @@ -388,3 +402,12 @@ pub struct PluginCommitCheckResult { /// The check could not run (the plugin failed, timed out or lacks `vcs.read`). pub error: Option, } + +/// The invoking window's response to a command request. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(tag = "kind", content = "value", rename_all = "camelCase")] +pub enum CommandAnswer { + Value(Option), + NotFound, + Failed(String), +} diff --git a/crates/ide-host/src/plugins/web.rs b/crates/ide-host/src/plugins/web.rs index d3d9514d8..b08b8d5c8 100644 --- a/crates/ide-host/src/plugins/web.rs +++ b/crates/ide-host/src/plugins/web.rs @@ -309,7 +309,7 @@ impl PluginHost { if !workspace.trusted(&cwd) { return Err(IdeError::new(ide_core::error::ErrorKind::PermissionDenied, "project is not trusted")); } - let program = self.program_for(plugin_id, &command.program)?; + let program = self.program_for_project(plugin_id, &command.program, Some(&cwd))?; Ok(ide_terminal::TerminalOptions { cwd: cwd.into(), shell: Some(program.to_string_lossy().into_owned()), diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index f6aa475e8..d052e0804 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -396,6 +396,8 @@ pub fn projectless_command_allowed(cmd: &str) -> bool { | "plugin_set_enabled" | "plugin_grant" | "plugin_set_capability" + | "plugin_choose_program" + | "plugin_program" | "plugin_roll_back" | "plugin_reload" ) diff --git a/crates/ide-host/tests/distribution.rs b/crates/ide-host/tests/distribution.rs index 1af8a1068..1c38a8bb1 100644 --- a/crates/ide-host/tests/distribution.rs +++ b/crates/ide-host/tests/distribution.rs @@ -59,6 +59,7 @@ fn fixture() -> Fixture { fn inv() -> Invocation { Invocation { + command_chain: Vec::new(), client: Some("main".into()), workspace_root: None, editor: None, diff --git a/crates/ide-host/tests/plugin_indexing.rs b/crates/ide-host/tests/plugin_indexing.rs index 63dd97dad..b936494e8 100644 --- a/crates/ide-host/tests/plugin_indexing.rs +++ b/crates/ide-host/tests/plugin_indexing.rs @@ -194,6 +194,7 @@ fn two_windows_of_same_root_keep_unsaved_snapshots_isolated() { &f.root, Snapshot { path, version: Some(1), text, symbols: &symbols, scope: "" }, Invocation { + command_chain: Vec::new(), client: Some(client.into()), workspace_root: Some(f.root.clone()), editor: None, diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index 9702d3f99..b02ac264e 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -285,6 +285,7 @@ fn fixture(limits: Limits) -> Fixture { impl Fixture { fn inv(&self) -> Invocation { Invocation { + command_chain: Vec::new(), client: Some("main".into()), workspace_root: Some(self.project.clone()), editor: None, @@ -5642,3 +5643,241 @@ fn view_secondary_requires_api_1_3_and_a_boolean_tool_window_placement() { assert!(err.message.contains(message), "{api}, {location}, {value}: {err:?}"); } } + +#[test] +fn api14_denies_new_privileges_and_requires_an_invoking_window() { + let f = fixture(Limits::default()); + f.host.install_from_dir(&sample("api14"), &Consent::default()).unwrap(); + for (command, arg, capability) in [ + ("ipc", "/tmp/api14-no-grant", "ipc:"), + ("fetch", "http://example.com/", "net.http:"), + ("secret", "value", "secrets"), + ("delete-secret", "", "secrets"), + ] { + let error = f.run("api14", command, Some(arg)).unwrap_err(); + assert!(error.contains(capability) && error.contains("not granted"), "{error}"); + } + for command in ["window-status", "remove-window-status", "execute", "oauth", "output"] { + let error = f.host.run_command("api14", command, Some("value"), Invocation::default()).unwrap_err(); + assert_eq!(error.kind, ErrorKind::InvalidInput, "{command}: {error:?}"); + } + f.host.set_capability("api14", "secrets", true).unwrap(); + f.run("api14", "secret", Some(" raw value ")).unwrap(); + assert_eq!(f.host.declared_secret("api14", "token"), Some(" raw value ".into())); + assert!(f.run("api14", "undeclared-secret", Some("value")).unwrap_err().contains("undeclared")); + f.run("api14", "delete-secret", None).unwrap(); + assert_eq!(f.host.declared_secret("api14", "token"), None); +} + +#[test] +fn api14_window_status_overrides_fall_back_and_are_withdrawn() { + let f = fixture(Limits::default()); + f.install(&sample("api14")); + f.run("api14", "global-status", Some("global")).unwrap(); + f.run("api14", "window-status", Some("main")).unwrap(); + let snapshot = f.host.status_snapshot("main"); + assert!(snapshot.iter().any(|i| i.window && i.item.text == "main")); + assert!(!f.host.status_snapshot("other").iter().any(|i| i.window)); + f.run("api14", "global-status", Some("updated")).unwrap(); + f.run("api14", "remove-window-status", None).unwrap(); + assert_eq!(f.host.status_snapshot("main").len(), 1); + assert_eq!(f.host.status_snapshot("main")[0].item.text, "updated"); + f.run("api14", "window-status", Some("override")).unwrap(); + f.host.forget_client("main"); + assert!(!f.host.status_snapshot("main").iter().any(|i| i.window)); + f.host.reopen_client("main"); + f.run("api14", "window-status", Some("again")).unwrap(); + f.host.set_enabled("api14", false).unwrap(); + assert!(f.host.status_snapshot("main").is_empty()); + assert!(f.take_events().iter().any(|(window, event)| window.as_deref() == Some("main") + && matches!(event, PluginEvent::WindowStatusItemChanged { item: None, .. }))); +} + +#[test] +fn api14_command_requests_preserve_window_result_and_reject_cycles() { + let f = Arc::new(fixture(Limits::default())); + f.install(&sample("api14")); + assert!(f.run("api14", "execute", Some("plugin.api14.execute")).unwrap_err().contains("recursive")); + for answer in [CommandAnswer::Value(Some("result".into())), CommandAnswer::Value(None), CommandAnswer::NotFound] { + f.take_events(); + let runner = f.clone(); + let worker = std::thread::spawn(move || runner.run("api14", "execute", Some("test.action"))); + let deadline = Instant::now() + Duration::from_secs(5); + let request = loop { + if let Some((window, PluginEvent::ExecuteCommand { request_id, arg, chain, .. })) = + f.events.lock().iter().find(|(_, e)| matches!(e, PluginEvent::ExecuteCommand { .. })).cloned() + { + assert_eq!(window.as_deref(), Some("main")); + assert_eq!(arg.as_deref(), Some("argument")); + assert_eq!(chain, ["api14"]); + break request_id; + } + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + }; + assert!(!f.host.answer_command("other", &request, answer.clone())); + assert!(f.host.answer_command("main", &request, answer.clone())); + let result = worker.join().unwrap(); + match answer { + CommandAnswer::Value(value) => assert_eq!(result.unwrap(), value), + CommandAnswer::NotFound => assert!(result.unwrap_err().contains("test.action")), + _ => unreachable!(), + } + } +} + +#[test] +fn api14_settings_and_input_events_use_other_and_capture_the_editor() { + let f = fixture(Limits::default()); + f.install(&sample("api14")); + use ide_plugin::WorkbenchEvent as E; + f.host.post_events(Some("main"), vec![E::SettingsChanged(Vec::new())]); + f.workspace + .settings + .lock() + .insert("api14".into(), serde_json::from_value(serde_json::json!({"enabled": true})).unwrap()); + let path = to_ipc(&f.project.join("src/notes.txt")); + f.host.post_window_events( + "main", + vec![ + E::SettingsChanged(vec!["another-plugin-key".into()]), + E::FileClosed(path.clone()), + E::InputModeChanged(ide_plugin::InputMode { + path: path.clone(), + mode: "visual".into(), + sub: Some("linewise".into()), + }), + ], + Some(PluginEditor { + path: path.clone(), + language: "text".into(), + selections: vec![ide_core::Range::default()], + }), + ); + f.host.flush_events_at(Instant::now() + Duration::from_secs(2)); + assert!(f.host.wait_events(Duration::from_secs(5))); + let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap(); + let events = received.as_array().unwrap(); + assert_eq!(events.len(), 3, "{received}"); + assert_eq!(events[0]["kind"], "settings-changed"); + assert_eq!(events[0]["data"], "[\"enabled\"]"); + assert_eq!(events[2]["kind"], "input-mode-changed"); + assert_eq!(events[2]["editor"][0], path); + assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0])); +} + +#[cfg(unix)] +#[test] +fn api14_ipc_echo_checks_the_grant_in_the_wasm_binding() { + use std::io::{Read, Write}; + let f = fixture(Limits::default()); + let pkg = f._tmp.path().join("api14-package"); + copy_dir(&sample("api14"), &pkg); + let path = f._tmp.path().join("echo.sock"); + let manifest = pkg.join("plugin.toml"); + let text = std::fs::read_to_string(&manifest) + .unwrap() + .replace("ipc:$TMPDIR/api14-*", &format!("ipc:{}", f._tmp.path().join("*.sock").display())); + std::fs::write(manifest, text).unwrap(); + f.install(&pkg); + let listener = std::os::unix::net::UnixListener::bind(&path).unwrap(); + let worker = std::thread::spawn(move || { + let (mut stream, _) = listener.accept().unwrap(); + let mut bytes = [0; 4]; + stream.read_exact(&mut bytes).unwrap(); + stream.write_all(&bytes).unwrap(); + }); + assert_eq!(f.run("api14", "ipc", path.to_str()).unwrap().as_deref(), Some("echo")); + worker.join().unwrap(); + f.host.set_capability("api14", &format!("ipc:{}", f._tmp.path().join("*.sock").display()), false).unwrap(); + assert!(f.run("api14", "ipc", path.to_str()).unwrap_err().contains("not granted")); +} + +#[test] +fn api14_oauth_wait_excludes_the_call_budget_and_closes_after_redirect() { + use std::io::{Read, Write}; + let f = Arc::new(fixture(Limits { timeout: Duration::from_millis(200), ..Limits::default() })); + f.install(&sample("api14")); + let runner = f.clone(); + let worker = std::thread::spawn(move || runner.run("api14", "oauth", None)); + let deadline = Instant::now() + Duration::from_secs(5); + let uri = loop { + if let Some((_, PluginEvent::OutputChanged { text: Some(text), .. })) = f + .events + .lock() + .iter() + .find(|(_, e)| matches!(e, PluginEvent::OutputChanged { channel, .. } if channel == "oauth")) + .cloned() + { + break text; + } + assert!(Instant::now() < deadline); + std::thread::sleep(Duration::from_millis(5)); + }; + assert!(uri.starts_with("http://127.0.0.1:")); + std::thread::sleep(Duration::from_millis(300)); + let authority = uri.strip_prefix("http://").unwrap().split('/').next().unwrap(); + let mut stream = std::net::TcpStream::connect(authority).unwrap(); + stream.write_all(b"GET /oauth/callback?code=a%2Bb&state=test HTTP/1.1\r\nHost: localhost\r\n\r\n").unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + assert!(response.contains("You can close this tab")); + assert_eq!(worker.join().unwrap().unwrap().as_deref(), Some("code=a%2Bb&state=test")); + assert!(std::net::TcpStream::connect(authority).is_err()); + f.run("api14", "global-status", Some("still running")).unwrap(); +} + +#[cfg(unix)] +#[test] +fn api14_executable_choices_are_pinned_per_project_and_reset_revalidates() { + use std::os::unix::fs::PermissionsExt; + let f = fixture(Limits::default()); + let package = f._tmp.path().join("api14-process"); + copy_dir(&sample("api14"), &package); + let manifest = package.join("plugin.toml"); + let text = + std::fs::read_to_string(&manifest).unwrap().replace("optional = [", "optional = [\"process:api14-tool\", "); + std::fs::write(manifest, text).unwrap(); + f.install(&package); + let executable = |name: &str| { + let path = f._tmp.path().join(format!("{name}-bin")); + std::fs::write(&path, format!("#!/bin/sh\nprintf '{name}'\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.canonicalize().unwrap() + }; + let global = executable("global"); + let project = executable("project"); + f.host.choose_program("api14", "process:api14-tool", None, Some(&global)).unwrap(); + f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&project)).unwrap(); + assert_eq!(f.host.program_for("api14", "api14-tool").unwrap(), global); + assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).unwrap(), project); + for command in ["process-run", "process-run-command", "process-start"] { + assert_eq!(f.run("api14", command, None).unwrap().as_deref(), Some("project")); + let invocation = Invocation { client: Some("global".into()), ..Invocation::default() }; + assert_eq!(f.host.run_command("api14", command, None, invocation).unwrap().as_deref(), Some("global")); + } + f.run("api14", "terminal", None).unwrap(); + assert!( + f.take_events().iter().any( + |(_, e)| matches!(e, PluginEvent::OpenTerminal { program, .. } if program.as_ref() == project.as_path()) + ) + ); + f.run("api14", "log", None).unwrap(); + assert!( + f.take_events() + .iter() + .any(|(_, e)| matches!(e, PluginEvent::OpenLogTab { log, .. } if log.program == "api14-tool")) + ); + let unrelated = f._tmp.path().join("unrelated"); + assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&unrelated)).unwrap(), global); + std::fs::write(&project, "changed").unwrap(); + assert!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).is_err()); + f.host.choose_program("api14", "process:api14-tool", Some(&f.project), None).unwrap(); + assert_eq!(f.host.program_for_project("api14", "api14-tool", Some(&f.project)).unwrap(), global); + f.host.choose_program("api14", "process:api14-tool", Some(&f.project), Some(&project)).unwrap(); + std::fs::write(&global, "changed").unwrap(); + f.host.choose_program("api14", "process:api14-tool", Some(&f.project), None).unwrap(); + assert!( + !f.host.info_of("api14").unwrap().capabilities.iter().find(|c| c.id == "process:api14-tool").unwrap().granted + ); +} diff --git a/crates/ide-host/tests/remote_plugins.rs b/crates/ide-host/tests/remote_plugins.rs index 3416eef09..71784ca24 100644 --- a/crates/ide-host/tests/remote_plugins.rs +++ b/crates/ide-host/tests/remote_plugins.rs @@ -27,6 +27,7 @@ struct Client { events: Mutex>, plugin_events: Mutex>, secret_requests: Mutex>, + desktop: Option>, } impl Handler for Client { @@ -45,6 +46,19 @@ impl Handler for Client { self.secret_requests.lock().push(r); return Ok(serde_json::to_value(value).unwrap()); } + if let Some(desktop) = &self.desktop { + use ide_host::plugins::remote_host::{AUTH_REQUEST, SECRET_WRITE}; + if method == AUTH_REQUEST { + return Ok( + serde_json::to_value(desktop.remote_auth("main", serde_json::from_value(params).unwrap())).unwrap() + ); + } + if method == SECRET_WRITE { + return Ok( + serde_json::to_value(desktop.remote_secret_write(serde_json::from_value(params).unwrap())).unwrap() + ); + } + } Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, method.to_owned())) } } @@ -350,3 +364,90 @@ async fn remote_projects_get_plugin_views_and_custom_editors() { plugins.host().shutdown(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop() { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let tmp = tempfile::tempdir().unwrap(); + let desktop = Arc::new( + PluginHost::new(tmp.path().join("desktop/plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()) + .unwrap(), + ); + desktop.install_from_dir(&fixture("api14"), &Consent::all()).unwrap(); + let project = tmp.path().join("project"); + std::fs::create_dir(&project).unwrap(); + let project = project.canonicalize().unwrap(); + let base = tmp.path().join("server"); + let peer_slot = Arc::new(OnceLock::new()); + let sink_peer = peer_slot.clone(); + let host = Arc::new(Host::new(HostConfig { + config_dir: base.join("config"), + data_dir: base.join("data"), + local_data_dir: base.join("data"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(move |w| rpc::event_sink(sink_peer.clone(), Some(w.into()))), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + let plugins = RemotePlugins::start(&base.join("data"), &host, peer_slot.clone()).unwrap(); + let mut dispatcher = Dispatcher::standard(); + plugins.register(&mut dispatcher); + let (client_io, server_io) = tokio::io::duplex(1 << 20); + let (sr, sw) = tokio::io::split(server_io); + tokio::spawn(rpc::serve(host, dispatcher, peer_slot, sr, sw)); + let (cr, cw) = tokio::io::split(client_io); + let client = Arc::new(Client { desktop: Some(desktop.clone()), ..Client::default() }); + let peer = Peer::connect(cr, cw, client.clone()); + let _: Value = peer.request("initialize", json!({ "version": rpc::PROTOCOL_VERSION }), None).await.unwrap(); + invoke(&peer, "open_project", json!({ "path": project })).await.unwrap(); + invoke(&peer, "project_trust_set", json!({ "path": project, "trusted": true, "folder": false })).await.unwrap(); + sync(&peer, &desktop, &[]).await; + let report = sync(&peer, &desktop, &["api14"]).await; + assert!(report.failed.is_empty(), "{report:?}"); + let run = |command: &str, arg: Option<&str>| json!({ "pluginId": "api14", "commandId": command, "arg": arg, "editor": null }); + invoke(&peer, "plugin_run_command", run("secret", Some("remote-token"))).await.unwrap(); + assert_eq!(desktop.declared_secret("api14", "token").as_deref(), Some("remote-token")); + invoke(&peer, "plugin_run_command", run("delete-secret", None)).await.unwrap(); + assert_eq!(desktop.declared_secret("api14", "token"), None); + invoke(&peer, "plugin_run_command", run("window-status", Some("remote"))).await.unwrap(); + let status = invoke(&peer, "plugin_status_items", json!({})).await.unwrap(); + assert!(status.as_array().unwrap().iter().any(|s| s["window"] == true && s["item"]["text"] == "remote")); + let oauth_peer = peer.clone(); + let oauth = tokio::spawn(async move { + invoke( + &oauth_peer, + "plugin_run_command", + json!({ "pluginId": "api14", "commandId": "oauth", "arg": null, "editor": null }), + ) + .await + }); + until("remote OAuth URI", 5, || { + client + .plugin_events + .lock() + .iter() + .any(|m| matches!(&m.event, PluginEvent::OutputChanged { channel, .. } if channel == "oauth")) + }) + .await; + let uri = client + .plugin_events + .lock() + .iter() + .find_map(|m| match &m.event { + PluginEvent::OutputChanged { channel, text: Some(text), .. } if channel == "oauth" => Some(text.clone()), + _ => None, + }) + .unwrap(); + let authority = uri.strip_prefix("http://").unwrap().split('/').next().unwrap(); + let mut stream = tokio::net::TcpStream::connect(authority).await.unwrap(); + stream.write_all(b"GET /oauth/callback?code=desktop%2Bcode HTTP/1.1\r\nHost: localhost\r\n\r\n").await.unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).await.unwrap(); + assert!(response.contains("You can close this tab")); + assert_eq!(oauth.await.unwrap().unwrap(), json!("code=desktop%2Bcode")); + plugins.host().shutdown(); + desktop.shutdown(); + peer.kill(); +} diff --git a/crates/ide-http/src/client.rs b/crates/ide-http/src/client.rs index 05963a4c5..66fcc97d2 100644 --- a/crates/ide-http/src/client.rs +++ b/crates/ide-http/src/client.rs @@ -26,6 +26,11 @@ pub fn with_proxy(builder: reqwest::ClientBuilder, proxy: &ProxySettings) -> req /// A client for `proxy`. pub fn build(proxy: &ProxySettings) -> IdeResult { + build_with_redirect(proxy, reqwest::redirect::Policy::default()) +} + +/// A client with an explicit redirect policy, for callers enforcing network grants. +pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::Policy) -> IdeResult { use rustls_platform_verifier::BuilderVerifierExt; let fail = |e: String| IdeError::internal(format!("HTTP client: {e}")); let provider = Arc::new(rustls::crypto::ring::default_provider()); @@ -44,6 +49,7 @@ pub fn build(proxy: &ProxySettings) -> IdeResult { ]; let builder = reqwest::Client::builder() .tls_backend_preconfigured(tls) + .redirect(redirect) .resolve_to_addrs("localhost", &loopback) .connect_timeout(Duration::from_secs(30)) .user_agent(concat!("OpenIDEA-HttpClient/", env!("CARGO_PKG_VERSION"))); diff --git a/crates/ide-plugin/Cargo.toml b/crates/ide-plugin/Cargo.toml index da304e85e..25e22c72c 100644 --- a/crates/ide-plugin/Cargo.toml +++ b/crates/ide-plugin/Cargo.toml @@ -16,6 +16,7 @@ thiserror.workspace = true tracing.workspace = true parking_lot.workspace = true semver = "1" +url = "2" wasmtime = { version = "49.0.4", default-features = false, features = ["runtime", "cranelift", "component-model", "std", "parallel-compilation", "async"] } wasmtime-wasi = { version = "49.0.4", default-features = false, features = ["p2"] } diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 28fa745a3..ea4d1d235 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -50,7 +50,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view; use views_bindings::openidea::plugin::view_types as wit_vt; /// The API version of the world above, `major.minor` of [`host_api`]. -pub const API_VERSION: &str = "1.3"; +pub const API_VERSION: &str = "1.4"; const EPOCH_TICK: Duration = Duration::from_millis(10); pub(crate) const MAX_TEXT: usize = 1 << 20; pub(crate) const MAX_TITLE: usize = 256; @@ -101,8 +101,40 @@ pub trait HostApi: Send + Sync { let _ = (client, view); Ok(()) } + /// Executes a stable command in the invoking window and waits for its result. + fn execute_command( + &self, + invocation: &Invocation, + id: &str, + arg: Option, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result, HostError> { + let _ = (invocation, id, arg, cancel, timeout); + Err(HostError::NotFound("command".into())) + } + /// Appends text, or clears (`None`), in a plugin-owned output channel. + fn output_write(&self, channel: &str, text: Option<&str>) -> Result<(), HostError> { + let _ = (channel, text); + Err(HostError::Failed("output unavailable".into())) + } + /// Reveals an output channel in the invoking window. + fn output_reveal(&self, client: &str, channel: &str) -> Result<(), HostError> { + let _ = (client, channel); + Err(HostError::Failed("output unavailable".into())) + } + /// Checks manifest minimum API requirements for new declarations or subscriptions. + fn require_api(&self, what: &str, minor: u64) -> Result<(), HostError> { + let _ = (what, minor); + Ok(()) + } /// Sets (`Some`) or removes the plugin's status bar item `id`. fn status_item(&self, id: &str, item: Option); + /// Sets or removes the status override in the invoking window. + fn window_status_item(&self, client: &str, id: &str, item: Option) -> Result<(), HostError> { + let _ = (client, id, item); + Err(HostError::Invalid("window status unavailable".into())) + } /// Sets (`Some`, validated JSON text) or removes the plugin's context key, /// for window `client` (every window if `None`). fn set_context(&self, client: Option<&str>, key: &str, value: Option) -> Result<(), HostError> { @@ -181,6 +213,62 @@ pub trait HostApi: Send + Sync { /// Performs `request` (its host is granted), filling in secret placeholders. fn fetch(&self, request: HttpRequest, cancel: &CancellationToken) -> Result; fn secret_is_set(&self, name: &str) -> bool; + + /// Stores or deletes a secret declared by this plugin; never returns its value. + fn secret_set(&self, name: &str, value: Option<&str>) -> Result<(), HostError> { + let _ = (name, value); + Err(HostError::NotFound("secret".into())) + } + /// Creates a desktop loopback listener and returns its handle and redirect URI. + fn begin_loopback(&self, client: &str, path: &str) -> Result<(u64, String), HostError> { + let _ = (client, path); + Err(HostError::Failed("loopback unavailable".into())) + } + /// Awaits a browser redirect, excluded from the caller's execution budget. + fn wait_loopback( + &self, + id: u64, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + let _ = (id, timeout, cancel); + Err(HostError::NotFound("loopback".into())) + } + /// Releases a desktop listener when its resource or plugin stops. + fn close_loopback(&self, id: u64) { + let _ = id; + } + /// Connects to an approved host-local socket; owned by this plugin instance. + fn ipc_connect(&self, name: &str, cancel: &CancellationToken, timeout: Duration) -> Result { + let _ = (name, cancel, timeout); + Err(HostError::Failed("IPC unavailable".into())) + } + /// Writes to an owned IPC connection. + fn ipc_write( + &self, + id: u64, + bytes: Vec, + cancel: &CancellationToken, + timeout: Duration, + ) -> Result<(), HostError> { + let _ = (id, bytes, cancel, timeout); + Err(HostError::NotFound("connection".into())) + } + /// Reads from an owned IPC connection, empty on timeout or EOF. + fn ipc_read( + &self, + id: u64, + max: usize, + timeout: Duration, + cancel: &CancellationToken, + ) -> Result, HostError> { + let _ = (id, max, timeout, cancel); + Err(HostError::NotFound("connection".into())) + } + /// Closes an owned IPC connection, including when its resource is dropped. + fn ipc_close(&self, id: u64) { + let _ = id; + } /// Runs the approved file of `process:` with `cmd.env` added to /// the inherited environment, and waits. fn run_process( @@ -653,6 +741,18 @@ const MAX_BATCH: usize = 1000; fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event { match e { + WorkbenchEvent::FileClosed(p) => wit_events::Event::Other(wit_types::Extension { + kind: "file-closed".into(), + data: serde_json::to_string(&p).expect("path serializes"), + }), + WorkbenchEvent::SettingsChanged(keys) => wit_events::Event::Other(wit_types::Extension { + kind: "settings-changed".into(), + data: serde_json::to_string(&keys).expect("keys serialize"), + }), + WorkbenchEvent::InputModeChanged(mode) => wit_events::Event::Other(wit_types::Extension { + kind: "input-mode-changed".into(), + data: serde_json::to_string(&mode).expect("mode serializes"), + }), WorkbenchEvent::FileOpened(p) => wit_events::Event::FileOpened(p), WorkbenchEvent::FileSaved(p) => wit_events::Event::FileSaved(p), WorkbenchEvent::FilesChanged(batch) => wit_events::Event::Other(wit_types::Extension { diff --git a/crates/ide-plugin/src/types.rs b/crates/ide-plugin/src/types.rs index 81c4f0952..9ee469204 100644 --- a/crates/ide-plugin/src/types.rs +++ b/crates/ide-plugin/src/types.rs @@ -25,6 +25,8 @@ pub struct EditorContext { /// Where a command or event batch comes from: the window and its project. #[derive(Clone, Debug, Default)] pub struct Invocation { + /// Plugin instances waiting on this command chain; never re-enter one. + pub command_chain: Vec, pub client: Option, pub workspace_root: Option, /// Settings actions can read the global layer while retaining their project context. @@ -35,7 +37,7 @@ pub struct Invocation { } /// A failed host call, as the plugin sees it (WIT `types.error`). -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum HostError { /// Not granted; names the capability. Denied(String), @@ -98,6 +100,9 @@ pub enum Prompt { #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Type)] #[serde(rename_all = "kebab-case")] pub enum EventKind { + FileClosed, + SettingsChanged, + InputModeChanged, FileOpened, FileSaved, FilesChanged, @@ -108,7 +113,10 @@ pub enum EventKind { } impl EventKind { - pub const ALL: [Self; 7] = [ + pub const ALL: [Self; 10] = [ + Self::FileClosed, + Self::SettingsChanged, + Self::InputModeChanged, Self::FileOpened, Self::FileSaved, Self::FilesChanged, @@ -120,6 +128,9 @@ impl EventKind { pub fn name(self) -> &'static str { match self { + Self::FileClosed => "file-closed", + Self::SettingsChanged => "settings-changed", + Self::InputModeChanged => "input-mode-changed", Self::FileOpened => "file-opened", Self::FileSaved => "file-saved", Self::FilesChanged => "files-changed", @@ -138,7 +149,7 @@ impl EventKind { /// manifest declares). pub fn capability(self) -> Option { match self { - Self::ActionPerformed => Some(ide_extension::Capability::InputEvents), + Self::ActionPerformed | Self::InputModeChanged => Some(ide_extension::Capability::InputEvents), Self::Scheduled => None, _ => Some(ide_extension::Capability::Events), } @@ -188,10 +199,21 @@ pub struct FilesChanged { pub removed: Vec, } +/// The focused editor's input mode and optional visual sub-mode. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +pub struct InputMode { + pub path: String, + pub mode: String, + pub sub: Option, +} + /// A workbench event delivered to plugins. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] #[serde(rename_all = "camelCase", tag = "kind", content = "value")] pub enum WorkbenchEvent { + FileClosed(String), + SettingsChanged(Vec), + InputModeChanged(InputMode), FileOpened(String), FileSaved(String), FilesChanged(FilesChanged), @@ -204,6 +226,9 @@ pub enum WorkbenchEvent { impl WorkbenchEvent { pub fn kind(&self) -> EventKind { match self { + Self::FileClosed(_) => EventKind::FileClosed, + Self::SettingsChanged(_) => EventKind::SettingsChanged, + Self::InputModeChanged(_) => EventKind::InputModeChanged, Self::FileOpened(_) => EventKind::FileOpened, Self::FileSaved(_) => EventKind::FileSaved, Self::FilesChanged(_) => EventKind::FilesChanged, @@ -350,6 +375,8 @@ pub struct HttpRequest { pub headers: Vec<(String, String)>, pub body: Option>, pub timeout: Duration, + /// Grants checked again before following a redirect. + pub grants: Vec, } #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -371,6 +398,8 @@ pub struct ProcessOutput { /// the environment to add to the inherited one (WIT `process.command`). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct ProcessCommand { + /// The invoking project whose executable override applies, independent of cwd. + pub approval_root: Option, pub program: String, pub args: Vec, pub env: Vec<(String, String)>, @@ -388,23 +417,27 @@ pub struct ProcessChunk { /// Where `net:` requests may go: the URL's host when it is `https`, or /// `http` to the loopback interface. pub fn net_host(url: &str) -> Result { - let (scheme, rest) = url.split_once("://").ok_or_else(|| format!("{url:?} is not an absolute URL"))?; - let authority = rest.split(['/', '?', '#']).next().unwrap_or_default(); - let authority = authority.rsplit_once('@').map_or(authority, |(_, h)| h); - let host = if let Some(v6) = authority.strip_prefix('[') { - v6.split(']').next().unwrap_or_default().to_owned() - } else { - authority.split(':').next().unwrap_or_default().to_ascii_lowercase() - }; - if host.is_empty() { - return Err(format!("{url:?} has no host")); + let parsed = url::Url::parse(url).map_err(|e| format!("invalid URL: {e}"))?; + if !matches!(parsed.scheme(), "http" | "https") { + return Err(format!("unsupported scheme {:?}", parsed.scheme())); } - let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1"); - match scheme.to_ascii_lowercase().as_str() { - "https" => Ok(host), - "http" if loopback => Ok(host), - "http" => Err(format!("{url:?}: plain http is only allowed to localhost")), - other => Err(format!("{url:?}: unsupported scheme {other:?}")), + match parsed.host() { + Some(url::Host::Domain(host)) => Ok(host.trim_end_matches('.').to_ascii_lowercase()), + Some(url::Host::Ipv4(host)) => Ok(host.to_string()), + Some(url::Host::Ipv6(host)) => Ok(host.to_string()), + None => Err("URL has no host".into()), + } +} + +/// The grant required by a URL; loopback HTTP retains the original `net:` rule. +pub fn net_capability(url: &str) -> Result { + let host = net_host(url)?; + if url::Url::parse(url).is_ok_and(|u| u.scheme() == "http") + && !matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1") + { + Ok(ide_extension::Capability::NetHttp(host)) + } else { + Ok(ide_extension::Capability::Net(host)) } } @@ -427,7 +460,10 @@ mod tests { assert_eq!(net_host("https://API.example.com:8443/v1?x").unwrap(), "api.example.com"); assert_eq!(net_host("http://localhost:11434/api").unwrap(), "localhost"); assert_eq!(net_host("https://user:pw@h.io/").unwrap(), "h.io"); - assert!(net_host("http://example.com/").is_err()); + assert_eq!( + net_capability("http://example.com/").unwrap(), + ide_extension::Capability::NetHttp("example.com".into()) + ); assert!(net_host("file:///etc/passwd").is_err()); assert!(net_host("example.com").is_err()); } diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index f1b8008c0..8fa1bce03 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -6,7 +6,7 @@ use crate::runtime::{MAX_TITLE, StoreData, clip}; use crate::sandbox; use crate::types::{ EditorContext, EventKind, HostError, HttpRequest, NotificationLevel, PickItem, ProcessChunk, ProcessCommand, - Prompt, StatusItem, net_host, + Prompt, StatusItem, net_capability, }; use ide_core::ipc_path::to_ipc; use ide_extension::Capability; @@ -25,6 +25,8 @@ pub(crate) mod bindings { "openidea:plugin/invocation.invocation": super::InvocationRes, "openidea:plugin/tasks.task": super::TaskRes, "openidea:plugin/process.child": super::ChildRes, + "openidea:plugin/ipc.connection": super::ConnectionRes, + "openidea:plugin/auth.loopback": super::LoopbackRes, }, }); } @@ -51,6 +53,10 @@ pub(crate) mod syntax_bindings { "openidea:plugin/net": super::bindings::openidea::plugin::net, "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/output": super::bindings::openidea::plugin::output, + "openidea:plugin/auth": super::bindings::openidea::plugin::auth, + "openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner, + "openidea:plugin/ipc": super::bindings::openidea::plugin::ipc, "openidea:plugin/fs": super::bindings::openidea::plugin::fs, "openidea:plugin/views": super::bindings::openidea::plugin::views, "openidea:plugin/settings": super::bindings::openidea::plugin::settings, @@ -80,6 +86,10 @@ pub(crate) mod providers_bindings { "openidea:plugin/net": super::bindings::openidea::plugin::net, "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/output": super::bindings::openidea::plugin::output, + "openidea:plugin/auth": super::bindings::openidea::plugin::auth, + "openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner, + "openidea:plugin/ipc": super::bindings::openidea::plugin::ipc, "openidea:plugin/fs": super::bindings::openidea::plugin::fs, "openidea:plugin/views": super::bindings::openidea::plugin::views, "openidea:plugin/settings": super::bindings::openidea::plugin::settings, @@ -109,6 +119,10 @@ pub(crate) mod views_bindings { "openidea:plugin/net": super::bindings::openidea::plugin::net, "openidea:plugin/secrets": super::bindings::openidea::plugin::secrets, "openidea:plugin/process": super::bindings::openidea::plugin::process, + "openidea:plugin/output": super::bindings::openidea::plugin::output, + "openidea:plugin/auth": super::bindings::openidea::plugin::auth, + "openidea:plugin/command-runner": super::bindings::openidea::plugin::command_runner, + "openidea:plugin/ipc": super::bindings::openidea::plugin::ipc, "openidea:plugin/fs": super::bindings::openidea::plugin::fs, "openidea:plugin/views": super::bindings::openidea::plugin::views, "openidea:plugin/settings": super::bindings::openidea::plugin::settings, @@ -117,8 +131,8 @@ pub(crate) mod views_bindings { } use bindings::openidea::plugin::{ - commit, detail_types, diagnostics, editor, events, fs, invocation, log, net, process, secrets, settings, storage, - tasks, types as wit, ui, vcs, views, workspace, + commit, detail_types, diagnostics, editor, events, fs, invocation, ipc, log, net, process, secrets, settings, + storage, tasks, types as wit, ui, vcs, views, workspace, }; /// A project handle: its root. @@ -319,6 +333,14 @@ impl StoreData { self.ask(Prompt::QuickPick { title: clip(title, MAX_TITLE), items, multiple }) } + fn require_window(&self) -> Result<(), wit::Error> { + self.require_interactive()?; + if self.invocation.client.is_none() { + return Err(wit::Error::Invalid("requires an invoking window".into())); + } + Ok(()) + } + /// APIs reserved for commands and events exclude code-action resolution. fn require_interactive(&self) -> Result<(), wit::Error> { if self.interactive { @@ -381,6 +403,29 @@ impl ui::Host for StoreData { Ok(()) } + fn set_window_status_item(&mut self, id: String, item: ui::StatusItem) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let item = StatusItem { + text: clip(item.text, MAX_STATUS_TEXT), + tooltip: item.tooltip.map(|t| clip(t, 1024)), + command: item.command.map(|c| clip(c, 128)), + }; + Ok(self + .host + .window_status_item(self.invocation.client.as_deref().expect("checked"), &clip(id, 64), Some(item)) + .map_err(to_wit)) + } + fn remove_window_status_item(&mut self, id: String) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + Ok(self + .host + .window_status_item(self.invocation.client.as_deref().expect("checked"), &clip(id, 64), None) + .map_err(to_wit)) + } fn set_context(&mut self, key: String, value: ui::ContextValue) -> Fallible<()> { let valid_key = (1..=64).contains(&key.len()) && key.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-')); @@ -850,6 +895,11 @@ impl events::Host for StoreData { let Some(kind) = EventKind::parse(&kind) else { return Ok(Err(wit::Error::Invalid(format!("no event kind {kind:?} in this OpenIDEA")))); }; + if matches!(kind, EventKind::FileClosed | EventKind::SettingsChanged | EventKind::InputModeChanged) + && let Err(e) = self.host.require_api(kind.name(), 4) + { + return Ok(Err(to_wit(e))); + } if let Some(cap) = kind.capability() && let Err(e) = self.require(cap) { @@ -952,11 +1002,11 @@ impl diagnostics::Host for StoreData { impl net::Host for StoreData { fn fetch(&mut self, req: net::Request) -> Fallible { - let host = match net_host(&req.url) { + let capability = match net_capability(&req.url) { Ok(h) => h, Err(e) => return Ok(Err(wit::Error::Invalid(e))), }; - if let Err(e) = self.require(Capability::Net(host)) { + if let Err(e) = self.require(capability) { return Ok(Err(e)); } if req.headers.iter().any(|h| h.value.contains("{{secret:")) @@ -974,6 +1024,7 @@ impl net::Host for StoreData { headers: req.headers.into_iter().map(|h| (h.name, h.value)).collect(), body: req.body, timeout: wanted.min(self.remaining()), + grants: self.granted.clone(), }; let token = self.cancel.token(); Ok(self @@ -989,6 +1040,21 @@ impl net::Host for StoreData { } impl secrets::Host for StoreData { + fn set(&mut self, name: String, value: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::Secrets) { + return Ok(Err(e)); + } + if name.len() > 128 || value.len() > 64 << 10 { + return Ok(Err(wit::Error::Invalid("secret name or value too long".into()))); + } + Ok(self.host.secret_set(&name, Some(&value)).map_err(to_wit)) + } + fn delete(&mut self, name: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::Secrets) { + return Ok(Err(e)); + } + Ok(self.host.secret_set(&name, None).map_err(to_wit)) + } fn is_set(&mut self, name: String) -> wasmtime::Result { Ok(self.granted.iter().any(|g| g.covers(&Capability::Secrets)) && self.host.secret_is_set(&name)) } @@ -1013,7 +1079,12 @@ impl StoreData { return Err(wit::Error::Invalid(format!("the value of {name:?} is too long or holds a NUL"))); } } - Ok(ProcessCommand { program: cmd.program, args: cmd.args, env: cmd.env }) + Ok(ProcessCommand { + program: cmd.program, + args: cmd.args, + env: cmd.env, + approval_root: self.invocation.workspace_root.clone(), + }) } /// The project a call runs in, when it named one. @@ -1489,3 +1560,129 @@ pub(crate) fn diagnostics_from_wit(items: Vec, source: }) .collect() } + +/// An IPC connection owned by this plugin instance. +pub struct ConnectionRes { + id: u64, + host: std::sync::Arc, +} +impl Drop for ConnectionRes { + fn drop(&mut self) { + self.host.ipc_close(self.id); + } +} +impl ipc::Host for StoreData { + fn connect(&mut self, name: String) -> Fallible> { + if let Err(e) = ide_extension::validate_ipc_name(&name, false) { + return Ok(Err(wit::Error::Invalid(e))); + } + if let Err(e) = self.require(Capability::Ipc(name.clone())) { + return Ok(Err(e)); + } + let name = match ide_extension::expand_ipc_name(&name) { + Ok(name) => name, + Err(e) => return Ok(Err(wit::Error::Invalid(e))), + }; + match self.host.ipc_connect(&name, &self.cancel.token(), self.remaining()) { + Ok(id) => self.push(ConnectionRes { id, host: self.host.clone() }).map(Ok), + Err(e) => Ok(Err(to_wit(e))), + } + } +} +impl ipc::HostConnection for StoreData { + fn write(&mut self, this: Resource, bytes: Vec) -> Fallible<()> { + if bytes.len() > 1 << 20 { + return Ok(Err(wit::Error::Invalid("at most 1 MiB per write".into()))); + } + let id = self.table.get(&this)?.id; + Ok(self.host.ipc_write(id, bytes, &self.cancel.token(), self.remaining()).map_err(to_wit)) + } + fn read(&mut self, this: Resource, max_bytes: u32, timeout_ms: u32) -> Fallible> { + let id = self.table.get(&this)?.id; + let timeout = Duration::from_millis(u64::from(timeout_ms)).min(self.remaining()); + Ok(self.host.ipc_read(id, (max_bytes as usize).min(1 << 20), timeout, &self.cancel.token()).map_err(to_wit)) + } + fn close(&mut self, this: Resource) -> Fallible<()> { + let id = self.table.get(&this)?.id; + self.host.ipc_close(id); + Ok(Ok(())) + } + fn drop(&mut self, this: Resource) -> wasmtime::Result<()> { + self.table.delete(this)?; + Ok(()) + } +} + +impl bindings::openidea::plugin::command_runner::Host for StoreData { + fn execute(&mut self, id: String, arg: Option) -> Fallible> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + if id.len() > 256 || arg.as_ref().is_some_and(|a| a.len() > 64 << 10) { + return Ok(Err(wit::Error::Invalid("command id or argument too long".into()))); + } + Ok(self + .host + .execute_command(&self.invocation, &id, arg, &self.cancel.token(), self.remaining()) + .map_err(to_wit)) + } +} + +/// A desktop OAuth listener; its URI remains available after the one-shot wait. +pub struct LoopbackRes { + id: u64, + uri: String, + host: std::sync::Arc, +} +impl Drop for LoopbackRes { + fn drop(&mut self) { + self.host.close_loopback(self.id); + } +} +impl bindings::openidea::plugin::auth::Host for StoreData { + fn begin_loopback(&mut self, path: String) -> Fallible> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + match self.host.begin_loopback(self.invocation.client.as_deref().expect("checked"), &path) { + Ok((id, uri)) => self.push(LoopbackRes { id, uri, host: self.host.clone() }).map(Ok), + Err(e) => Ok(Err(to_wit(e))), + } + } +} +impl bindings::openidea::plugin::auth::HostLoopback for StoreData { + fn redirect_uri(&mut self, this: Resource) -> wasmtime::Result { + Ok(self.table.get(&this)?.uri.clone()) + } + fn wait(&mut self, this: Resource, timeout_ms: u32) -> Fallible> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let id = self.table.get(&this)?.id; + let started = Instant::now(); + let result = self.host.wait_loopback(id, Duration::from_millis(u64::from(timeout_ms)), &self.cancel.token()); + let waited = started.elapsed(); + self.deadline += waited; + self.call_started += waited; + Ok(result.map_err(to_wit)) + } + fn drop(&mut self, this: Resource) -> wasmtime::Result<()> { + self.table.delete(this)?; + Ok(()) + } +} + +impl bindings::openidea::plugin::output::Host for StoreData { + fn append(&mut self, channel: String, text: String) -> Fallible<()> { + Ok(self.host.output_write(&channel, Some(&text)).map_err(to_wit)) + } + fn clear(&mut self, channel: String) -> Fallible<()> { + Ok(self.host.output_write(&channel, None).map_err(to_wit)) + } + fn reveal(&mut self, channel: String) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + Ok(self.host.output_reveal(self.invocation.client.as_deref().expect("checked"), &channel).map_err(to_wit)) + } +} diff --git a/crates/ide-plugin/tests/api_compat.rs b/crates/ide-plugin/tests/api_compat.rs index 7926dae3f..602dc883c 100644 --- a/crates/ide-plugin/tests/api_compat.rs +++ b/crates/ide-plugin/tests/api_compat.rs @@ -88,15 +88,15 @@ fn the_sdk_carries_the_hosts_wit() { #[test] fn the_version_check_runs_compatible_components_and_explains_the_rest() { - let host = v("1.3.0"); - for ok in ["1.0.0", "1.3.0", "1.3.7", "1.0.0-rc.1"] { + let host = v("1.4.0"); + for ok in ["1.0.0", "1.3.0", "1.3.7", "1.4.0", "1.0.0-rc.1"] { assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}"); } - let newer = check_api(&v("1.4.0"), &host).unwrap_err(); - assert!(newer.contains("1.4") && newer.contains("update OpenIDEA"), "{newer}"); + let newer = check_api(&v("1.5.0"), &host).unwrap_err(); + assert!(newer.contains("1.5") && newer.contains("update OpenIDEA"), "{newer}"); assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA")); let older = check_api(&v("0.2.0"), &host).unwrap_err(); - assert!(older.contains("rebuild it with the 1.3 SDK"), "{older}"); + assert!(older.contains("rebuild it with the 1.4 SDK"), "{older}"); // 0.x: every minor is its own API. assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(())); assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err()); diff --git a/crates/ide-plugin/tests/fixtures/api14/Cargo.lock b/crates/ide-plugin/tests/fixtures/api14/Cargo.lock new file mode 100644 index 000000000..fcc4da830 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/Cargo.lock @@ -0,0 +1,337 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "wit-bindgen", +] + +[[package]] +name = "openidea-plugin-api14" +version = "0.1.0" +dependencies = [ + "openidea-plugin", + "serde_json", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/api14/Cargo.toml b/crates/ide-plugin/tests/fixtures/api14/Cargo.toml new file mode 100644 index 000000000..26cadfe50 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "openidea-plugin-api14" +version = "0.1.0" +edition = "2024" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } +serde_json = "1" + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm new file mode 100644 index 000000000..68d46d438 Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources new file mode 100644 index 000000000..495ea9bd1 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -0,0 +1 @@ +59145ee5ce6e05000c52d80174156c66e4fcdc5fa9ff329f0d803c15aa1f4fbc diff --git a/crates/ide-plugin/tests/fixtures/api14/plugin.toml b/crates/ide-plugin/tests/fixtures/api14/plugin.toml new file mode 100644 index 000000000..bb06f2b02 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/plugin.toml @@ -0,0 +1,85 @@ +id = "api14" +name = "API 1.4 host tests" +version = "0.1.0" +engines.openidea = "^1.4" +wasm = "dist/plugin.wasm" +activation = ["on-command:*", "on-event:file-closed", "on-event:settings-changed", "on-event:input-mode-changed"] + +[capabilities] +required = ["storage"] +optional = ["events", "events.input", "editor.read", "secrets", "net:localhost", "net.http:example.com", "ipc:$TMPDIR/api14-*"] + +[[contributes.secrets]] +name = "token" +label = "Token" + +[contributes.settings] +schema = "settings.json" + +[[contributes.commands]] +id = "ipc" +title = "ipc" + +[[contributes.commands]] +id = "fetch" +title = "fetch" + +[[contributes.commands]] +id = "window-status" +title = "window-status" + +[[contributes.commands]] +id = "remove-window-status" +title = "remove-window-status" + +[[contributes.commands]] +id = "global-status" +title = "global-status" + +[[contributes.commands]] +id = "execute" +title = "execute" + +[[contributes.commands]] +id = "oauth" +title = "oauth" + +[[contributes.commands]] +id = "secret" +title = "secret" + +[[contributes.commands]] +id = "delete-secret" +title = "delete-secret" + +[[contributes.commands]] +id = "undeclared-secret" +title = "undeclared-secret" + +[[contributes.commands]] +id = "output" +title = "output" + +[[contributes.commands]] +id = "events" +title = "events" + +[[contributes.commands]] +id = "process-run" +title = "process-run" + +[[contributes.commands]] +id = "process-run-command" +title = "process-run-command" + +[[contributes.commands]] +id = "process-start" +title = "process-start" + +[[contributes.commands]] +id = "terminal" +title = "terminal" + +[[contributes.commands]] +id = "log" +title = "log" diff --git a/crates/ide-plugin/tests/fixtures/api14/settings.json b/crates/ide-plugin/tests/fixtures/api14/settings.json new file mode 100644 index 000000000..9a6af9374 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/settings.json @@ -0,0 +1 @@ +{"properties":{"enabled":{"type":"boolean","title":"Enabled","default":false}}} diff --git a/crates/ide-plugin/tests/fixtures/api14/src/lib.rs b/crates/ide-plugin/tests/fixtures/api14/src/lib.rs new file mode 100644 index 000000000..92c2597f5 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/api14/src/lib.rs @@ -0,0 +1,102 @@ +use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, host, register_plugin}; +#[derive(Default)] +struct Api14; +impl Plugin for Api14 { + fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result, Error> { + let arg = arg.unwrap_or_default(); + match id { + "ipc" => { + let stream = host::ipc_connect(arg)?; + stream.write(b"echo")?; + let bytes = stream.read(4, 2000)?; + stream.close()?; + Ok(Some(String::from_utf8_lossy(&bytes).into())) + } + "fetch" => { + let response = host::fetch(&openidea_plugin::HttpRequest::get(arg))?; + Ok(Some(String::from_utf8_lossy(&response.body).into())) + } + "global-status" | "window-status" => { + let item = StatusItem { text: arg.into(), tooltip: None, command: Some("events".into()) }; + if id == "global-status" { + host::set_status_item("state", &item); + } else { + host::set_window_status_item("state", &item)?; + } + Ok(None) + } + "remove-window-status" => { + host::remove_window_status_item("state")?; + Ok(None) + } + "execute" => host::execute_command(arg, Some("argument")), + "oauth" => { + let redirect = host::begin_loopback("oauth/callback")?; + host::output_append("oauth", &redirect.redirect_uri())?; + redirect.wait(2000) + } + "secret" => { + host::secret_set("token", arg)?; + Ok(None) + } + "delete-secret" => { + host::secret_delete("token")?; + Ok(None) + } + "undeclared-secret" => { + host::secret_set("undeclared", arg)?; + Ok(None) + } + "output" => { + host::output_append("test", arg)?; + host::output_reveal("test")?; + Ok(None) + } + "process-run" => Ok(Some(host::run_process("api14-tool", &[], None)?.stdout)), + "process-run-command" => Ok(Some(host::run_command(&host::Command::new("api14-tool"), None, None)?.stdout)), + "process-start" => { + let child = host::start(&host::Command::new("api14-tool"), None)?; + Ok(Some(child.wait(2000)?.stdout)) + } + "terminal" => { + host::open_terminal("API test", "api14-tool", &[])?; + Ok(None) + } + "log" => { + host::open_log_tab( + "api-test", + "API test", + &openidea_plugin::details::ProcessLog { + program: "api14-tool".into(), + args: Vec::new(), + toggles: Vec::new(), + }, + )?; + Ok(None) + } + "events" => host::storage::get("events"), + _ => Err(Error::NotFound(id.into())), + } + } + fn handle_events(&mut self, events: &[Event], ctx: &Invocation) { + let mut received: Vec = + host::storage::get("events").unwrap().map(|s| serde_json::from_str(&s).unwrap()).unwrap_or_default(); + for event in events { + if let Event::Other { kind, data } = event { + let editor = ctx.editor().map(|e| { + ( + e.path(), + e.selections() + .unwrap() + .into_iter() + .map(|r| [r.start.line, r.start.character, r.end.line, r.end.character]) + .collect::>(), + ) + }); + received.push(serde_json::json!({ "kind": kind, "data": data, "editor": editor })); + } + } + host::storage::set("events", &serde_json::to_string(&received).unwrap()).unwrap(); + } +} +register_plugin!(Api14); diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 498018633..24a909d97 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 60b38a389..f70006d16 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -6d7d707c7492d487fbd9debae791ad7e3755ac005f1f518efa54e6536ec59f08 +aae3c82c01b54387a4a18d95614e5275374bb5d1fde8685e11cc4b0ca54f3edb diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index cdcf91b87..238e4a66f 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index 235ce4fd6..0978e9f64 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -652977e0bf63bc7664807016998a4d4795d2a7eb841ee1912ef562057e5437cb +49a56737954cd79c7dcca5543856473bfe77b420e977c6091ab832bafadac8c1 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 6aba123b1..889fbb2f2 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index 2f45ab6e3..9c13180a8 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -42d3856b634bdaa69e21f4a42a9f375b73c2d19753a8986b82f2228bf92d37bc +07882856be39355607403ff5c2066c537333fc80e5fa4248f7193456c56e34c2 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index 03887b874..ec882571b 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index a10b690a5..153c0dd54 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -cacd381d84e1070fffe8f0ac64fad91b768df63b759c0b3e5e2d22a6a2fdeb73 +81f06d523eab81c3a930906750d110d49a2ea1028c41aa825551b854ad2c971c diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index a4f2867c3..d2e36f1b2 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 3fa85d991..0febd991c 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -0d418585dca868fbceb6432d06c5c838c3d42a9e99e7a9c7641199f25fb8fbe8 +e5552be8e6bcb0dc1aed69b15ef6d56c4861bca507514fd11549387a85703e38 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index 3f37ce42e..9610d6e85 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 22f4d5f57..5f950f09f 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -6caa94db0c866c0c7f86011dbf837b3f9edb1c891276a4d435a8d02e8f64e0cb +8184794f370596474b2fc306a3adce3f1ce8685bea748442133efd92abab5cdc diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index 865a9b957..9e7dc8855 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index b9928c8e8..002e4d4f8 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -8d9c6bcd572b6fb54dd42c79d66d4971e55ec3dc072fc769f5634212c2927e22 +3b11fb8a7e61919808ef2c09c770be0b6cc86c2ba20abf62aa95b3e7f34c8453 diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index fec17dc6c..9ce6fd45d 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index e62ffb8cd..67a7344b4 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -2af65b7db7edce8450f0ca829adb3b79fcb64b1ec3d39b785fb9df9423815e7b +1319e0b252577fc01c1b999bb35c43168d2416c985362d49e06e7d627205347b diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 2a468a118..97f2423cc 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index 9cfccba7f..236559007 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -40f80dcba2f370d02e2d5ad9609b21500fc42fc7c7202b439485a9cbf7baf727 +d2e60f464a297332b55172cac4968fced00a7ec218af9c6ce7e01b259da515d7 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index 5bd99d2cd..6cde36bdc 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index a1c8782be..757b17a37 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -a5ca61ba85297c52936cf9892ccf1c678383641c84a5a885389b24582fa1abfb +4daf9ad04a2b10872799976debb792ce24f04fb128e0318e784e6a0a307db9de diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index e8710f3dd..5df62c9e7 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index b77911fb8..af57b8835 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -5723b90f8a742f912b315209fc597e3ea7f428a2a234cf4ea5b4620454206d71 +73d73b1e33e2e7ad58db158744630cc53b263213940b8aca251c1fe36f6e9368 diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 7fe3f4277..82155eeb1 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index 53d5b7a23..d257a2bd4 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -dd5d41490f53a3b9b03d45ee8aba9f3fb08dd9211e835db5d3f9f7c42d3b6f9a +af621d99276ac3ad29a92c4c056e1bf8ab253b911a0fbd6562f0f227e2941177 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index 1c6092c27..75246295e 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index 1612f2bb1..94c17a282 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -185557c699fc00796eb487f50c688c3e91d8895bd05d4185b492352c187f9d98 +b5e51d67739b775dda14f342db2d0776a0fea5aaf6fe482416b99581c998dd55 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index 59db88875..18234bec2 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -5,9 +5,9 @@ wit_bindgen::generate!({ inline: " package fixture:misbehave; world misbehave { - include openidea:plugin/plugin-syntax@1.3.0; - export openidea:plugin/providers@1.3.0; - export openidea:plugin/file-actions@1.3.0; + include openidea:plugin/plugin-syntax@1.4.0; + export openidea:plugin/providers@1.4.0; + export openidea:plugin/file-actions@1.4.0; } ", path: "../../../../../wit", diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index b77075715..5d15d374e 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index 6f4fdb848..95c6e8bf2 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -d047b5618051144ec754b481b6bc75fae428d96c83711e9f0edf78749df59016 +85e18a196e960ff9b1bc61bae84fd3f7ec5b08872de0df4b12d6843b0bcea467 diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index d437b5359..c05e178bc 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index 0d0841088..f54f9cab3 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -18957534fc011510894544b61e154a9d0972c27ab1872d9d2accd01864984fa0 +15c74b27c3fc5809d061768df0abd84a785a641d685c33fc1ca4c637d7268008 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index d270f4772..e5e911de1 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index da42ec0b8..fe5ca8081 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -3562bc253b0b4f0fa1cb15b9c8a7470a09719b28008aa8f5f459bbaba8eda598 +9e8e38868d12ca3ac2504fc6e537cb93efc3fa4db33e08b8abdaaa86e5f6e254 diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index 49f377ecb..33b29836e 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index 7b3b8525e..aeeec21ab 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -f28b40f3708ec4f828d04f7cec29208b66d0ab6158b26c60c0bd989cdc74f9b4 +742f536436ef3a6034087a85f41765bbb9a55a8f7ec61e24e752e4dc4031a57b diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 6dad1e8a6..6b2120c58 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index 98a0bf52b..f073f0555 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -60f6c34375c918ee941dc8f5a1c7851732fd0f5dd2c14ec609db1955c557026a +9c84ce120727c3a85e9d94e607a266b02faf70b5ca77e4b2ee4debcca272e2b1 diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index 5d26e6c68..db1b32148 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index afddaf44f..c36bdcd59 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -edac658f8a54e396f294c74d031a31787508583256659a8effa8cc3d330e9a08 +569e5be98fcf45288141fc40bcb50e0a3fb8038d679c6b9a06c73efd0d425494 diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index 44219a22a..f9efbf790 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index 02312108a..7fc5b327f 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -28e1d58c8ab50574e184cb401050a6fd2755c9398cd3a3720dc376f67461a44b +38c9e6fd9a8aa0b8c6ec830080fbba01a637a98fb0b19f77fbe98324271cb096 diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index 176b52e99..f8a218b23 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 7c51baa74..52bf05d18 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -e80605523d9aaa1c88c83deac439a39a739541bdb327e279352441547de3c232 +f9102292daa0fd169e55791b48dae2c10893cb3d867377e0745a013657b1496e diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index 5671f3313..3b2742239 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index f039130a9..2915a92ab 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -efb03a86021bf5690feab0446c77d977c6252a4da1ee41030d923350e6cc5d11 +371709b0820de67ce575df082776a9b3c5e116aa44f18c8be53851192431d4f2 diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index df2e4016d..603a63446 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index c59478b01..800b7e274 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -009f7e069920bcf0e7699b57cd41954dc1dcb620977e081c24ec58ef0a9809d2 +81537fa6fb1212fda71bb081df1fceff3a2e27d3df43e89e1b7301d8b9efc306 diff --git a/plugins/README.md b/plugins/README.md index 333cd1df4..2d3a138ee 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -37,7 +37,7 @@ sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host) crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints ``` -The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.3.0`, world +The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.4.0`, world `plugin`). ## 1. Quick start @@ -299,10 +299,12 @@ machine. Users can revoke optional capabilities in Settings › Plugins. | `vcs.write` | medium | `Project::vcs_fetch` (trusted projects only), `host::set_commit_message` | | `storage` | low | `host::storage` (64 MiB per plugin, counting UTF-8 bytes of keys and values) | | `events` | low | file opened/saved, editor focused, repository changed events | -| `events.input` | medium | `action-performed` events (which actions you run, and how) | +| `events.input` | medium | `action-performed` and `input-mode-changed` events | | `process:` | high | `Project::run_process`, language servers, debug adapters, runs | -| `net:` | medium | `host::fetch` to that host (`*.example.com`: its subdomains) | -| `secrets` | medium | `{{secret:}}` in request headers, `host::secret_is_set` | +| `net:` | medium | `host::fetch` over HTTPS (also loopback HTTP); `*.example.com` matches subdomains | +| `net.http:` | medium | Unencrypted HTTP to that host; API 1.4, same wildcard rules as `net:` | +| `ipc:` | high | Local Unix sockets or Windows named pipes on the project machine; API 1.4 | +| `secrets` | medium | `{{secret:}}` in request headers, `host::secret_is_set`, `secret_set`, `secret_delete` | | `clipboard` | medium | `host::copy_to_clipboard` and the clipboard API in the plugin's web views | `process:` capabilities are also derived from what the contributions start: a @@ -438,45 +440,51 @@ then run `openidea-plugin check`. ### The API -| Rust SDK | WIT | Notes | -| ------------------------------------------------------------------------ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _" failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | -| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | -| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | -| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | -| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | -| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | -| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | -| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | -| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | -| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | -| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | -| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | -| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | -| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | -| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | -| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | -| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | -| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | -| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | -| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | -| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | -| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | -| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | -| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | -| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | -| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | -| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | -| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | -| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. | -| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | -| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | -| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | -| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | -| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | -| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | -| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | -| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | +| Rust SDK | WIT | Notes | +| ------------------------------------------------------------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Plugin::run_command(id, ctx, arg)` | export `commands.run` | `ctx` is the window: `ctx.project()`, `ctx.editor()`. An error shows _"<title> failed: …"_; the plugin keeps running. `"msg".into()` is `Error::Failed`; `Cancelled` and `Denied` don't count as the plugin failing. | +| `Plugin::handle_events(events, ctx)` | export `event-handler.handle` | Batches of subscribed events, oldest first, per window. | +| `Plugin::activate` / `deactivate` | export `lifecycle` | Per instance: after a crash or idle reclaim a new one is activated. | +| `TextEditor::document()` → `{version, text}` | `editor.text-editor.document` | `selections()` are those when the command ran (0-based lines, UTF-16 columns). | +| `TextEditor::apply_edits(version, edits)` | `editor.text-editor.apply-edits` | One undoable change, only if the document is still at `version` — else `Error::Stale` and nothing changes. `transform_selections` retries once. | +| `Project::root()`, `read_file(path)` | `workspace.project` | Absolute or project-relative; `..`/symlinks escaping the root are rejected; UTF-8 only, ≤ 16 MiB; unsaved editor contents win; a missing path is `Error::NotFound`. | +| `Project::exists(path)`, `stat(path)` | `workspace.project` | `exists` covers files and directories, hidden and ignored included, without reading content; `stat` gives kind, size and modified time (`Error::NotFound` for a missing path). | +| `host::projects()` | `workspace.projects` | Every open project (for scheduled work without a window). | +| `Project::vcs_status()`, `vcs_remotes()`, `vcs_fetch()` | `vcs` | `vcs_remotes` returns `(name, url)` pairs; fetch runs git, so only in trusted projects (call it inside a task). | +| `host::pending_commit()`, `host::set_commit_message(revision, text)` | `commit` | The commit being prepared in the calling window and its message; see _Commits_. | +| `host::subscribe(kind)` | `events.subscribe` | For the session, across idle reclaim (an event activates the plugin). Or declare `on-event:<kind>`. | +| `host::begin_task(title, cancellable)` → `Task` | `tasks.begin` | Shown with the background tasks; `report`, `is_cancelled`; the call may run 60 s instead of 5 s while it is open; dropping it ends it. | +| `host::storage::{get, set, delete, keys}` | `storage` | Survives restarts; the instance's memory does not. Deleted on uninstall. | +| `host::set_status_item(id, item)`, `remove_status_item` | `ui` | `text`, `tooltip`, `command` (one of yours, run on click); at most 8; kept while the plugin is idle. | +| `host::set_window_status_item(id, item)`, `remove_window_status_item(id)` | `ui.{set,remove}-window-status-item` | API 1.4: window-only override; removed on window close or plugin stop; removing falls back to the global item. Click runs its command in that window. | +| `host::execute_command(id, arg)` → `Option<String>` | `command-runner.execute` | API 1.4: stable IDE action or `plugin.<plugin-id>.<command-id>` in the invoking window. IDE actions return none; plugin commands return their result. Unknown ids are not-found; at most 8 nested calls, no re-entry into a waiting instance. | +| `host::ipc_connect(name)` → `Connection` | `ipc.connect` | API 1.4: `write(bytes)`, `read(max_bytes, timeout_ms)`, `close()`; requires `ipc:<path>`, at most 8 connections, closed on drop or plugin stop. Runs on the project server in remote projects. | +| `host::secret_set(name, value)`, `secret_delete(name)` | `secrets.{set,delete}` | API 1.4: requires `secrets` and a declared name. Never returns the value. | +| `host::begin_loopback(path)` → `Loopback` | `auth.begin-loopback` | API 1.4: `redirect_uri()`, `wait(timeout_ms)` → raw query or none on timeout. Desktop-only, even for remote projects; no capability. At most 2 listeners; one-shot, closed on timeout, drop or stop. Waiting excludes the call budget. | +| `host::output_append(channel, text)`, `output_clear`, `output_reveal` | `output.{append,clear,reveal}` | API 1.4: read-only Output tabs; 32 named channels per plugin, each a 1 MiB UTF-8 ring buffer. Reveal requires the invoking window. | +| `host::set_context(key, value)`, `remove_context` | `ui.{set,remove}-context` | Sets `plugin.<id>.<key>` for `when` clauses in the window the call came from (`true`, `3.5`, `"text"`; `ContextValue`). Key 1–64 of `A-Za-z0-9_-`, 100 per plugin; gone when the plugin stops. | +| `host::notify(level, title, body)` | `ui.show-notification` | Balloon in the window the command or events came from (every window otherwise). | +| `host::copy_to_clipboard(text)` | `ui.copy-to-clipboard` | Copies `text` to the system clipboard. Needs `clipboard`. | +| `host::open_url(url)` | `ui.open-url` | Opens an `http://` or `https://` URL in the user's default browser. | +| `host::pick(title, items)`, `pick_many` | `ui.pick`, `ui.pick-many` | Picks key(s) from `PickItem`s, or `None` when dismissed. From a command/event or code-action resolution in its editor window (else `invalid`); waiting is excluded from the budget. | +| `host::input(prompt, value)` | `ui.input` | A one-line text box pre-filled with `value`; `None` when dismissed. Same rules as `pick`. | +| `host::input_multiline(prompt, value)` | `ui.input-multiline` | A multi-line text box pre-filled with `value`; `None` when dismissed; Cmd/Ctrl+Enter confirms. Only from a command or event of a window. | +| `host::confirm(title, body)` | `ui.confirm` | OK / Cancel; `true` on OK. Same rules as `pick`. | +| `host::locale()` | `ui.locale` | The IDE's UI language as a BCP 47 tag (`en`, `fr`, `zh-CN`); no capability. See _Translations_. | +| `host::log(level, msg)` | `log` | IDE log, tagged with the plugin id. `eprintln!` output is logged too and shown when the plugin crashes. | +| `Project::find_files(glob, limit)` | `workspace.project.find-files` | Project-relative glob (`**/*Mapper.xml`); honours `.gitignore`; at most `limit` paths. | +| `Project::symbols(query, limit)` | `workspace.symbols` | New in 1.3; `project.read`. Fuzzy in-memory search (no LSP): name, camelCase kind, container and UTF-16 location. Queries ≤ 256 UTF-8 bytes; limits capped at 1000. Snapshot notes below. | +| `host::publish_diagnostics(path, items)` | `diagnostics.publish` | Replaces this plugin's problems for the file (editor squiggles and the Problems view); an empty list clears them. | +| `host::fetch(request)` → `{status, headers, body}` | `net.fetch` | See _Network_. | +| `Project::run_process(program, args, stdin)` → `{code, stdout, stderr}` | `process.run` | Only the pinned program of a `process:` grant; runs in the project root of a trusted project; 4 MiB of output; killed when the call is cancelled or times out. | +| `host::run_command(cmd, project, stdin)` → `{code, stdout, stderr}` | `process.run-command` | API 1.3: same limits as `run_process`, with append-only environment variables; needs the pinned `process:<program>` grant. | +| `host::start(cmd, project)` → `Child` | `process.start` | API 1.3: `poll(max_bytes)`, `write(text)`, `close_stdin()`, `wait(timeout_ms)`, `kill()`; at most 8 handles; dropping one kills its process. | +| `host::refresh_view(view)` | `views.refresh` | The view (or custom editors) render again; call it when the content changed. | +| `host::reveal_view(view)` | `views.reveal` | Brings one of your declared `[[contributes.views]]` to the front in the calling window. | +| `host::post_view_message(view, text)` | `views.post-message` | To the script of the view's `html` body. | +| `host::open_terminal(title, program, args)` | `views.open-terminal` | A terminal tab in the invoking window running the approved `process:<program>` in the project root: output that keeps coming, interactive sessions. | +| `host::open_location(path, line, column)` | `views.open-location` | Opens a file inside the project in an editor of the invoking window, the caret at `line`/`column` (0-based, UTF-16): a view's links to code. Needs `project.read`. | +| `host::setting(key)`, `setting_bool`, `setting_string`, `setting_number` | `settings.get` | The user's value (project over global) or the schema's default. | `Project::symbols` reads the current in-memory index: results may be partial while indexing, and locations can lag unsaved edits. Normal saves and filesystem @@ -507,15 +515,18 @@ from another feature, or nothing when run from Search Everywhere / a shortcut. ` ### Events -| Kind | Capability | Delivered | -| ------------------ | -------------- | ------------------------------------------------------------------------- | -| `file-opened` | `events` | a file opens in an editor | -| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) | -| `file-saved` | `events` | after the file is written | -| `editor-focused` | `events` | the focused editor changes (path, or none) | -| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) | -| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut | -| `scheduled` | — | the `on-schedule` period elapsed | +| Kind | Capability | Delivered | +| -------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `file-opened` | `events` | a file opens in an editor | +| `file-closed` | `events` | API 1.4, `Event::Other`: JSON path string | +| `settings-changed` | `events` | API 1.4, `Event::Other`: JSON array of this plugin's changed setting keys (effective values) | +| `input-mode-changed` | `events.input` | API 1.4, `Event::Other`: JSON `{path, mode, sub}` on focused Vim mode changes; `ctx.editor()` includes the document and current selections | +| `files-changed` | `events` | debounced created, modified and removed paths in open projects (API 1.3) | +| `file-saved` | `events` | after the file is written | +| `editor-focused` | `events` | the focused editor changes (path, or none) | +| `vcs-changed` | `events` | a repository's state changed (commit, checkout, fetch…; its root) | +| `action-performed` | `events.input` | an IDE action ran: id, title, source (keyboard, menu, toolbar…), shortcut | +| `scheduled` | — | the `on-schedule` period elapsed | Events are batched: a running plugin gets them within a fraction of a second, an idle one collects them for 2 s before it is woken, so frequent events @@ -807,10 +818,19 @@ scrolling. Labels are cut at 256 bytes and tooltips at 1 KiB. ### Network and secrets -`host::fetch` makes an HTTPS request (plain HTTP only to `localhost`) to a host -the plugin was granted with `net:<host>`; redirects to another host are -refused and responses are limited to 8 MiB. Requests are made from the -machine the project is on. +`host::fetch` requires `net:<host>` for HTTPS and loopback HTTP. API 1.4 adds +`net.http:<host>` for unencrypted HTTP to other hosts; it does not imply an +HTTPS grant. Both use the same wildcard rules. Each redirect is checked before +connecting to the destination; HTTPS → HTTP also requires `net.http:<host>`, +even on loopback. Responses are limited to 8 MiB. Requests run on the project +machine. A manifest using `net.http:` or `ipc:` declares `engines.openidea = "^1.4"`. + +`ipc:<path>` grants a local byte stream: an absolute Unix socket path (the host +expands `~/`, `$TMPDIR/` and `$XDG_RUNTIME_DIR/`) or `\\.\pipe\<name>` on Windows. +Only a grant's last path segment may contain `*`, for example +`ipc:$TMPDIR/discord-ipc-*`. It never grants TCP. A remote project's connection +runs on the server. Reads and writes honor cancellation and the call budget; +reads return empty bytes on timeout or EOF, and each operation is capped at 1 MiB. Secrets declared under `[[contributes.secrets]]` are entered by the user in Settings › Plugins and kept in the system keychain. The plugin never reads @@ -818,6 +838,27 @@ them: it writes `{{secret:<name>}}` in a request header and the host fills it in on the way out (`secrets` capability). `host::secret_is_set(name)` tells whether the user has entered one. +API 1.4 can also store or delete declared secrets with `host::secret_set` and +`host::secret_delete`; the plugin still cannot read them. An OAuth flow uses +`begin_loopback("oauth/callback")`, `ui.open-url` with its `redirect_uri()`, +`wait`, an authorized `net.fetch` code exchange and `secrets.set` for the token. +The listener binds only `127.0.0.1` on a random port on the **desktop**, including +for remote projects, serves "You can close this tab", then closes. There are +no OS URI callbacks or `on-uri` activation. Validate OAuth state in the plugin. + +Window status overrides, command execution, loopback creation/waiting and +output reveal are valid only in a command or event from a window. The Vim +context key `vim.mode` is `normal`, `insert`, `visual` or `replace`, and empty +when Vim is disabled. Subscribing to the three new event kinds, including +`on-event:<kind>` activation, requires `engines.openidea = "^1.4"`. + +Settings › Plugins lets the user choose the executable of a `process:<name>` +grant globally or for the current project. The native chooser's selection is +approved again and pinned by path and content hash. Project choices override +the global choice for runs, process handles, terminals and log panes. Resetting +a choice verifies its fallback, or revokes the grant if that is unavailable. +The plugin continues to call its declared program name. + ### Views and custom editors A view is data: a toolbar, a body — `Tree`, `List`, `Form`, `Table`, @@ -1753,7 +1794,7 @@ the API itself follows _Evolving the plugin API_ below. ## 10. Evolving the plugin API Released versions are frozen: 1.0.0 shipped with OpenIDEA 0.1.36, 1.1.0 -with 0.1.37 and 1.2.0 with 0.1.38. wasmtime decides what stays compatible: it resolves interface names +with 0.1.37, 1.2.0 with 0.1.38 and 1.3.0 with 0.1.39. wasmtime decides what stays compatible: it resolves interface names by semver (a component importing `openidea:plugin/x@1.0.0` links against a host defining `@1.1.0`, and the host finds its exports the same way), but function types must match exactly — a record with another field count, or a diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 90c83adc3..22ac34439 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index 12a94dd9e..8e8878878 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -7dfbea1faeae8930b462fe80d431c83c49aeafa45ac7acd36f7d7f05fac3aaa4 +8a1b87e6985c9bff6f034b56c4d4bf967a96f7579d5aff79213e631a95722408 diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index 35b84c97c..36c90091f 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index e3440fcf3..33cbdbb67 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -adeef6ba69276d3ac8e9ba349ca6e787befa6532ccac69bc35a381c0428af189 +1b68413078837975701fd58850a7f5dc1960de2ccc8e7f20effa57c2ca595eaf diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index c0e3c433e..75da43a5e 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index 66190f363..e35cd84a0 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -51def3be1a570ee61cb23f0b738002427298dbdafffcb687896531685bbe3c77 +2282cc3959e7b3576714d5dad611b51c404143ffbdadba809d0e3bc2d2afad29 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index 3fde3ebc0..d804afdda 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index 390cff508..16d429c9c 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -6c4439b36b22289c8dc54498d6e7e72a4c4cc15eac1a4957fc2b71d4fbd3c330 +eeb7ccd4b23564f1bb61edd50c4e3c50e445a028a0b4f90371b16b39bd1a40b4 diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index eb2f4ce88..1d19283ce 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index 7df840afa..0c7552410 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -00d56f431ab8e59c04796cf56054a98ba78040a5e4142c3f727725c31781a008 +15d35ef3cbc8b81a16f66d645f6f4c8d20ccda9bbff911ca1548866d77d7b9a4 diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 8526a5f22..8bbb02c9c 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 3d0ab2bcf..d5c4dacff 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -9fca272eec5a601b8de6071aa358954e9b79db08f45714f077624418e8f616bc +418d6e2b7725cc1099997febd78705f27b2b1739121e98a3db4fe43ae3c21b02 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index 57a9de496..e0d41b9b2 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index 60a829496..9c891801e 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -5adfc0d749feabe5fe7e20857fd636d01341b91f3dd8440779af6dcd14435619 +f280966be4b29a792d1494bfbac1695b750895ded1011ba1a4b9501981b73997 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index 97883f1e2..11534517b 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index bcefdb21e..8301808a2 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -1b388c40cb6be29c5e10e938c0c8f6848d10cb4bf1f7438db37f53b13314708e +db4087cf4c2265c78508949d167d0c3e8b5c0b9434000101d201d12196bed3f1 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index 6974f2cff..ee16b4807 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index fd050c58b..972f7afa9 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -af4478864196b5802f505d26beafe4492bc1335536311bc873b9d18773f9eebb +85653ef957f5e0483889ea750e486c79fe7e6630fee65ff2aa2e187abbcf7964 diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index f73c4c5d5..f6b2b7b71 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index b414f0c96..5a0dd34c5 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -46ce9f2d5b4f87a4be26facea4870f3de59952dc95c536fcf33fb0ff0a7c27a7 +b488971480de36f755c1ed0e0d496ac356e24dae34ccf7b487468bf6688ab36a diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index e9871c762..7a51dcb0e 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index 2d44ef4df..d81f8708f 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -f4e37cdac925f376bac945d5bb86c648b559787aa22737e6440835456f9f74cf +a85560746a3ae5032ed463c3352ac6e8170b944dd896e16416e1a4c07ac35a59 diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 0fe71b92b..680fc3875 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -91,6 +91,37 @@ mod imp { wit::ui::set_status_item(id, &item) } + pub fn set_window_status_item(id: &str, item: &StatusItem) -> Result<(), Error> { + wit::ui::set_window_status_item( + id, + &wit::ui::StatusItem { + text: item.text.clone(), + tooltip: item.tooltip.clone(), + command: item.command.clone(), + }, + ) + .map_err(error) + } + pub fn remove_window_status_item(id: &str) -> Result<(), Error> { + wit::ui::remove_window_status_item(id).map_err(error) + } + pub fn execute_command(id: &str, arg: Option<&str>) -> Result<Option<String>, Error> { + wit::command_runner::execute(id, arg).map_err(error) + } + pub type ConnectionRes = wit::ipc::Connection; + pub fn ipc_connect(name: &str) -> Result<ConnectionRes, Error> { + wit::ipc::connect(name).map_err(error) + } + pub fn ipc_write(c: &ConnectionRes, bytes: &[u8]) -> Result<(), Error> { + c.write(bytes).map_err(error) + } + pub fn ipc_read(c: &ConnectionRes, max: u32, timeout: u32) -> Result<Vec<u8>, Error> { + c.read(max, timeout).map_err(error) + } + pub fn ipc_close(c: &ConnectionRes) -> Result<(), Error> { + c.close().map_err(error) + } + pub fn remove_status_item(id: &str) { wit::ui::remove_status_item(id) } @@ -435,6 +466,31 @@ mod imp { .map_err(error) } + pub fn secret_set(name: &str, value: &str) -> Result<(), Error> { + wit::secrets::set(name, value).map_err(error) + } + pub fn secret_delete(name: &str) -> Result<(), Error> { + wit::secrets::delete(name).map_err(error) + } + pub type LoopbackRes = wit::auth::Loopback; + pub fn begin_loopback(path: &str) -> Result<LoopbackRes, Error> { + wit::auth::begin_loopback(path).map_err(error) + } + pub fn loopback_uri(l: &LoopbackRes) -> String { + l.redirect_uri() + } + pub fn loopback_wait(l: &LoopbackRes, timeout_ms: u32) -> Result<Option<String>, Error> { + l.wait(timeout_ms).map_err(error) + } + pub fn output_append(channel: &str, text: &str) -> Result<(), Error> { + wit::output::append(channel, text).map_err(error) + } + pub fn output_clear(channel: &str) -> Result<(), Error> { + wit::output::clear(channel).map_err(error) + } + pub fn output_reveal(channel: &str) -> Result<(), Error> { + wit::output::reveal(channel).map_err(error) + } pub fn secret_is_set(name: &str) -> bool { wit::secrets::is_set(name) } @@ -684,8 +740,8 @@ pub fn publish_diagnostics(path: &str, items: &[Diagnostic]) -> Result<(), Error imp::publish_diagnostics(path, items) } -/// HTTP(S) to a host granted with `net:<host>` (plain http only to -/// localhost). `{{secret:<name>}}` in a header is filled in by the IDE (needs +/// HTTPS with `net:<host>`; unencrypted HTTP with `net.http:<host>` +/// (loopback HTTP retains `net:<host>`). `{{secret:<name>}}` in a header is filled in by the IDE (needs /// `secrets`). `Error::Cancelled` when the call was superseded. pub fn fetch(request: &HttpRequest) -> Result<HttpResponse, Error> { imp::fetch(request) @@ -1177,3 +1233,81 @@ pub fn notify_with_actions( pub fn __diagnostic_to(d: &Diagnostic) -> crate::bindings::openidea::plugin::diagnostics::Diagnostic { imp::diagnostic_to(d) } + +/// Overrides an item in the invoking window, until removed or the window/plugin closes. +pub fn set_window_status_item(id: &str, item: &StatusItem) -> Result<(), Error> { + imp::set_window_status_item(id, item) +} +/// Removes this window's status override, exposing the global item. +pub fn remove_window_status_item(id: &str) -> Result<(), Error> { + imp::remove_window_status_item(id) +} + +/// An approved byte stream on the project machine (the server in remote projects). +pub struct Connection { + inner: imp::ConnectionRes, +} +impl Connection { + /// Writes at most 1 MiB. + pub fn write(&self, bytes: &[u8]) -> Result<(), Error> { + imp::ipc_write(&self.inner, bytes) + } + /// Reads up to 1 MiB; empty on timeout or EOF. + pub fn read(&self, max_bytes: u32, timeout_ms: u32) -> Result<Vec<u8>, Error> { + imp::ipc_read(&self.inner, max_bytes, timeout_ms) + } + /// Closes this stream. Dropping it also closes it. + pub fn close(&self) -> Result<(), Error> { + imp::ipc_close(&self.inner) + } +} +/// Connects to a granted absolute socket path or Windows named pipe (API 1.4). +pub fn ipc_connect(name: &str) -> Result<Connection, Error> { + imp::ipc_connect(name).map(|inner| Connection { inner }) +} + +/// Executes a stable action or another plugin's command in the invoking window. +/// IDE actions return `None`; plugin commands return their result (API 1.4). +pub fn execute_command(id: &str, arg: Option<&str>) -> Result<Option<String>, Error> { + imp::execute_command(id, arg) +} + +/// Stores a declared secret in the desktop keychain; requires `secrets`. +pub fn secret_set(name: &str, value: &str) -> Result<(), Error> { + imp::secret_set(name, value) +} +/// Deletes a declared secret; requires `secrets`. +pub fn secret_delete(name: &str) -> Result<(), Error> { + imp::secret_delete(name) +} +/// A one-shot browser redirect on the desktop, including for remote projects. +pub struct Loopback { + inner: imp::LoopbackRes, +} +impl Loopback { + /// The authorization flow's loopback redirect URI. + pub fn redirect_uri(&self) -> String { + imp::loopback_uri(&self.inner) + } + /// Awaits the raw query string; `None` on timeout. Waiting excludes the call budget. + pub fn wait(&self, timeout_ms: u32) -> Result<Option<String>, Error> { + imp::loopback_wait(&self.inner, timeout_ms) + } +} +/// Begins an OAuth redirect listener in the invoking window (no capability). +pub fn begin_loopback(path: &str) -> Result<Loopback, Error> { + imp::begin_loopback(path).map(|inner| Loopback { inner }) +} + +/// Appends to a plugin-owned Output tab's 1 MiB ring buffer. +pub fn output_append(channel: &str, text: &str) -> Result<(), Error> { + imp::output_append(channel, text) +} +/// Clears a plugin-owned output channel. +pub fn output_clear(channel: &str) -> Result<(), Error> { + imp::output_clear(channel) +} +/// Reveals a read-only Output tab in the invoking window. +pub fn output_reveal(channel: &str) -> Result<(), Error> { + imp::output_reveal(channel) +} diff --git a/sdk/rust/openidea-plugin/src/lib.rs b/sdk/rust/openidea-plugin/src/lib.rs index 8518a3a4c..9888b85ef 100644 --- a/sdk/rust/openidea-plugin/src/lib.rs +++ b/sdk/rust/openidea-plugin/src/lib.rs @@ -98,7 +98,7 @@ pub mod providers_bindings { export_macro_name: "__export_editor_providers_world", default_bindings_module: "openidea_plugin::providers_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, }, }); } @@ -115,10 +115,10 @@ pub mod views_bindings { export_macro_name: "__export_views_world", default_bindings_module: "openidea_plugin::views_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, - "openidea:plugin/workspace@1.3.0": crate::bindings::openidea::plugin::workspace, - "openidea:plugin/editor@1.3.0": crate::bindings::openidea::plugin::editor, - "openidea:plugin/invocation@1.3.0": crate::bindings::openidea::plugin::invocation, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/workspace@1.4.0": crate::bindings::openidea::plugin::workspace, + "openidea:plugin/editor@1.4.0": crate::bindings::openidea::plugin::editor, + "openidea:plugin/invocation@1.4.0": crate::bindings::openidea::plugin::invocation, }, }); } @@ -130,7 +130,7 @@ pub mod indexing_bindings { world: "indexing", path: "wit", pub_export_macro: true, export_macro_name: "__export_indexing_world", default_bindings_module: "openidea_plugin::indexing_bindings", - with: { "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types }, + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, }); } @@ -142,10 +142,10 @@ pub mod details_bindings { export_macro_name: "__export_details_world", default_bindings_module: "openidea_plugin::details_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, - "openidea:plugin/workspace@1.3.0": crate::bindings::openidea::plugin::workspace, - "openidea:plugin/editor@1.3.0": crate::bindings::openidea::plugin::editor, - "openidea:plugin/invocation@1.3.0": crate::bindings::openidea::plugin::invocation, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/workspace@1.4.0": crate::bindings::openidea::plugin::workspace, + "openidea:plugin/editor@1.4.0": crate::bindings::openidea::plugin::editor, + "openidea:plugin/invocation@1.4.0": crate::bindings::openidea::plugin::invocation, }, }); } @@ -157,7 +157,7 @@ pub mod semantic_bindings { world: "semantic-tokens", path: "wit", pub_export_macro: true, export_macro_name: "__export_semantic_tokens_world", default_bindings_module: "openidea_plugin::semantic_bindings", - with: { "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types }, + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, }); } @@ -169,8 +169,8 @@ pub mod diagnostics_bindings { export_macro_name: "__export_diagnostics_world", default_bindings_module: "openidea_plugin::diagnostics_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, - "openidea:plugin/diagnostics@1.3.0": crate::bindings::openidea::plugin::diagnostics, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/diagnostics@1.4.0": crate::bindings::openidea::plugin::diagnostics, }, }); } @@ -182,7 +182,7 @@ pub mod hover_bindings { world: "hover", path: "wit", pub_export_macro: true, export_macro_name: "__export_hover_world", default_bindings_module: "openidea_plugin::hover_bindings", - with: { "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types }, + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, }); } @@ -194,11 +194,11 @@ pub mod commit_checks_bindings { export_macro_name: "__export_commit_checks_world", default_bindings_module: "openidea_plugin::commit_checks_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, - "openidea:plugin/workspace@1.3.0": crate::bindings::openidea::plugin::workspace, - "openidea:plugin/editor@1.3.0": crate::bindings::openidea::plugin::editor, - "openidea:plugin/invocation@1.3.0": crate::bindings::openidea::plugin::invocation, - "openidea:plugin/commit@1.3.0": crate::bindings::openidea::plugin::commit, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/workspace@1.4.0": crate::bindings::openidea::plugin::workspace, + "openidea:plugin/editor@1.4.0": crate::bindings::openidea::plugin::editor, + "openidea:plugin/invocation@1.4.0": crate::bindings::openidea::plugin::invocation, + "openidea:plugin/commit@1.4.0": crate::bindings::openidea::plugin::commit, }, }); } @@ -210,7 +210,7 @@ pub mod inlay_bindings { world: "inlay-hints", path: "wit", pub_export_macro: true, export_macro_name: "__export_inlay_hints_world", default_bindings_module: "openidea_plugin::inlay_bindings", - with: { "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types }, + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, }); } @@ -221,7 +221,7 @@ pub mod file_actions_bindings { world: "file-actions-provider", path: "wit", pub_export_macro: true, export_macro_name: "__export_file_actions_world", default_bindings_module: "openidea_plugin::file_actions_bindings", - with: { "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types }, + with: { "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types }, }); } @@ -233,10 +233,10 @@ pub mod endpoints_bindings { export_macro_name: "__export_endpoints_world", default_bindings_module: "openidea_plugin::endpoints_bindings", with: { - "openidea:plugin/types@1.3.0": crate::bindings::openidea::plugin::types, - "openidea:plugin/workspace@1.3.0": crate::bindings::openidea::plugin::workspace, - "openidea:plugin/editor@1.3.0": crate::bindings::openidea::plugin::editor, - "openidea:plugin/invocation@1.3.0": crate::bindings::openidea::plugin::invocation, + "openidea:plugin/types@1.4.0": crate::bindings::openidea::plugin::types, + "openidea:plugin/workspace@1.4.0": crate::bindings::openidea::plugin::workspace, + "openidea:plugin/editor@1.4.0": crate::bindings::openidea::plugin::editor, + "openidea:plugin/invocation@1.4.0": crate::bindings::openidea::plugin::invocation, }, }); } diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index 46edd3292..c9067e906 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -36,6 +36,8 @@ pub struct MockTask { pub ended: bool, } +type CommandHandler = dyn Fn(Option<&str>) -> Result<Option<String>, Error>; + type NetHandler = Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Error>>; type ProcessHandler = Box<dyn Fn(&[String], Option<&str>) -> Result<ProcessOutput, Error>>; @@ -94,6 +96,13 @@ struct State { action_notifications: Vec<ActionNotification>, logs: Vec<(LogLevel, String)>, status: BTreeMap<String, StatusItem>, + window_status: BTreeMap<String, StatusItem>, + ipc: BTreeMap<u64, VecDeque<u8>>, + next_ipc: u64, + loopbacks: BTreeSet<u64>, + next_loopback: u64, + output: BTreeMap<String, String>, + revealed_output: Vec<String>, context: BTreeMap<String, ContextValue>, storage: BTreeMap<String, String>, subscriptions: BTreeSet<EventKind>, @@ -112,6 +121,10 @@ struct State { diagnostics: BTreeMap<String, Vec<Diagnostic>>, provider_diagnostics: BTreeMap<String, Vec<Diagnostic>>, secrets: BTreeMap<String, String>, + declared_secrets: BTreeSet<String>, + commands: BTreeMap<String, Rc<CommandHandler>>, + command_depth: usize, + loopback_queries: VecDeque<Option<String>>, net: Option<NetHandler>, requests: Vec<HttpRequest>, processes: BTreeMap<String, ProcessHandler>, @@ -274,7 +287,8 @@ impl MockHost { } pub fn status_items(&self) -> BTreeMap<String, StatusItem> { - self.state.borrow().status.clone() + let s = self.state.borrow(); + s.status.iter().chain(&s.window_status).map(|(k, v)| (k.clone(), v.clone())).collect() } pub fn context_keys(&self) -> BTreeMap<String, ContextValue> { @@ -431,8 +445,27 @@ impl MockHost { self.state.borrow_mut().locale = Some(tag.into()); } + /// Registers the result of a stable action or plugin command. + pub fn on_command(&self, id: &str, handler: impl Fn(Option<&str>) -> Result<Option<String>, Error> + 'static) { + self.state.borrow_mut().commands.insert(id.into(), Rc::new(handler)); + } + /// Queues the raw browser query returned by the next loopback wait. + pub fn queue_loopback_query(&self, query: Option<&str>) { + self.state.borrow_mut().loopback_queries.push_back(query.map(str::to_owned)); + } + + /// Declares a secret the plugin is allowed to store (the mock has no manifest). + pub fn declare_secret(&self, name: &str) { + self.state.borrow_mut().declared_secrets.insert(name.into()); + } + /// The plugin's read-only output buffers. + pub fn output(&self) -> BTreeMap<String, String> { + self.state.borrow().output.clone() + } + /// A secret the user stored. pub fn set_secret(&self, name: &str, value: &str) { + self.state.borrow_mut().declared_secrets.insert(name.into()); self.state.borrow_mut().secrets.insert(name.into(), value.into()); } @@ -663,6 +696,82 @@ pub mod current { with(|s| s.status.insert(id.to_owned(), item.clone())); } + pub fn set_window_status_item(id: &str, item: &StatusItem) -> Result<(), Error> { + with(|s| { + s.window_status.insert(id.into(), item.clone()); + }); + Ok(()) + } + pub fn remove_window_status_item(id: &str) -> Result<(), Error> { + with(|s| { + s.window_status.remove(id); + }); + Ok(()) + } + pub fn execute_command(id: &str, arg: Option<&str>) -> Result<Option<String>, Error> { + let handler = with(|s| { + if s.command_depth >= 8 { + return Err(Error::Invalid("command nesting limit (8)".into())); + } + let handler = s.commands.get(id).cloned().ok_or_else(|| Error::NotFound(id.into()))?; + s.command_depth += 1; + Ok(handler) + })?; + let result = handler(arg); + with(|s| s.command_depth -= 1); + result + } + pub struct ConnectionRes { + id: u64, + owner: Rc<RefCell<State>>, + } + impl Drop for ConnectionRes { + fn drop(&mut self) { + self.owner.borrow_mut().ipc.remove(&self.id); + } + } + pub fn ipc_connect(name: &str) -> Result<ConnectionRes, Error> { + with(|s| { + let cap = format!("ipc:{name}"); + let granted = s.capabilities.iter().any(|g| { + g == &cap + || g.strip_prefix("ipc:").is_some_and(|pattern| { + let Some((base, tail)) = pattern.rsplit_once('/') else { return false }; + let Some((parent, file)) = name.rsplit_once('/') else { return false }; + base == parent && tail.strip_suffix('*').is_some_and(|prefix| file.starts_with(prefix)) + }) + }); + if !granted { + return Err(Error::Denied(cap)); + } + if s.ipc.len() >= 8 { + return Err(Error::Invalid("at most eight IPC connections".into())); + } + s.next_ipc += 1; + s.ipc.insert(s.next_ipc, VecDeque::new()); + let owner = CURRENT.with(|c| c.borrow().as_ref().unwrap().clone()); + Ok(ConnectionRes { id: s.next_ipc, owner }) + }) + } + pub fn ipc_write(c: &ConnectionRes, bytes: &[u8]) -> Result<(), Error> { + if bytes.len() > 1 << 20 { + return Err(Error::Invalid("at most 1 MiB".into())); + } + let mut s = c.owner.borrow_mut(); + let data = s.ipc.get_mut(&c.id).ok_or_else(|| Error::NotFound("connection".into()))?; + data.extend(bytes); + Ok(()) + } + pub fn ipc_read(c: &ConnectionRes, max: u32, _timeout: u32) -> Result<Vec<u8>, Error> { + let mut s = c.owner.borrow_mut(); + let data = s.ipc.get_mut(&c.id).ok_or_else(|| Error::NotFound("connection".into()))?; + let count = data.len().min(max as usize).min(1 << 20); + Ok(data.drain(..count).collect()) + } + pub fn ipc_close(c: &ConnectionRes) -> Result<(), Error> { + c.owner.borrow_mut().ipc.remove(&c.id); + Ok(()) + } pub fn remove_status_item(id: &str) { with(|s| s.status.remove(id)); } @@ -1181,7 +1290,7 @@ pub mod current { pub fn subscribe(kind: EventKind) -> Result<(), Error> { with(|s| { let cap = match kind { - EventKind::ActionPerformed => Some("events.input"), + EventKind::ActionPerformed | EventKind::InputModeChanged => Some("events.input"), EventKind::Scheduled => None, _ => Some("events"), }; @@ -1242,8 +1351,18 @@ pub mod current { pub fn fetch(req: &HttpRequest) -> Result<HttpResponse, Error> { with(|s| { let host = net_host(&req.url).ok_or_else(|| Error::Invalid(format!("{:?} is not a URL", req.url)))?; - let cap = format!("net:{host}"); - if !s.capabilities.iter().any(|c| *c == cap || c == "net:*") { + let kind = if req.url.starts_with("http://") && !matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1") + { + "net.http" + } else { + "net" + }; + let cap = format!("{kind}:{host}"); + if !s.capabilities.iter().any(|c| { + *c == cap + || c == &format!("{kind}:*") + || c.strip_prefix(&format!("{kind}:*.")).is_some_and(|suffix| host.ends_with(&format!(".{suffix}"))) + }) { return Err(Error::Denied(cap)); } let mut sent = req.clone(); @@ -1265,6 +1384,87 @@ pub mod current { }) } + pub fn secret_set(name: &str, value: &str) -> Result<(), Error> { + with(|s| { + require(s, "secrets")?; + if !s.declared_secrets.contains(name) { + return Err(Error::NotFound(name.into())); + } + s.secrets.insert(name.into(), value.into()); + Ok(()) + }) + } + pub fn secret_delete(name: &str) -> Result<(), Error> { + with(|s| { + require(s, "secrets")?; + if !s.declared_secrets.contains(name) { + return Err(Error::NotFound(name.into())); + } + s.secrets.remove(name); + Ok(()) + }) + } + pub struct LoopbackRes { + id: u64, + owner: Rc<RefCell<State>>, + uri: String, + } + impl Drop for LoopbackRes { + fn drop(&mut self) { + self.owner.borrow_mut().loopbacks.remove(&self.id); + } + } + pub fn begin_loopback(path: &str) -> Result<LoopbackRes, Error> { + with(|s| { + if s.loopbacks.len() >= 2 { + return Err(Error::Invalid("at most two loopbacks".into())); + } + s.next_loopback += 1; + s.loopbacks.insert(s.next_loopback); + Ok(LoopbackRes { + id: s.next_loopback, + owner: CURRENT.with(|c| c.borrow().as_ref().unwrap().clone()), + uri: format!("http://127.0.0.1:{}/{}", 49152 + s.next_loopback, path.trim_start_matches('/')), + }) + }) + } + pub fn loopback_uri(l: &LoopbackRes) -> String { + l.uri.clone() + } + pub fn loopback_wait(l: &LoopbackRes, _timeout_ms: u32) -> Result<Option<String>, Error> { + if !l.owner.borrow_mut().loopbacks.remove(&l.id) { + return Err(Error::Invalid("loopback already awaited".into())); + } + Ok(l.owner.borrow_mut().loopback_queries.pop_front().flatten()) + } + pub fn output_append(channel: &str, text: &str) -> Result<(), Error> { + with(|s| { + if channel.is_empty() || channel.len() > 128 || channel.chars().any(char::is_control) { + return Err(Error::Invalid("invalid channel".into())); + } + if !s.output.contains_key(channel) && s.output.len() >= 32 { + return Err(Error::Invalid("at most 32 channels".into())); + } + let buffer = s.output.entry(channel.into()).or_default(); + buffer.push_str(text); + let mut remove = buffer.len().saturating_sub(1 << 20); + while !buffer.is_char_boundary(remove) { + remove += 1; + } + buffer.drain(..remove); + Ok(()) + }) + } + pub fn output_clear(channel: &str) -> Result<(), Error> { + output_append(channel, "")?; + with(|s| s.output.get_mut(channel).unwrap().clear()); + Ok(()) + } + pub fn output_reveal(channel: &str) -> Result<(), Error> { + output_append(channel, "")?; + with(|s| s.revealed_output.push(channel.into())); + Ok(()) + } pub fn secret_is_set(name: &str) -> bool { with(|s| s.capabilities.iter().any(|c| c == "secrets") && s.secrets.contains_key(name)) } diff --git a/sdk/rust/openidea-plugin/src/types.rs b/sdk/rust/openidea-plugin/src/types.rs index 1168f7519..7d59cdaec 100644 --- a/sdk/rust/openidea-plugin/src/types.rs +++ b/sdk/rust/openidea-plugin/src/types.rs @@ -211,6 +211,9 @@ impl From<String> for ContextValue { #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum EventKind { + FileClosed, + SettingsChanged, + InputModeChanged, FileOpened, FileSaved, FilesChanged, @@ -225,6 +228,9 @@ impl EventKind { /// The name the IDE knows it by. pub fn name(self) -> &'static str { match self { + Self::FileClosed => "file-closed", + Self::SettingsChanged => "settings-changed", + Self::InputModeChanged => "input-mode-changed", Self::FileOpened => "file-opened", Self::FileSaved => "file-saved", Self::FilesChanged => "files-changed", diff --git a/sdk/rust/openidea-plugin/tests/api14.rs b/sdk/rust/openidea-plugin/tests/api14.rs new file mode 100644 index 000000000..26e485a3c --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api14.rs @@ -0,0 +1,62 @@ +use openidea_plugin::{Error, HttpRequest, StatusItem, host, mock::MockHost}; + +#[test] +fn ipc_is_granted_bounded_and_closed_on_drop() { + let mock = MockHost::install().with_capabilities(&[]); + assert!(matches!(host::ipc_connect("/tmp/test-1"), Err(Error::Denied(_)))); + let _mock = mock.with_capabilities(&["ipc:/tmp/test-*"]); + let connection = host::ipc_connect("/tmp/test-1").unwrap(); + connection.write(b"echo").unwrap(); + assert_eq!(connection.read(4, 100).unwrap(), b"echo"); + let others: Vec<_> = (0..7).map(|_| host::ipc_connect("/tmp/test-2").unwrap()).collect(); + assert!(matches!(host::ipc_connect("/tmp/test-3"), Err(Error::Invalid(_)))); + connection.close().unwrap(); + assert!(connection.read(4, 0).is_err()); + host::ipc_connect("/tmp/test-3").unwrap(); + drop(others); +} + +#[test] +fn http_requires_its_own_grant_and_secrets_are_declaration_scoped() { + let mock = MockHost::install().with_capabilities(&["net:*.example.com", "secrets"]); + assert!( + matches!(host::fetch(&HttpRequest::get("http://api.example.com/")), Err(Error::Denied(c)) if c == "net.http:api.example.com") + ); + assert!(matches!(host::secret_set("token", "value"), Err(Error::NotFound(_)))); + mock.declare_secret("token"); + host::secret_set("token", "value").unwrap(); + assert!(host::secret_is_set("token")); + host::secret_delete("token").unwrap(); + assert!(!host::secret_is_set("token")); +} + +#[test] +fn scoped_status_commands_output_and_loopbacks_are_available_in_the_sdk() { + let mock = MockHost::install(); + let item = |text: &str| StatusItem { text: text.into(), tooltip: None, command: None }; + host::set_status_item("state", &item("global")); + host::set_window_status_item("state", &item("window")).unwrap(); + host::set_status_item("state", &item("updated")); + assert_eq!(mock.status_items()["state"].text, "window"); + host::remove_window_status_item("state").unwrap(); + assert_eq!(mock.status_items()["state"].text, "updated"); + mock.on_command("other.command", |arg| Ok(arg.map(str::to_owned))); + assert_eq!(host::execute_command("other.command", Some("result")).unwrap(), Some("result".into())); + assert!(matches!(host::execute_command("missing", None), Err(Error::NotFound(_)))); + mock.on_command("recursive", |_| host::execute_command("recursive", None)); + assert!(matches!(host::execute_command("recursive", None), Err(Error::Invalid(_)))); + host::output_append("build", &"😀".repeat(300_000)).unwrap(); + assert_eq!(mock.output()["build"].len(), 1 << 20); + host::output_clear("build").unwrap(); + assert!(mock.output()["build"].is_empty()); + host::output_reveal("build").unwrap(); + let listener = host::begin_loopback("callback").unwrap(); + assert!(listener.redirect_uri().starts_with("http://127.0.0.1:")); + let other = host::begin_loopback("second").unwrap(); + assert!(matches!(host::begin_loopback("third"), Err(Error::Invalid(_)))); + mock.queue_loopback_query(Some("code=a%2Bb&state=test")); + assert_eq!(listener.wait(100).unwrap().as_deref(), Some("code=a%2Bb&state=test")); + assert!(listener.wait(100).is_err()); + drop(other); + host::begin_loopback("third").unwrap(); +} diff --git a/sdk/rust/openidea-plugin/wit/commit.wit b/sdk/rust/openidea-plugin/wit/commit.wit index a70b889c1..91dbe0e28 100644 --- a/sdk/rust/openidea-plugin/wit/commit.wit +++ b/sdk/rust/openidea-plugin/wit/commit.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// The commit being prepared in the window the current command or event came /// from (the Commit tool window, or the Commit dialog while it is open): the diff --git a/sdk/rust/openidea-plugin/wit/details.wit b/sdk/rust/openidea-plugin/wit/details.wit index 9e889851a..f7342991d 100644 --- a/sdk/rust/openidea-plugin/wit/details.wit +++ b/sdk/rust/openidea-plugin/wit/details.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// What the pane beside the Services tree shows for a plugin's node. interface detail-types { diff --git a/sdk/rust/openidea-plugin/wit/diagnostics.wit b/sdk/rust/openidea-plugin/wit/diagnostics.wit index d5d62de72..499335fde 100644 --- a/sdk/rust/openidea-plugin/wit/diagnostics.wit +++ b/sdk/rust/openidea-plugin/wit/diagnostics.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-diagnostics`): problems in the current, /// possibly unsaved document, for the languages declared with the diff --git a/sdk/rust/openidea-plugin/wit/endpoints.wit b/sdk/rust/openidea-plugin/wit/endpoints.wit index 95302fcb0..f4a446fe0 100644 --- a/sdk/rust/openidea-plugin/wit/endpoints.wit +++ b/sdk/rust/openidea-plugin/wit/endpoints.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// HTTP endpoints found in a project (`[[contributes.endpoints]]`). interface endpoints-provider { diff --git a/sdk/rust/openidea-plugin/wit/events.wit b/sdk/rust/openidea-plugin/wit/events.wit index 8851d18a7..f52030971 100644 --- a/sdk/rust/openidea-plugin/wit/events.wit +++ b/sdk/rust/openidea-plugin/wit/events.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Workbench events, delivered in batches to `event-handler.handle`. interface events { @@ -29,6 +29,9 @@ interface events { /// Delivers `kind` events from now on, for the rest of the session (also /// across idle reclaim: an event activates the plugin again). Declare /// `activation = ["on-event:<kind>"]` to get them before first use. + /// API 1.4 also delivers `file-closed` (JSON path string), `settings-changed` + /// (JSON array of the plugin's changed setting keys), and `input-mode-changed` + /// (JSON {path, mode, sub}) through `other`. The last needs `events.input`. /// Kinds: `file-opened`, `file-saved`, `files-changed` (batched disk changes /// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor /// changed), `vcs-changed` (a repository's state changed: commit, diff --git a/sdk/rust/openidea-plugin/wit/exports.wit b/sdk/rust/openidea-plugin/wit/exports.wit index 67d7c6060..434b29ceb 100644 --- a/sdk/rust/openidea-plugin/wit/exports.wit +++ b/sdk/rust/openidea-plugin/wit/exports.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; interface lifecycle { use types.{context, error}; diff --git a/sdk/rust/openidea-plugin/wit/file-actions.wit b/sdk/rust/openidea-plugin/wit/file-actions.wit index 477809180..12b4aec17 100644 --- a/sdk/rust/openidea-plugin/wit/file-actions.wit +++ b/sdk/rust/openidea-plugin/wit/file-actions.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-file-actions`): quick fixes and /// refactorings that create, rename or delete files, next to the text edits diff --git a/sdk/rust/openidea-plugin/wit/fs.wit b/sdk/rust/openidea-plugin/wit/fs.wit index 7cd07fd71..c1a96cf83 100644 --- a/sdk/rust/openidea-plugin/wit/fs.wit +++ b/sdk/rust/openidea-plugin/wit/fs.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Files outside the open projects: the configuration of the program a /// plugin integrates with, a tool installed elsewhere, a licence file. diff --git a/sdk/rust/openidea-plugin/wit/host.wit b/sdk/rust/openidea-plugin/wit/host.wit index 91c3e12fc..d81877524 100644 --- a/sdk/rust/openidea-plugin/wit/host.wit +++ b/sdk/rust/openidea-plugin/wit/host.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Writes to the IDE log, tagged with the plugin id. interface log { @@ -53,6 +53,11 @@ interface ui { /// Shows or updates the plugin's status bar item `id` in every window. set-status-item: func(id: string, item: status-item); remove-status-item: func(id: string); + /// Overrides the global item in the invoking window only (API 1.4). + /// Invalid outside a command or event of a window; removed on window close or plugin stop. + set-window-status-item: func(id: string, item: status-item) -> result<_, error>; + /// Removes this window's override, falling back to the global item. + remove-window-status-item: func(id: string) -> result<_, error>; /// Sets the plugin's context key `key`, which `when` clauses test as /// `plugin.<id>.<key>`, in the window the current command or event came /// from (every window when there is none). A window's value takes @@ -104,3 +109,22 @@ interface storage { /// Keys starting with `prefix`, sorted. keys: func(prefix: string) -> result<list<string>, error>; } + +/// Executes stable IDE action ids or `plugin.<plugin-id>.<command-id>` (API 1.4). +interface command-runner { + use types.{error}; + /// Only in commands/events of a window. Returns a plugin command's value, + /// or none for IDE actions; unknown ids are not-found. Nested calls are bounded. + execute: func(id: string, arg: option<string>) -> result<option<string>, error>; +} + +/// Per-plugin named, read-only Output tabs (API 1.4), with a 1 MiB UTF-8 ring buffer. +interface output { + use types.{error}; + /// Appends text to a channel (at most 32 channels, names 1-128 bytes). + append: func(channel: string, text: string) -> result<_, error>; + /// Clears a channel's buffer. + clear: func(channel: string) -> result<_, error>; + /// Reveals the channel in the invoking window; only commands/events of a window. + reveal: func(channel: string) -> result<_, error>; +} diff --git a/sdk/rust/openidea-plugin/wit/hover.wit b/sdk/rust/openidea-plugin/wit/hover.wit index a95c22758..5ddde792e 100644 --- a/sdk/rust/openidea-plugin/wit/hover.wit +++ b/sdk/rust/openidea-plugin/wit/hover.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-hover`): Markdown added to the hover of /// documents of the languages declared with the `hover` provider kind, diff --git a/sdk/rust/openidea-plugin/wit/indexing.wit b/sdk/rust/openidea-plugin/wit/indexing.wit index 4ee08d64b..227aab726 100644 --- a/sdk/rust/openidea-plugin/wit/indexing.wit +++ b/sdk/rust/openidea-plugin/wit/indexing.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Cross-file associations a plugin publishes for the files it declares under /// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable diff --git a/sdk/rust/openidea-plugin/wit/inlay.wit b/sdk/rust/openidea-plugin/wit/inlay.wit index ab00b0c9b..1098869a5 100644 --- a/sdk/rust/openidea-plugin/wit/inlay.wit +++ b/sdk/rust/openidea-plugin/wit/inlay.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-inlay-hints`): inline hints in documents of /// the languages declared with the `inlay-hints` provider kind, including diff --git a/sdk/rust/openidea-plugin/wit/io.wit b/sdk/rust/openidea-plugin/wit/io.wit index cffd883be..2ebc7a889 100644 --- a/sdk/rust/openidea-plugin/wit/io.wit +++ b/sdk/rust/openidea-plugin/wit/io.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Problems in files, shown in the editor and the Problems view. interface diagnostics { @@ -35,7 +35,7 @@ interface diagnostics { publish: func(path: string, diagnostics: list<diagnostic>) -> result<_, error>; } -/// HTTP(S) to the hosts granted with `net:<host>`. +/// HTTPS with `net:<host>`; unencrypted HTTP with `net.http:<host>`. interface net { use types.{error}; @@ -46,7 +46,8 @@ interface net { record request { method: string, - /// `https://…`; plain `http://` only to `localhost` / `127.0.0.1`. + /// `https://…` requires `net:<host>`. Plain `http://…` requires + /// `net.http:<host>` (API 1.4), except loopback, which uses `net:<host>`. url: string, /// `{{secret:<name>}}` in a value is replaced by the plugin's secret /// `name` on the way out (requires `secrets`); the plugin never sees it. @@ -72,6 +73,11 @@ interface net { /// OS keychain). Plugins only use them through `{{secret:<name>}}` in /// `net` requests. Requires `secrets`. interface secrets { + use types.{error}; + /// Stores a declared secret without ever exposing it back to plugin code (API 1.4). + set: func(name: string, value: string) -> result<_, error>; + /// Deletes a declared secret (API 1.4). + delete: func(name: string) -> result<_, error>; is-set: func(name: string) -> bool; } @@ -144,3 +150,38 @@ interface process { /// also ends its processes. start: func(cmd: command, cwd: option<borrow<project>>) -> result<child, error>; } + +/// Local sockets on the project machine, including the server for remote projects. +/// Requires `ipc:<path>`; host-expanded `~/`, `$TMPDIR/`, `$XDG_RUNTIME_DIR/` +/// and Windows `\\.\pipe\name` are accepted. API 1.4. +interface ipc { + use types.{error}; + /// A byte stream. At most eight per plugin; dropping closes it, as does stopping the plugin. + resource connection { + /// Writes up to 1 MiB, subject to the current call's budget and cancellation. + write: func(bytes: list<u8>) -> result<_, error>; + /// Reads up to 1 MiB; empty on EOF or timeout. Zero timeout only checks. + read: func(max-bytes: u32, timeout-ms: u32) -> result<list<u8>, error>; + /// Closes the stream; subsequent reads and writes fail. + close: func() -> result<_, error>; + } + /// Connects to an absolute Unix socket or Windows named pipe; never TCP. + connect: func(name: string) -> result<connection, error>; +} + +/// OAuth browser redirects received on the desktop, even for remote projects (API 1.4). +/// No capability needed; only commands/events of a window may use this interface. +interface auth { + use types.{error}; + /// A one-shot IPv4 loopback listener. At most two open per plugin. + resource loopback { + /// `http://127.0.0.1:<random-port>/<path>` for the authorization URL. + redirect-uri: func() -> string; + /// Returns the first matching request's raw query string, or none on timeout. + /// Waiting is excluded from the call budget. The listener serves a short + /// completion page and closes; resource drop and plugin stop also close it. + wait: func(timeout-ms: u32) -> result<option<string>, error>; + } + /// Binds 127.0.0.1 only. `path` has no query or fragment. + begin-loopback: func(path: string) -> result<loopback, error>; +} diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index 8d1451ac3..acb2a8e7a 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -8,7 +8,7 @@ /// `fs` and `workspace`, and everything else goes through the imports below, /// gated by the capabilities granted in `plugin.toml` (a missing one returns /// `error::denied`). -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; world plugin { import log; @@ -26,6 +26,10 @@ world plugin { import net; import secrets; import process; + import ipc; + import output; + import auth; + import command-runner; import views; import settings; diff --git a/sdk/rust/openidea-plugin/wit/providers.wit b/sdk/rust/openidea-plugin/wit/providers.wit index 317eb81d1..8c0713ec6 100644 --- a/sdk/rust/openidea-plugin/wit/providers.wit +++ b/sdk/rust/openidea-plugin/wit/providers.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Editor features a plugin provides for the languages it declares under /// `[[contributes.providers]]` (the host calls only declared kinds). They run diff --git a/sdk/rust/openidea-plugin/wit/semantic.wit b/sdk/rust/openidea-plugin/wit/semantic.wit index ec89fe405..586c324e6 100644 --- a/sdk/rust/openidea-plugin/wit/semantic.wit +++ b/sdk/rust/openidea-plugin/wit/semantic.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-semantic-tokens`): semantic colouring of /// documents of the languages declared with the `semantic-tokens` provider diff --git a/sdk/rust/openidea-plugin/wit/types.wit b/sdk/rust/openidea-plugin/wit/types.wit index 8114a2db0..4192e783c 100644 --- a/sdk/rust/openidea-plugin/wit/types.wit +++ b/sdk/rust/openidea-plugin/wit/types.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Shared types. Positions are 0-based lines and UTF-16 code unit columns, /// as in the editor and LSP. diff --git a/sdk/rust/openidea-plugin/wit/views.wit b/sdk/rust/openidea-plugin/wit/views.wit index 78da35354..0f3b7d498 100644 --- a/sdk/rust/openidea-plugin/wit/views.wit +++ b/sdk/rust/openidea-plugin/wit/views.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Declarative views: tool windows declared /// under `[[contributes.views]]` and custom editors under diff --git a/sdk/rust/openidea-plugin/wit/workspace.wit b/sdk/rust/openidea-plugin/wit/workspace.wit index 556dd0da8..851d14d57 100644 --- a/sdk/rust/openidea-plugin/wit/workspace.wit +++ b/sdk/rust/openidea-plugin/wit/workspace.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; interface workspace { use types.{error, location}; diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 3fdfcaa79..9fda5603e 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -504,6 +504,9 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> { plugin::plugin_cancel_task, plugin::plugin_answer_prompt, plugin::plugin_answer_commit, + plugin::plugin_answer_command, + plugin::plugin_choose_program, + plugin::plugin_program, plugin::plugin_commit_checks, plugin::plugin_view_render, plugin::plugin_view_event, diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index 1fd07a381..aa52f4e11 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -338,10 +338,12 @@ pub async fn plugin_run_command( editor: Option<PluginEditor>, paths: Option<Vec<PathBuf>>, settings_scope: Option<SettingsScope>, + command_chain: Option<Vec<String>>, ) -> IdeResult<Option<String>> { let host = state.plugins.clone(); let project = state.project(window.label()).ok(); let invocation = Invocation { + command_chain: command_chain.unwrap_or_default(), client: Some(window.label().to_owned()), workspace_root: project.as_ref().map(|p| p.root.clone()), editor: editor.map(PluginEditor::context), @@ -354,8 +356,13 @@ pub async fn plugin_run_command( /// Workbench events from this window (only the kinds of `plugin_event_kinds`). #[tauri::command] #[specta::specta] -pub fn plugin_post_events(window: Window, state: State<'_, AppState>, events: Vec<WorkbenchEvent>) { - state.plugins.post_events(Some(window.label()), events); +pub fn plugin_post_events( + window: Window, + state: State<'_, AppState>, + events: Vec<WorkbenchEvent>, + editor: Option<PluginEditor>, +) { + state.plugins.post_window_events(window.label(), events, editor); } /// Kinds of workbench events plugins want (re-fetch on `subscriptionsChanged`). @@ -375,13 +382,8 @@ pub async fn plugin_event_kinds(app: tauri::AppHandle) -> Vec<EventKind> { /// Every plugin status bar item (later changes arrive as `statusItemChanged`). #[tauri::command] #[specta::specta] -pub fn plugin_status_items(state: State<'_, AppState>) -> Vec<PluginStatusItem> { - state - .plugins - .status_items() - .into_iter() - .map(|(plugin_id, id, item)| PluginStatusItem { plugin_id, id, item }) - .collect() +pub fn plugin_status_items(window: Window, state: State<'_, AppState>) -> Vec<PluginStatusItem> { + state.plugins.status_snapshot(window.label()) } /// Plugin context keys in effect for this window (later changes arrive as `contextChanged`). @@ -876,3 +878,52 @@ pub async fn plugin_navigation_markers( ide_host::plugins::index_ops::plugin_navigation_markers(&state.host, state.plugins.clone(), window.label(), paths) .await } + +/// The invoking window's reply to a plugin command request. +#[tauri::command] +#[specta::specta] +pub fn plugin_answer_command( + window: Window, + state: State<'_, AppState>, + request_id: String, + answer: ide_host::plugins::CommandAnswer, +) -> IdeResult<bool> { + Ok(state.plugins.answer_command(window.label(), &request_id, answer)) +} + +/// Re-approves a plugin's executable, globally or for this window's project. +#[tauri::command] +#[specta::specta] +pub async fn plugin_choose_program( + window: Window, + state: State<'_, AppState>, + plugin_id: String, + capability: String, + scope: SettingsScope, + path: Option<PathBuf>, +) -> IdeResult<PluginInfo> { + let host = state.plugins.clone(); + let root = match scope { + SettingsScope::Global => None, + SettingsScope::Project => Some(state.project(window.label())?.root.clone()), + }; + blocking(move || host.choose_program(&plugin_id, &capability, root.as_deref(), path.as_deref())).await +} + +/// The currently approved executable in the selected scope, after revalidating its pin. +#[tauri::command] +#[specta::specta] +pub async fn plugin_program( + window: Window, + state: State<'_, AppState>, + plugin_id: String, + program: String, + scope: SettingsScope, +) -> IdeResult<ide_core::IpcPath> { + let host = state.plugins.clone(); + let root = match scope { + SettingsScope::Global => None, + SettingsScope::Project => Some(state.project(window.label())?.root.clone()), + }; + blocking(move || host.program_for_project(&plugin_id, &program, root.as_deref()).map(Into::into)).await +} diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 81dc86bc9..595012e0a 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -237,7 +237,9 @@ impl Handler for ClientHandler { } fn on_request(&self, method: &str, params: Value) -> Result<Value, (i64, String)> { - use ide_host::plugins::remote_host::{SECRET_REQUEST, SecretRequest}; + use ide_host::plugins::remote_host::{ + AUTH_REQUEST, AuthRequest, SECRET_REQUEST, SECRET_WRITE, SecretRequest, SecretWrite, + }; match method { // A remote plugin's request header needs a secret from this machine's keychain. SECRET_REQUEST => { @@ -246,6 +248,18 @@ impl Handler for ClientHandler { let state = self.app.state::<AppState>(); Ok(serde_json::to_value(state.plugins.declared_secret(&r.plugin, &r.name)).unwrap_or(Value::Null)) } + SECRET_WRITE => { + let request: SecretWrite = + serde_json::from_value(params).map_err(|e| (ide_jsonrpc::codes::INVALID_PARAMS, e.to_string()))?; + Ok(serde_json::to_value(self.app.state::<AppState>().plugins.remote_secret_write(request)) + .unwrap_or(Value::Null)) + } + AUTH_REQUEST => { + let request: AuthRequest = + serde_json::from_value(params).map_err(|e| (ide_jsonrpc::codes::INVALID_PARAMS, e.to_string()))?; + Ok(serde_json::to_value(self.app.state::<AppState>().plugins.remote_auth(&self.window, request)) + .unwrap_or(Value::Null)) + } _ => Err((ide_jsonrpc::codes::METHOD_NOT_FOUND, format!("unhandled method {method}"))), } } @@ -537,8 +551,11 @@ pub async fn remote_connect( state.remote_dev.0.lock().insert(label.clone(), connection.clone()); let weak = Arc::downgrade(&connection); let peer = connection.peer.clone(); + let auth_plugins = state.plugins.clone(); + let auth_window = label.clone(); tauri::async_runtime::spawn(async move { peer.closed().await; + auth_plugins.forget_remote_loopbacks(&auth_window); if let Some(connection) = weak.upgrade() { connection.forwards.lock().clear(); } diff --git a/src/bindings.ts b/src/bindings.ts index 85e0f2333..38966e761 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1103,9 +1103,13 @@ export const commands = { path: string, language: string, selections: Range[], -} | null, paths: string[] | null, settingsScope: "global" | "project" | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("plugin_run_command", { pluginId, commandId, arg, editor, paths, settingsScope })), +} | null, paths: string[] | null, settingsScope: "global" | "project" | null, commandChain: string[] | null) => typedError<string | null, IdeError>(__TAURI_INVOKE("plugin_run_command", { pluginId, commandId, arg, editor, paths, settingsScope, commandChain })), /** Workbench events from this window (only the kinds of `plugin_event_kinds`). */ - pluginPostEvents: (events: WorkbenchEvent[]) => __TAURI_INVOKE<void>("plugin_post_events", { events }), + pluginPostEvents: (events: WorkbenchEvent[], editor: { + path: string, + language: string, + selections: Range[], +} | null) => __TAURI_INVOKE<void>("plugin_post_events", { events, editor }), /** Kinds of workbench events plugins want (re-fetch on `subscriptionsChanged`). */ pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"), /** Every plugin status bar item (later changes arrive as `statusItemChanged`). */ @@ -1124,6 +1128,12 @@ export const commands = { * longer waits. */ pluginAnswerCommit: (requestId: string, answer: CommitAnswer) => __TAURI_INVOKE<boolean>("plugin_answer_commit", { requestId, answer }), + /** The invoking window's reply to a plugin command request. */ + pluginAnswerCommand: (requestId: string, answer: CommandAnswer) => typedError<boolean, IdeError>(__TAURI_INVOKE("plugin_answer_command", { requestId, answer })), + /** Re-approves a plugin's executable, globally or for this window's project. */ + pluginChooseProgram: (pluginId: string, capability: string, scope: SettingsScope, path: string | null) => typedError<PluginInfo, IdeError>(__TAURI_INVOKE("plugin_choose_program", { pluginId, capability, scope, path })), + /** The currently approved executable in the selected scope, after revalidating its pin. */ + pluginProgram: (pluginId: string, program: string, scope: SettingsScope) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("plugin_program", { pluginId, program, scope })), /** * Runs plugins' before-commit checks on what `selection` commits, until * `request` is cancelled. @@ -2429,6 +2439,9 @@ export type Command = { arguments: string[], }; +/** The invoking window's response to a command request. */ +export type CommandAnswer = { kind: "value"; value: string | null } | { kind: "notFound" } | { kind: "failed"; value: string }; + export type CommandForm = { command: Command, formFields: FormField[], @@ -3785,7 +3798,7 @@ export type ErrorKind = "notFound" | "alreadyExists" | "permissionDenied" | "inv "unavailable" | "io" | "protocol" | "internal"; /** Kinds of workbench events a plugin can subscribe to (`on-event:<kind>`). */ -export type EventKind = "file-opened" | "file-saved" | "files-changed" | "editor-focused" | "action-performed" | "vcs-changed" | "scheduled"; +export type EventKind = "file-closed" | "settings-changed" | "input-mode-changed" | "file-opened" | "file-saved" | "files-changed" | "editor-focused" | "action-performed" | "vcs-changed" | "scheduled"; /** An exception breakpoint filter offered by an adapter (`exceptionBreakpointFilters`). */ export type ExceptionFilter = { @@ -4808,6 +4821,13 @@ export type InlineCompletionSettings = { disabledLanguages?: string[], }; +/** The focused editor's input mode and optional visual sub-mode. */ +export type InputMode = { + path: string, + mode: string, + sub: string | null, +}; + export type InspectEvent = /** Files about to be inspected. */ { type: "started"; total: number } | @@ -6125,6 +6145,12 @@ export type PluginEndpoint = { export type PluginEvent = /** Plugins, their status or their contributions changed: re-fetch `plugin_list`. */ { type: "commandsChanged" } | +/** A bounded output channel snapshot, or withdrawal when the plugin stops. */ +{ type: "outputChanged"; pluginId: string; channel: string; text: string | null } | +/** Reveal a read-only Output tab in the receiving window. */ +{ type: "revealOutput"; pluginId: string; channel: string; text: string } | +/** Execute an action through the receiving window and answer over IPC. */ +{ type: "executeCommand"; requestId: string; id: string; arg: string | null; chain: string[] } | /** Cached document associations were disposed (reload, disable or failure). */ { type: "documentIndexesChanged" } | /** @@ -6141,6 +6167,8 @@ export type PluginEvent = actions: NotificationAction[] } | /** A plugin's status bar item was set (`item`) or removed. */ { type: "statusItemChanged"; pluginId: string; id: string; item: StatusItem | null } | +/** An override in the receiving window; removal exposes the global item. */ +{ type: "windowStatusItemChanged"; pluginId: string; id: string; item: StatusItem | null } | /** * A plugin's context key was set (`value`: JSON text) or removed, in the * emitted window (every window when the client is `None`). @@ -6285,6 +6313,8 @@ export type PluginStatus = /** A plugin's status bar item. */ export type PluginStatusItem = { + /** Whether this item overrides the global item in the requesting window. */ + window: boolean, pluginId: string, id: string, item: StatusItem, @@ -8483,7 +8513,7 @@ export type WindowTab = { }; /** A workbench event delivered to plugins. */ -export type WorkbenchEvent = { kind: "fileOpened"; value: string } | { kind: "fileSaved"; value: string } | { kind: "filesChanged"; value: FilesChanged } | { kind: "editorFocused"; value: string | null } | { kind: "actionPerformed"; value: ActionPerformed } | { kind: "vcsChanged"; value: string } | { kind: "scheduled" }; +export type WorkbenchEvent = { kind: "fileClosed"; value: string } | { kind: "settingsChanged"; value: string[] } | { kind: "inputModeChanged"; value: InputMode } | { kind: "fileOpened"; value: string } | { kind: "fileSaved"; value: string } | { kind: "filesChanged"; value: FilesChanged } | { kind: "editorFocused"; value: string | null } | { kind: "actionPerformed"; value: ActionPerformed } | { kind: "vcsChanged"; value: string } | { kind: "scheduled" }; export type WorkingTreeChange = { path: string, diff --git a/src/editor/api.ts b/src/editor/api.ts index 5206a786b..6be4d04eb 100644 --- a/src/editor/api.ts +++ b/src/editor/api.ts @@ -456,6 +456,7 @@ export function _provideNavigationHistory(provider: () => NavigationHistorySnaps // --- editor events ------------------------------------------------------------ export type EditorEvent = + | { type: "inputModeChanged"; path: string; mode: string; sub: string | null } | { type: "docOpened"; doc: number; path: string; language: string } | { type: "docClosed"; doc: number; path: string } /** After the backend wrote the file. */ @@ -465,6 +466,11 @@ export type EditorEvent = /** Caret moved in the active text editor (throttled to animation frames). 0-based. */ | { type: "caretMoved"; doc: number; path: string; line: number; col: number; offset: number }; +/** Reports the focused editor's input mode from an editor contribution. */ +export function reportInputMode(path: string, mode: string, sub: string | null) { + _emitEditorEvent({ type: "inputModeChanged", path, mode, sub }); +} + type EditorEventListener = (e: EditorEvent) => void; const editorEventListeners = new Set<EditorEventListener>(); diff --git a/src/features/plugins/PluginsPage.module.css b/src/features/plugins/PluginsPage.module.css index 305ad6483..4eb73a89a 100644 --- a/src/features/plugins/PluginsPage.module.css +++ b/src/features/plugins/PluginsPage.module.css @@ -334,6 +334,41 @@ } /* Permission dialog and notices */ +.capabilityItem { + min-width: 0; + padding: 8px 10px; +} +.capabilityItem + .capabilityItem { + border-top: 1px solid var(--border); +} +.capabilityHeader { + display: flex; + align-items: center; + gap: 10px; +} +.capabilityHeader > .mono { + flex: 1; + min-width: 0; + overflow-wrap: anywhere; +} +.capabilityDescription { + margin: 4px 0 0 26px; + color: var(--fg); + overflow-wrap: anywhere; +} +.programPermission { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + min-width: 0; + margin: 6px 0 0 26px; +} +.programPath { + flex-basis: 100%; + min-width: 0; + overflow-wrap: anywhere; +} .consent { display: flex; flex-direction: column; diff --git a/src/features/plugins/PluginsPage.tsx b/src/features/plugins/PluginsPage.tsx index ec1f9546c..4ad771cbc 100644 --- a/src/features/plugins/PluginsPage.tsx +++ b/src/features/plugins/PluginsPage.tsx @@ -31,7 +31,7 @@ import { type MenuItem, T, } from "@/ui"; -import { RISK_LABEL, sortByRisk } from "./consent"; +import { RISK_LABEL, sortByRisk, capabilityDescription } from "./consent"; import { pluginIconName } from "./pluginIcon"; import { localizeContributions, usePluginCatalogs, usePluginT } from "./pluginText"; import { itemsOf, uiPoint } from "./projection"; @@ -59,6 +59,8 @@ import { openExternalUrl } from "@/platform/openUrl"; import { importIntellijTheme, showInstalledIntellijThemes } from "./intellijImport"; import { promptInput } from "@/workbench/inputDialogs"; import styles from "./PluginsPage.module.css"; +import { pluginsBackend } from "./backend"; +import { confirm } from "@/workbench/messages"; import { tx } from "@/platform/i18n"; const STATUS: Record<PluginStatus, { label: string; tone: "success" | "accent" | "neutral" | "danger" | "warning" }> = { @@ -293,17 +295,86 @@ function PointSection({ plugin, point }: { plugin: PluginInfo; point: string }) ); } -function CapabilityRow({ cap, children }: { cap: CapabilityInfo; children?: ReactNode }) { +function CapabilityRow({ cap, children, program }: { cap: CapabilityInfo; children?: ReactNode; program?: ReactNode }) { return ( - <li className={styles.item}> - {children} - <span className={styles.itemMain}>{tx(cap.description)}</span> - <span className={styles.mono}>{cap.id}</span> - <Badge tone={RISK_LABEL[cap.risk].tone}>{RISK_LABEL[cap.risk].label}</Badge> + <li className={styles.capabilityItem}> + <div className={styles.capabilityHeader}> + {children} + <span className={styles.mono}>{cap.id}</span> + <Badge tone={RISK_LABEL[cap.risk].tone}>{RISK_LABEL[cap.risk].label}</Badge> + </div> + <p className={styles.capabilityDescription}>{capabilityDescription(cap)}</p> + {program} </li> ); } +function ProgramPermission({ plugin, cap, disabled }: { plugin: PluginInfo; cap: CapabilityInfo; disabled: boolean }) { + const project = useProject((s) => s.project); + const [scope, setScope] = useState<"global" | "project">("global"); + const [path, setPath] = useState(""); + const [error, setError] = useState(""); + const [working, setWorking] = useState(false); + useEffect(() => { + let live = true; + void pluginsBackend() + .program(plugin.id, cap.id.slice(8), scope) + .then((p) => { + if (live) setPath(p); + }) + .catch(() => { + if (live) setPath(""); + }); + return () => { + live = false; + }; + }, [plugin, cap.id, scope, working]); + const choose = async (reset: boolean) => { + setError(""); + setWorking(true); + try { + const selected = reset ? null : await pluginsBackend().pickProgram(); + if (!reset && !selected) return; + const message = reset + ? tx("Revalidate the default executable? If it is unavailable, this permission will be revoked.") + : tx`Allow ${plugin.name} to run ${selected}? This is equivalent to running arbitrary code on this machine.`; + if (!(await confirm({ title: tx("Approve plugin executable"), message, ok: tx("Allow"), icon: "warning" }))) + return; + await pluginsBackend().chooseProgram(plugin.id, cap.id, scope, selected); + await refreshPlugins(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setWorking(false); + } + }; + return ( + <div className={styles.programPermission}> + {path && <span className={clsx(styles.mono, styles.programPath)}>{path}</span>} + <Select + aria-label={tx("Executable scope")} + value={scope} + onChange={(value) => setScope(value as "global" | "project")} + options={[ + { value: "global", label: tx("Global") }, + ...(project ? [{ value: "project", label: tx("Project") }] : []), + ]} + /> + <Button disabled={disabled || working} onClick={() => void choose(false)}> + {tx("Choose executable…")} + </Button> + <Button disabled={disabled || working} onClick={() => void choose(true)}> + {tx("Reset executable")} + </Button> + {error && ( + <span role="alert" className={styles.error}> + {error} + </span> + )} + </div> + ); +} + function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) { if (plugin.capabilities.length === 0) { return ( @@ -316,7 +387,13 @@ function CapabilityList({ plugin, busy }: { plugin: PluginInfo; busy: boolean }) return ( <ul className={styles.items} aria-label={tx("Permissions")}> {sortByRisk(plugin.capabilities).map((c) => ( - <CapabilityRow key={c.id} cap={c}> + <CapabilityRow + key={c.id} + cap={c} + program={ + c.id.startsWith("process:") && <ProgramPermission plugin={plugin} cap={c} disabled={busy || !confirmed} /> + } + > <Checkbox checked={c.granted} disabled={busy || !confirmed} diff --git a/src/features/plugins/__tests__/logEditor.test.tsx b/src/features/plugins/__tests__/logEditor.test.tsx index da0293c34..d25a5c8da 100644 --- a/src/features/plugins/__tests__/logEditor.test.tsx +++ b/src/features/plugins/__tests__/logEditor.test.tsx @@ -8,6 +8,7 @@ import { useContributions } from "@/workbench/contributions"; import { usePlugins } from "../store"; import { startViewUi } from "../uiPoints"; import { registerLogActions } from "../views/logActions"; +import { setPluginOutput, usePluginOutput } from "../views/outputStore"; import { PluginLogEditor } from "../views/logEditor"; import { boundedLog, logTabData, type PluginLogEditorData } from "../views/logTab"; import { logTabPtyBackend, webPtyBackend } from "../views/ptyBackend"; @@ -71,6 +72,33 @@ function setup(extra: Partial<PluginLogEditorData> = {}) { } describe("plugin streaming log tabs", () => { + it("shows output channel snapshots in the read-only log editor without starting a process", () => { + vi.mocked(webPtyBackend).mockClear(); + vi.mocked(logTabPtyBackend).mockClear(); + usePluginOutput.setState({ channels: new Map() }); + setPluginOutput("probe", "build", "first output"); + const data: PluginLogEditorData = { + pluginId: "probe", + view: "", + key: "build", + title: "Build output", + program: "", + args: [], + toggles: [], + origin: "output", + }; + const rendered = render(<PluginLogEditor input={{ kind: "pluginLog", key: "output", data }} />); + const view = EditorView.findFromDOM(rendered.container.querySelector(".cm-content") as HTMLElement)!; + expect(view.state.doc.toString()).toBe("first output"); + expect(view.state.readOnly).toBe(true); + act(() => setPluginOutput("probe", "build", "next output")); + expect(view.state.doc.toString()).toBe("next output"); + act(() => setPluginOutput("probe", "build", "")); + expect(view.state.doc.length).toBe(0); + expect(webPtyBackend).not.toHaveBeenCalled(); + expect(logTabPtyBackend).not.toHaveBeenCalled(); + }); + it("rejects malformed requests and exact-grant failures instead of rewriting commands", () => { usePlugins.setState({ plugins: [plugin] }); for (const bad of [ diff --git a/src/features/plugins/__tests__/plugins.test.tsx b/src/features/plugins/__tests__/plugins.test.tsx index 3a79818ca..b51f5f60d 100644 --- a/src/features/plugins/__tests__/plugins.test.tsx +++ b/src/features/plugins/__tests__/plugins.test.tsx @@ -502,6 +502,60 @@ describe("bridge events", () => { expect(useTasks.getState().tasks.find((t) => t.id === "plugin:7")?.done).toBe(true); }); + it("keeps a window status override above global updates and falls back on removal", () => { + const global = { text: "global", tooltip: null, command: null }; + const local = { text: "window", tooltip: null, command: null }; + handleRuntimeEvent({ type: "statusItemChanged", pluginId: "scope", id: "state", item: global }); + handleRuntimeEvent({ type: "windowStatusItemChanged", pluginId: "scope", id: "state", item: local }); + handleRuntimeEvent({ + type: "statusItemChanged", + pluginId: "scope", + id: "state", + item: { ...global, text: "updated" }, + }); + expect(usePluginStatusItems.getState().items.get("scope/state")?.item.text).toBe("window"); + handleRuntimeEvent({ type: "windowStatusItemChanged", pluginId: "scope", id: "state", item: null }); + expect(usePluginStatusItems.getState().items.get("scope/state")?.item.text).toBe("updated"); + handleRuntimeEvent({ type: "statusItemChanged", pluginId: "scope", id: "state", item: null }); + }); + + it("executes host command requests through actions and returns plugin command results", async () => { + const answerCommand = vi.fn().mockResolvedValue(undefined); + const runCommand = vi.fn().mockResolvedValue("plugin result"); + setPluginsBackend({ ...backend, answerCommand, runCommand }); + const run = vi.fn(); + const dispose = registerAction({ id: "test.host-command", title: "Test", run }); + try { + handleRuntimeEvent({ + type: "executeCommand", + requestId: "ide", + id: "test.host-command", + arg: "argument", + chain: ["caller"], + }); + await waitFor(() => expect(answerCommand).toHaveBeenCalledWith("ide", { kind: "value", value: null })); + expect(run).toHaveBeenCalledWith(expect.objectContaining({ arg: "argument" })); + usePlugins.setState({ + ui: [{ pluginId: "other", point: "commands", key: "test", decl: { id: "test", title: "Test" } }], + }); + handleRuntimeEvent({ + type: "executeCommand", + requestId: "plugin", + id: "plugin.other.test", + arg: "argument", + chain: ["caller"], + }); + await waitFor(() => + expect(answerCommand).toHaveBeenCalledWith("plugin", { kind: "value", value: "plugin result" }), + ); + expect(runCommand).toHaveBeenCalledWith("other", "test", "argument", null, [], undefined, ["caller"]); + handleRuntimeEvent({ type: "executeCommand", requestId: "missing", id: "unknown", arg: null, chain: ["caller"] }); + await waitFor(() => expect(answerCommand).toHaveBeenCalledWith("missing", { kind: "notFound" })); + } finally { + dispose(); + } + }); + it("runs notification buttons as commands of the publishing plugin with their arguments", async () => { const runCommand = vi.fn().mockResolvedValue(null); setPluginsBackend({ ...backend, runCommand }); diff --git a/src/features/plugins/backend.ts b/src/features/plugins/backend.ts index 4612feec1..9b251f705 100644 --- a/src/features/plugins/backend.ts +++ b/src/features/plugins/backend.ts @@ -9,6 +9,7 @@ import type { CapabilityInfo, CatalogPlugin, CommitAnswer, + CommandAnswer, CommitSelection, Consent, EventKind, @@ -35,6 +36,7 @@ import type { WorkbenchEvent, } from "@/bindings"; import { tx } from "@/platform/i18n"; +import { useRemote } from "@/platform/remote"; import { call, commands, IpcError, isCancelled, isTauri, nextRequestId } from "@/platform/ipc"; import { editorContext } from "./editorContext"; @@ -46,6 +48,14 @@ export interface PluginsBackend { installDir(path: string, consent: Consent): Promise<PluginInfo>; /** Confirms a plugin waiting for consent. */ grant(id: string, consent: Consent): Promise<PluginInfo>; + chooseProgram( + pluginId: string, + capability: string, + scope: "global" | "project", + path: string | null, + ): Promise<PluginInfo>; + program(pluginId: string, program: string, scope: "global" | "project"): Promise<string>; + pickProgram(): Promise<string | null>; setCapability(id: string, capability: string, granted: boolean): Promise<PluginInfo>; /** Validated assets (icon theme mapping and SVGs) whose id starts with `prefix`. */ assets(pluginId: string, prefix: string): Promise<[string, string][]>; @@ -63,6 +73,7 @@ export interface PluginsBackend { editor: PluginEditor | null, paths: string[], settingsScope?: "global" | "project", + commandChain?: string[], ): Promise<string | null>; /** Workbench events plugins subscribed to (see `eventKinds`). */ postEvents(events: WorkbenchEvent[]): Promise<void>; @@ -75,6 +86,7 @@ export interface PluginsBackend { /** Reports the answer to a plugin's `promptRequested`: keys, `[text]`, anything for OK, `null` when dismissed. */ answerPrompt(promptId: string, answer: string[] | null): Promise<void>; /** This window's answer to a plugin's `commitRequested`. */ + answerCommand(requestId: string, answer: CommandAnswer): Promise<void>; answerCommit(requestId: string, answer: CommitAnswer): Promise<void>; /** Runs plugins' before-commit checks on what `selection` commits. */ commitChecks(selection: CommitSelection, checks: PluginCommitCheckRef[]): Promise<PluginCommitCheckResult[]>; @@ -175,6 +187,20 @@ export const tauriPluginsBackend: PluginsBackend = { previewInstall: (path) => call(commands.pluginPreviewInstall(path)), installDir: (path, consent) => call(commands.pluginInstallDir(path, consent)), grant: (id, consent) => call(commands.pluginGrant(id, consent)), + chooseProgram: async (id, cap, scope, path) => { + const remote = !!useRemote.getState().session; + if (remote && path !== null) await call(commands.pluginSetCapability(id, cap, true)); + const chosen = await call(commands.pluginChooseProgram(id, cap, scope, path)); + if (remote && !chosen.capabilities.some((c) => c.id === cap && c.granted)) + await call(commands.pluginSetCapability(id, cap, false)); + return chosen; + }, + program: (id, program, scope) => call(commands.pluginProgram(id, program, scope)), + pickProgram: async () => { + const { open } = await import("@tauri-apps/plugin-dialog"); + const picked = await open({ directory: false, multiple: false, title: tx("Choose plugin executable") }); + return (Array.isArray(picked) ? picked[0] : picked) ?? null; + }, setCapability: (id, capability, granted) => call(commands.pluginSetCapability(id, capability, granted)), assets: (pluginId, prefix) => call(commands.pluginAssets(pluginId, prefix)), activationEvent: async (kind, value) => { @@ -185,10 +211,12 @@ export const tauriPluginsBackend: PluginsBackend = { await call(commands.pluginUninstall(id)); }, reload: (id) => call(commands.pluginReload(id)), - runCommand: (pluginId, commandId, arg, editor, paths, settingsScope) => - call(commands.pluginRunCommand(pluginId, commandId, arg, editor, paths, settingsScope ?? null)), + runCommand: (pluginId, commandId, arg, editor, paths, settingsScope, commandChain) => + call( + commands.pluginRunCommand(pluginId, commandId, arg, editor, paths, settingsScope ?? null, commandChain ?? null), + ), postEvents: async (events) => { - await commands.pluginPostEvents(events); + await commands.pluginPostEvents(events, editorContext()); }, eventKinds: () => commands.pluginEventKinds(), statusItems: () => commands.pluginStatusItems(), @@ -199,6 +227,9 @@ export const tauriPluginsBackend: PluginsBackend = { answerPrompt: async (promptId, answer) => { await commands.pluginAnswerPrompt(promptId, answer); }, + answerCommand: async (requestId, answer) => { + await call(commands.pluginAnswerCommand(requestId, answer)); + }, answerCommit: async (requestId, answer) => { await commands.pluginAnswerCommit(requestId, answer); }, @@ -520,6 +551,11 @@ export function createMemoryPluginsBackend( emit({ type: "commandsChanged" }); return { ...p }; }, + chooseProgram: async (id) => { + return { ...find(id) }; + }, + program: async (_id, program) => program, + pickProgram: async () => null, setCapability: async (id, capability, granted) => { const p = find(id); p.capabilities = p.capabilities.map((c) => (c.id === capability ? { ...c, granted } : c)); @@ -594,6 +630,7 @@ export function createMemoryPluginsBackend( viewEvent: async () => {}, serviceDetail: async () => [], endpoints: async () => [], + answerCommand: async () => {}, answerCommit: async () => {}, commitChecks: async () => [], serviceLog: (pluginId, view, key, _tab, _on, _onLine, onError) => { diff --git a/src/features/plugins/consent.tsx b/src/features/plugins/consent.tsx index b2f1268a6..1355a85c3 100644 --- a/src/features/plugins/consent.tsx +++ b/src/features/plugins/consent.tsx @@ -30,6 +30,19 @@ export function sortByRisk(caps: readonly CapabilityInfo[]): CapabilityInfo[] { return [...caps].sort((a, b) => RISK_ORDER[a.risk] - RISK_ORDER[b.risk] || a.id.localeCompare(b.id)); } +/** Parameterised permission text, translated independently of the granted host/path. */ +export function capabilityDescription(cap: CapabilityInfo): string { + if (cap.id.startsWith("net.http:")) { + const host = cap.id.slice(9); + return tx`Connect to ${host} over unencrypted HTTP (from the machine the project is on)`; + } + if (cap.id.startsWith("ipc:")) { + const path = cap.id.slice(4); + return tx`Connect to local socket ${path} — equivalent to running arbitrary code on the project machine`; + } + return tx(cap.description); +} + function ask(req: ConsentRequest): Promise<Consent | null> { return new Promise((resolve) => usePending.setState((s) => ({ queue: [...s.queue, { req, resolve }] }))); } @@ -84,28 +97,30 @@ function ConsentDialog({ pending, onDone }: { pending: Pending; onDone: () => vo ) : ( <ul className={styles.items} aria-label={tx("Requested permissions")}> {caps.map((c) => ( - <li key={c.id} className={styles.item}> - {c.optional ? ( - <Checkbox - checked={accepted.has(c.id)} - onChange={(on) => - setAccepted((s) => { - const next = new Set(s); - if (on) next.add(c.id); - else next.delete(c.id); - return next; - }) - } - aria-label={tx`Allow ${c.id}`} - /> - ) : ( - <span className={styles.consentRequired} title={tx("Required")}> - • - </span> - )} - <span className={styles.itemMain}>{tx(c.description)}</span> - <span className={styles.mono}>{c.id}</span> - <Badge tone={RISK_LABEL[c.risk].tone}>{RISK_LABEL[c.risk].label}</Badge> + <li key={c.id} className={styles.capabilityItem}> + <div className={styles.capabilityHeader}> + {c.optional ? ( + <Checkbox + checked={accepted.has(c.id)} + onChange={(on) => + setAccepted((s) => { + const next = new Set(s); + if (on) next.add(c.id); + else next.delete(c.id); + return next; + }) + } + aria-label={tx`Allow ${c.id}`} + /> + ) : ( + <span className={styles.consentRequired} title={tx("Required")}> + • + </span> + )} + <span className={styles.mono}>{c.id}</span> + <Badge tone={RISK_LABEL[c.risk].tone}>{RISK_LABEL[c.risk].label}</Badge> + </div> + <p className={styles.capabilityDescription}>{capabilityDescription(c)}</p> </li> ))} </ul> diff --git a/src/features/plugins/runtimeUi.tsx b/src/features/plugins/runtimeUi.tsx index ecd86c00c..9c07ee929 100644 --- a/src/features/plugins/runtimeUi.tsx +++ b/src/features/plugins/runtimeUi.tsx @@ -7,6 +7,7 @@ import { create } from "zustand"; import type { CommitAnswer, + CommandAnswer, CommitRequest, EventKind, PluginContextKey, @@ -29,8 +30,10 @@ import { notifications, maybeCommitService, maybeEditorService, registerStatusIt import { pickItems, promptInput } from "@/workbench/inputDialogs"; import { confirm } from "@/workbench/messages"; import { removeTask, upsertTask, useTasks } from "@/workbench/tasks"; +import { editorContext } from "./editorContext"; import { pluginsBackend } from "./backend"; import { usePluginT } from "./pluginText"; +import { setPluginOutput } from "./views/outputStore"; import { PLUGIN_LOG_EDITOR_KIND } from "./views/logEditor"; import type { PluginLogEditorData } from "./views/logTab"; import { bumpView, deliverViewMessage } from "./views/viewStore"; @@ -45,11 +48,22 @@ export const usePluginStatusItems = create<{ items: Map<ItemKey, { pluginId: str items: new Map(), })); -function setStatusItem(pluginId: string, id: string, item: StatusItem | null) { +let statusRevision = 0; +let statusRequest = 0; +const globalStatus = new Map<ItemKey, { pluginId: string; item: StatusItem }>(); +const windowStatus = new Map<ItemKey, { pluginId: string; item: StatusItem }>(); + +function setStatusItem(pluginId: string, id: string, item: StatusItem | null, window = false) { + statusRevision++; + const key: ItemKey = `${pluginId}/${id}`; + const scope = window ? windowStatus : globalStatus; + if (item) scope.set(key, { pluginId, item }); + else scope.delete(key); + const effective = windowStatus.get(key) ?? globalStatus.get(key); usePluginStatusItems.setState((s) => { const items = new Map(s.items); - if (item) items.set(`${pluginId}/${id}`, { pluginId, item }); - else items.delete(`${pluginId}/${id}`); + if (effective) items.set(key, effective); + else items.delete(key); return { items }; }); } @@ -161,9 +175,21 @@ function projectStatusItems(): () => void { * window's project is open and trusted, so call it again when that happens. */ function refreshStatusItems() { + const request = ++statusRequest; + const revision = statusRevision; void pluginsBackend() .statusItems() - .then((items) => items.forEach((i) => setStatusItem(i.pluginId, i.id, i.item))) + .then((items) => { + if (request !== statusRequest) return; + if (revision !== statusRevision) { + refreshStatusItems(); + return; + } + globalStatus.clear(); + windowStatus.clear(); + usePluginStatusItems.setState({ items: new Map() }); + items.forEach((i) => setStatusItem(i.pluginId, i.id, i.item, i.window)); + }) .catch(() => {}); } @@ -271,7 +297,10 @@ let postTimer: ReturnType<typeof setTimeout> | null = null; export function refreshEventKinds() { void pluginsBackend() .eventKinds() - .then((kinds) => (wanted = new Set(kinds))) + .then((kinds) => { + wanted = new Set(kinds); + if (wanted.has("settings-changed")) post({ kind: "settingsChanged", value: [] }); + }) .catch(() => {}); } @@ -293,6 +322,9 @@ function trackWorkbenchEvents(): () => void { refreshEventKinds(); const offEditor = onEditorEvent((e) => { if (e.type === "docOpened" && wanted.has("file-opened")) post({ kind: "fileOpened", value: e.path }); + if (e.type === "docClosed" && wanted.has("file-closed")) post({ kind: "fileClosed", value: e.path }); + if (e.type === "inputModeChanged" && wanted.has("input-mode-changed")) + post({ kind: "inputModeChanged", value: { path: e.path, mode: e.mode, sub: e.sub } }); if (e.type === "docSaved" && wanted.has("file-saved")) post({ kind: "fileSaved", value: e.path }); }); const offActions = onActionExecuted((id, _arg, source) => { @@ -303,6 +335,9 @@ function trackWorkbenchEvents(): () => void { value: { action: id, title: action?.title ?? id, source, shortcut: shortcutLabel(id) ?? null }, }); }); + const offSettings = onIdeEvent("settingsChanged", () => { + if (wanted.has("settings-changed")) post({ kind: "settingsChanged", value: [] }); + }); const offVcs = onIdeEvent("vcsChanged", (e) => { if (wanted.has("vcs-changed")) post({ kind: "vcsChanged", value: e.root }); }); @@ -310,6 +345,7 @@ function trackWorkbenchEvents(): () => void { offEditor(); offActions(); offVcs(); + offSettings(); if (postTimer) clearTimeout(postTimer); postTimer = null; queue = []; @@ -395,12 +431,47 @@ async function answerCommit(requestId: string, request: CommitRequest) { .catch(() => {}); } +async function answerCommand(e: Extract<PluginEvent, { type: "executeCommand" }>) { + let answer: CommandAnswer; + try { + const command = usePlugins + .getState() + .ui.find((c) => c.point === "commands" && e.id === `plugin.${c.pluginId}.${(c.decl as { id: string }).id}`); + if (command) { + const value = await pluginsBackend().runCommand( + command.pluginId, + (command.decl as { id: string }).id, + e.arg, + editorContext(), + [], + undefined, + e.chain, + ); + answer = { kind: "value", value }; + } else if (getAction(e.id)) { + await executeAction(e.id, e.arg); + answer = { kind: "value", value: null }; + } else answer = { kind: "notFound" }; + } catch (error) { + answer = { kind: "failed", value: error instanceof Error ? error.message : String(error) }; + } + await pluginsBackend() + .answerCommand(e.requestId, answer) + .catch(() => {}); +} + /** Handles the runtime UI events; returns whether `e` was one. */ export function handleRuntimeEvent(e: PluginEvent): boolean { switch (e.type) { + case "executeCommand": + void answerCommand(e); + return true; case "contextChanged": refreshContextKeys(); return true; + case "windowStatusItemChanged": + setStatusItem(e.pluginId, e.id, e.item, true); + return true; case "statusItemChanged": setStatusItem(e.pluginId, e.id, e.item); return true; @@ -422,6 +493,26 @@ export function handleRuntimeEvent(e: PluginEvent): boolean { // The program was approved (`process:`) and verified by the host. void executeAction("terminal.runCommand", { program: e.program, args: e.args, name: e.title, cwd: e.cwd }); return true; + case "outputChanged": + setPluginOutput(e.pluginId, e.channel, e.text); + return true; + case "revealOutput": + setPluginOutput(e.pluginId, e.channel, e.text); + void maybeEditorService()?.openInput({ + kind: PLUGIN_LOG_EDITOR_KIND, + key: `pluginOutput:${JSON.stringify([e.pluginId, e.channel])}`, + data: { + pluginId: e.pluginId, + view: "", + key: e.channel, + title: tx`Output: ${e.channel}`, + program: "", + args: [], + toggles: [], + origin: "output", + } satisfies PluginLogEditorData, + }); + return true; case "openLogTab": void maybeEditorService()?.openInput({ kind: PLUGIN_LOG_EDITOR_KIND, @@ -477,6 +568,10 @@ export function handleRuntimeEvent(e: PluginEvent): boolean { function refreshOnProjectChange(): () => void { return useProject.subscribe((s, prev) => { if (s.project === prev.project) return; + statusRevision++; + globalStatus.clear(); + windowStatus.clear(); + usePluginStatusItems.setState({ items: new Map() }); refreshEventKinds(); refreshStatusItems(); refreshContextKeys(); diff --git a/src/features/plugins/views/logEditor.tsx b/src/features/plugins/views/logEditor.tsx index d36c762a7..002cd3141 100644 --- a/src/features/plugins/views/logEditor.tsx +++ b/src/features/plugins/views/logEditor.tsx @@ -24,6 +24,7 @@ import { usePlugins } from "../store"; import { bindLogControls } from "./logActions"; import { boundedLog, type PluginLogEditorData } from "./logTab"; import { logTabPtyBackend, webPtyBackend } from "./ptyBackend"; +import { outputKey, usePluginOutput } from "./outputStore"; import { ptyBridge } from "./ptyBridge"; export const PLUGIN_LOG_EDITOR_KIND = "pluginLog"; @@ -50,7 +51,7 @@ const wheelZoom = EditorView.domEventHandlers({ export function PluginLogEditor({ input }: { input: EditorInput }) { const data = input.data as PluginLogEditorData | undefined; - if (!data || !data.program) { + if (!data || (!data.program && data.origin !== "output")) { return <EmptyState title={tx("Invalid log stream configuration")} />; } return <PluginLogEditorBody input={input} data={data} />; @@ -336,6 +337,16 @@ function PluginLogEditorBody({ input, data }: { input: EditorInput; data: Plugin useEffect(() => { const view = viewRef.current; if (!view) return; + if (data.origin === "output") { + const key = outputKey(data.pluginId, data.key ?? ""); + const update = () => { + const text = usePluginOutput.getState().channels.get(key) ?? ""; + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } }); + if (stickRef.current) view.scrollDOM.scrollTop = view.scrollDOM.scrollHeight; + }; + update(); + return usePluginOutput.subscribe(update); + } receivedRef.current = false; view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: tx("Waiting for output…") } }); stickRef.current = true; diff --git a/src/features/plugins/views/logTab.ts b/src/features/plugins/views/logTab.ts index 0ed1dc6c9..700584912 100644 --- a/src/features/plugins/views/logTab.ts +++ b/src/features/plugins/views/logTab.ts @@ -16,7 +16,7 @@ export interface PluginLogEditorData { args: string[]; toggles: PluginLogToggleSpec[]; /** Opened by the plugin's code (`views.open-log-tab`): the host starts what it approved for `key`. */ - origin?: "code"; + origin?: "code" | "output"; } const text = (v: unknown, max: number): v is string => diff --git a/src/features/plugins/views/outputStore.ts b/src/features/plugins/views/outputStore.ts new file mode 100644 index 000000000..80c33e75f --- /dev/null +++ b/src/features/plugins/views/outputStore.ts @@ -0,0 +1,13 @@ +import { create } from "zustand"; + +/** Snapshots of the host's bounded, read-only output channels. */ +export const usePluginOutput = create<{ channels: Map<string, string> }>(() => ({ channels: new Map() })); +export const outputKey = (pluginId: string, channel: string) => JSON.stringify([pluginId, channel]); +export function setPluginOutput(pluginId: string, channel: string, text: string | null) { + usePluginOutput.setState((s) => { + const channels = new Map(s.channels); + if (text === null) channels.delete(outputKey(pluginId, channel)); + else channels.set(outputKey(pluginId, channel), text); + return { channels }; + }); +} diff --git a/src/features/vim/__tests__/vim.test.ts b/src/features/vim/__tests__/vim.test.ts index 097a3138e..069c2ee18 100644 --- a/src/features/vim/__tests__/vim.test.ts +++ b/src/features/vim/__tests__/vim.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { EditorState, Prec } from "@codemirror/state"; import { EditorView, keymap } from "@codemirror/view"; import { getCM, Vim } from "@replit/codemirror-vim"; -import { embeddedEditorExtensions, transientChange, useEditorRegistry } from "@/editor/api"; +import { embeddedEditorExtensions, transientChange, useEditorRegistry, onEditorEvent } from "@/editor/api"; import { executeAction, registerAction } from "@/platform/actions"; import { getContext } from "@/platform/context"; import { _handleEx, applyRcCommands, vimExtension } from "../engine"; @@ -49,6 +49,7 @@ describe("Vim mode toggle", () => { await executeAction("vim.toggle"); expect(useVimSettings.getState().enabled).toBe(false); expect(hasContribution()).toBe(false); + expect(getContext()["vim.mode"]).toBe(""); expect(diffSide.dom.hasAttribute("data-openidea-vim")).toBe(false); expect(getCM(diffSide)).toBeNull(); diffSide.destroy(); @@ -217,7 +218,17 @@ describe("Vim engine", () => { const closePopup = Prec.highest( keymap.of([{ key: "Escape", run: () => (popupOpen ? !(popupOpen = false) : false) }]), ); - const view = makeView([vimExtension(), closePopup]); + const modes: string[] = []; + const offModes = onEditorEvent((event) => { + if (event.type === "inputModeChanged") { + expect(event.path).toBe("/p/a.ts"); + modes.push(event.mode); + } + }); + const view = makeView([ + vimExtension({ doc: 1, path: "/p/a.ts", language: "typescript", uiMode: null, readOnly: false }), + closePopup, + ]); view.focus(); const cm = getCM(view)!; Vim.handleKey(cm as never, "i", "user"); @@ -233,6 +244,9 @@ describe("Vim engine", () => { expect(cm.state.vim?.insertMode).toBe(false); Vim.handleKey(cm as never, "v", "user"); expect(useVimMode.getState().mode).toBe("visual"); + expect(getContext()["vim.mode"]).toBe("visual"); + expect(modes).toEqual(expect.arrayContaining(["insert", "normal", "visual"])); + offModes(); view.destroy(); }); }); diff --git a/src/features/vim/engine.ts b/src/features/vim/engine.ts index c3612a200..4a8209bea 100644 --- a/src/features/vim/engine.ts +++ b/src/features/vim/engine.ts @@ -6,7 +6,8 @@ import { EditorState, Prec, StateEffect, StateField, Transaction, type Extension } from "@codemirror/state"; import { EditorView, ViewPlugin, runScopeHandlers } from "@codemirror/view"; import { Vim, getCM, vim } from "@replit/codemirror-vim"; -import { transientChange } from "@/editor/api"; +import { transientChange, reportInputMode, type EditorDocContext } from "@/editor/api"; +import { setContext } from "@/platform/context"; import { executeAction, getAction } from "@/platform/actions"; import { showStatusInfo } from "@/workbench/contributions"; import { VIM_EDITOR_ATTR } from "./conflicts"; @@ -190,27 +191,32 @@ const escapeClosesPopupsFirst = EditorView.domEventHandlers({ }, }); -const modeTracker = ViewPlugin.define((view) => { - const cm = getCM(view); - let state: VimModeState = { mode: cm?.state.vim?.insertMode ? "insert" : "normal", sub: null }; - const publish = () => useVimMode.setState(state); - // Not `view.hasFocus`: that also needs the window focused, and this editor stays the last focused one. - const focused = () => view.root.activeElement === view.contentDOM; - const onModeChange = (e: { mode: string; subMode?: string }) => { - state = { mode: e.mode, sub: e.subMode === "linewise" || e.subMode === "blockwise" ? e.subMode : null }; - queueMicrotask(() => view.dispatch({ effects: setVimInsert.of(e.mode === "insert" || e.mode === "replace") })); +const modeTracker = (ctx?: EditorDocContext) => + ViewPlugin.define((view) => { + const cm = getCM(view); + let state: VimModeState = { mode: cm?.state.vim?.insertMode ? "insert" : "normal", sub: null }; + const publish = () => { + useVimMode.setState(state); + setContext("vim.mode", state.mode); + if (ctx) reportInputMode(ctx.path, state.mode, state.sub); + }; + // Not `view.hasFocus`: that also needs the window focused, and this editor stays the last focused one. + const focused = () => view.root.activeElement === view.contentDOM; + const onModeChange = (e: { mode: string; subMode?: string }) => { + state = { mode: e.mode, sub: e.subMode === "linewise" || e.subMode === "blockwise" ? e.subMode : null }; + queueMicrotask(() => view.dispatch({ effects: setVimInsert.of(e.mode === "insert" || e.mode === "replace") })); + if (focused()) publish(); + }; + cm?.on("vim-mode-change", onModeChange); + view.contentDOM.addEventListener("focus", publish); if (focused()) publish(); - }; - cm?.on("vim-mode-change", onModeChange); - view.contentDOM.addEventListener("focus", publish); - if (focused()) publish(); - return { - destroy() { - cm?.off("vim-mode-change", onModeChange); - view.contentDOM.removeEventListener("focus", publish); - }, - }; -}); + return { + destroy() { + cm?.off("vim-mode-change", onModeChange); + view.contentDOM.removeEventListener("focus", publish); + }, + }; + }); const caret = "var(--caret, var(--fg-strong))"; @@ -237,7 +243,7 @@ const vimTheme = EditorView.theme({ }); /** Vim for one editor. Highest precedence: Vim sees keys before the editor's keymaps. */ -export function vimExtension(): Extension { +export function vimExtension(ctx?: EditorDocContext): Extension { defineExCommands(); return [ Prec.highest([ @@ -248,7 +254,7 @@ export function vimExtension(): Extension { imeTransactions, escapeClosesPopupsFirst, vim(), - modeTracker, + modeTracker(ctx), ]), imeCleanup, vimTheme, diff --git a/src/features/vim/index.ts b/src/features/vim/index.ts index 7ccdba177..c9c684f00 100644 --- a/src/features/vim/index.ts +++ b/src/features/vim/index.ts @@ -52,6 +52,7 @@ export function activate(): () => void { const gen = ++generation; setContext("vimMode", enabled); if (!enabled) { + setContext("vim.mode", ""); contribution?.(); contribution = null; return; @@ -63,7 +64,7 @@ export function activate(): () => void { id: "vim", order: 0, embedded: true, - extensions: () => e.vimExtension(), + extensions: (ctx) => e.vimExtension(ctx), }); }; @@ -117,6 +118,7 @@ export function activate(): () => void { contribution?.(); contribution = null; setContext("vimMode", false); + setContext("vim.mode", ""); disposers.reverse().forEach((d) => d()); }; } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index d630a2740..885a3f72e 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -561,5 +561,16 @@ "Show status bar": "Show status bar", "No background tasks": "No background tasks", "Status Bar Widgets": "Status Bar Widgets", - "Background Tasks": "Background Tasks" + "Background Tasks": "Background Tasks", + "Choose plugin executable": "Choose plugin executable", + "Approve plugin executable": "Approve plugin executable", + "Executable scope": "Executable scope", + "Choose executable…": "Choose executable…", + "Reset executable": "Reset executable", + "Revalidate the default executable? If it is unavailable, this permission will be revoked.": "Revalidate the default executable? If it is unavailable, this permission will be revoked.", + "Allow {name} to run {selected}? This is equivalent to running arbitrary code on this machine.": "Allow {name} to run {selected}? This is equivalent to running arbitrary code on this machine.", + "Connect to {host} over unencrypted HTTP (from the machine the project is on)": "Connect to {host} over unencrypted HTTP (from the machine the project is on)", + "Connect to local socket {path} — equivalent to running arbitrary code on the project machine": "Connect to local socket {path} — equivalent to running arbitrary code on the project machine", + "Output: {channel}": "Output: {channel}", + "You can close this tab.": "You can close this tab." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index bbe7692cd..be17c1e8d 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6904,5 +6904,16 @@ "When off, Alt key combinations still work but pressing Alt alone does not focus the main menu": "关闭后,Alt 组合键仍然可用,但单独按下 Alt 不会聚焦主菜单", "the bundle of {gemfile} has no `debug` gem. Add `gem \"debug\"` to the Gemfile and run `bundle install`": "{gemfile} 的 bundle 中没有 `debug` gem。请在 Gemfile 中添加 `gem \"debug\"`,然后运行 `bundle install`", "No background tasks": "没有后台任务", - "Status Bar Widgets": "状态栏微件" + "Status Bar Widgets": "状态栏微件", + "Choose plugin executable": "选择插件可执行文件", + "Approve plugin executable": "批准插件可执行文件", + "Executable scope": "可执行文件作用域", + "Choose executable…": "选择可执行文件…", + "Reset executable": "重置可执行文件", + "Revalidate the default executable? If it is unavailable, this permission will be revoked.": "重新验证默认可执行文件?如果不可用,将撤销此权限。", + "Allow {name} to run {selected}? This is equivalent to running arbitrary code on this machine.": "允许 {name} 运行 {selected}?这等同于在此计算机上运行任意代码。", + "Connect to {host} over unencrypted HTTP (from the machine the project is on)": "通过未加密的 HTTP 连接到 {host}(从项目所在的计算机)", + "Connect to local socket {path} — equivalent to running arbitrary code on the project machine": "连接到本地套接字 {path} — 等同于在项目所在的计算机上运行任意代码", + "Output: {channel}": "输出:{channel}", + "You can close this tab.": "你可以关闭此标签页。" } diff --git a/wit/commit.wit b/wit/commit.wit index a70b889c1..91dbe0e28 100644 --- a/wit/commit.wit +++ b/wit/commit.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// The commit being prepared in the window the current command or event came /// from (the Commit tool window, or the Commit dialog while it is open): the diff --git a/wit/details.wit b/wit/details.wit index 9e889851a..f7342991d 100644 --- a/wit/details.wit +++ b/wit/details.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// What the pane beside the Services tree shows for a plugin's node. interface detail-types { diff --git a/wit/diagnostics.wit b/wit/diagnostics.wit index d5d62de72..499335fde 100644 --- a/wit/diagnostics.wit +++ b/wit/diagnostics.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-diagnostics`): problems in the current, /// possibly unsaved document, for the languages declared with the diff --git a/wit/endpoints.wit b/wit/endpoints.wit index 95302fcb0..f4a446fe0 100644 --- a/wit/endpoints.wit +++ b/wit/endpoints.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// HTTP endpoints found in a project (`[[contributes.endpoints]]`). interface endpoints-provider { diff --git a/wit/events.wit b/wit/events.wit index 8851d18a7..f52030971 100644 --- a/wit/events.wit +++ b/wit/events.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Workbench events, delivered in batches to `event-handler.handle`. interface events { @@ -29,6 +29,9 @@ interface events { /// Delivers `kind` events from now on, for the rest of the session (also /// across idle reclaim: an event activates the plugin again). Declare /// `activation = ["on-event:<kind>"]` to get them before first use. + /// API 1.4 also delivers `file-closed` (JSON path string), `settings-changed` + /// (JSON array of the plugin's changed setting keys), and `input-mode-changed` + /// (JSON {path, mode, sub}) through `other`. The last needs `events.input`. /// Kinds: `file-opened`, `file-saved`, `files-changed` (batched disk changes /// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor /// changed), `vcs-changed` (a repository's state changed: commit, diff --git a/wit/exports.wit b/wit/exports.wit index 67d7c6060..434b29ceb 100644 --- a/wit/exports.wit +++ b/wit/exports.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; interface lifecycle { use types.{context, error}; diff --git a/wit/file-actions.wit b/wit/file-actions.wit index 477809180..12b4aec17 100644 --- a/wit/file-actions.wit +++ b/wit/file-actions.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-file-actions`): quick fixes and /// refactorings that create, rename or delete files, next to the text edits diff --git a/wit/fs.wit b/wit/fs.wit index 7cd07fd71..c1a96cf83 100644 --- a/wit/fs.wit +++ b/wit/fs.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Files outside the open projects: the configuration of the program a /// plugin integrates with, a tool installed elsewhere, a licence file. diff --git a/wit/host.wit b/wit/host.wit index 91c3e12fc..d81877524 100644 --- a/wit/host.wit +++ b/wit/host.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Writes to the IDE log, tagged with the plugin id. interface log { @@ -53,6 +53,11 @@ interface ui { /// Shows or updates the plugin's status bar item `id` in every window. set-status-item: func(id: string, item: status-item); remove-status-item: func(id: string); + /// Overrides the global item in the invoking window only (API 1.4). + /// Invalid outside a command or event of a window; removed on window close or plugin stop. + set-window-status-item: func(id: string, item: status-item) -> result<_, error>; + /// Removes this window's override, falling back to the global item. + remove-window-status-item: func(id: string) -> result<_, error>; /// Sets the plugin's context key `key`, which `when` clauses test as /// `plugin.<id>.<key>`, in the window the current command or event came /// from (every window when there is none). A window's value takes @@ -104,3 +109,22 @@ interface storage { /// Keys starting with `prefix`, sorted. keys: func(prefix: string) -> result<list<string>, error>; } + +/// Executes stable IDE action ids or `plugin.<plugin-id>.<command-id>` (API 1.4). +interface command-runner { + use types.{error}; + /// Only in commands/events of a window. Returns a plugin command's value, + /// or none for IDE actions; unknown ids are not-found. Nested calls are bounded. + execute: func(id: string, arg: option<string>) -> result<option<string>, error>; +} + +/// Per-plugin named, read-only Output tabs (API 1.4), with a 1 MiB UTF-8 ring buffer. +interface output { + use types.{error}; + /// Appends text to a channel (at most 32 channels, names 1-128 bytes). + append: func(channel: string, text: string) -> result<_, error>; + /// Clears a channel's buffer. + clear: func(channel: string) -> result<_, error>; + /// Reveals the channel in the invoking window; only commands/events of a window. + reveal: func(channel: string) -> result<_, error>; +} diff --git a/wit/hover.wit b/wit/hover.wit index a95c22758..5ddde792e 100644 --- a/wit/hover.wit +++ b/wit/hover.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-hover`): Markdown added to the hover of /// documents of the languages declared with the `hover` provider kind, diff --git a/wit/indexing.wit b/wit/indexing.wit index 4ee08d64b..227aab726 100644 --- a/wit/indexing.wit +++ b/wit/indexing.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Cross-file associations a plugin publishes for the files it declares under /// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable diff --git a/wit/inlay.wit b/wit/inlay.wit index ab00b0c9b..1098869a5 100644 --- a/wit/inlay.wit +++ b/wit/inlay.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-inlay-hints`): inline hints in documents of /// the languages declared with the `inlay-hints` provider kind, including diff --git a/wit/io.wit b/wit/io.wit index cffd883be..2ebc7a889 100644 --- a/wit/io.wit +++ b/wit/io.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Problems in files, shown in the editor and the Problems view. interface diagnostics { @@ -35,7 +35,7 @@ interface diagnostics { publish: func(path: string, diagnostics: list<diagnostic>) -> result<_, error>; } -/// HTTP(S) to the hosts granted with `net:<host>`. +/// HTTPS with `net:<host>`; unencrypted HTTP with `net.http:<host>`. interface net { use types.{error}; @@ -46,7 +46,8 @@ interface net { record request { method: string, - /// `https://…`; plain `http://` only to `localhost` / `127.0.0.1`. + /// `https://…` requires `net:<host>`. Plain `http://…` requires + /// `net.http:<host>` (API 1.4), except loopback, which uses `net:<host>`. url: string, /// `{{secret:<name>}}` in a value is replaced by the plugin's secret /// `name` on the way out (requires `secrets`); the plugin never sees it. @@ -72,6 +73,11 @@ interface net { /// OS keychain). Plugins only use them through `{{secret:<name>}}` in /// `net` requests. Requires `secrets`. interface secrets { + use types.{error}; + /// Stores a declared secret without ever exposing it back to plugin code (API 1.4). + set: func(name: string, value: string) -> result<_, error>; + /// Deletes a declared secret (API 1.4). + delete: func(name: string) -> result<_, error>; is-set: func(name: string) -> bool; } @@ -144,3 +150,38 @@ interface process { /// also ends its processes. start: func(cmd: command, cwd: option<borrow<project>>) -> result<child, error>; } + +/// Local sockets on the project machine, including the server for remote projects. +/// Requires `ipc:<path>`; host-expanded `~/`, `$TMPDIR/`, `$XDG_RUNTIME_DIR/` +/// and Windows `\\.\pipe\name` are accepted. API 1.4. +interface ipc { + use types.{error}; + /// A byte stream. At most eight per plugin; dropping closes it, as does stopping the plugin. + resource connection { + /// Writes up to 1 MiB, subject to the current call's budget and cancellation. + write: func(bytes: list<u8>) -> result<_, error>; + /// Reads up to 1 MiB; empty on EOF or timeout. Zero timeout only checks. + read: func(max-bytes: u32, timeout-ms: u32) -> result<list<u8>, error>; + /// Closes the stream; subsequent reads and writes fail. + close: func() -> result<_, error>; + } + /// Connects to an absolute Unix socket or Windows named pipe; never TCP. + connect: func(name: string) -> result<connection, error>; +} + +/// OAuth browser redirects received on the desktop, even for remote projects (API 1.4). +/// No capability needed; only commands/events of a window may use this interface. +interface auth { + use types.{error}; + /// A one-shot IPv4 loopback listener. At most two open per plugin. + resource loopback { + /// `http://127.0.0.1:<random-port>/<path>` for the authorization URL. + redirect-uri: func() -> string; + /// Returns the first matching request's raw query string, or none on timeout. + /// Waiting is excluded from the call budget. The listener serves a short + /// completion page and closes; resource drop and plugin stop also close it. + wait: func(timeout-ms: u32) -> result<option<string>, error>; + } + /// Binds 127.0.0.1 only. `path` has no query or fragment. + begin-loopback: func(path: string) -> result<loopback, error>; +} diff --git a/wit/plugin.wit b/wit/plugin.wit index 8d1451ac3..acb2a8e7a 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -8,7 +8,7 @@ /// `fs` and `workspace`, and everything else goes through the imports below, /// gated by the capabilities granted in `plugin.toml` (a missing one returns /// `error::denied`). -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; world plugin { import log; @@ -26,6 +26,10 @@ world plugin { import net; import secrets; import process; + import ipc; + import output; + import auth; + import command-runner; import views; import settings; diff --git a/wit/providers.wit b/wit/providers.wit index 317eb81d1..8c0713ec6 100644 --- a/wit/providers.wit +++ b/wit/providers.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Editor features a plugin provides for the languages it declares under /// `[[contributes.providers]]` (the host calls only declared kinds). They run diff --git a/wit/semantic.wit b/wit/semantic.wit index ec89fe405..586c324e6 100644 --- a/wit/semantic.wit +++ b/wit/semantic.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Optional export (world `plugin-semantic-tokens`): semantic colouring of /// documents of the languages declared with the `semantic-tokens` provider diff --git a/wit/types.wit b/wit/types.wit index 8114a2db0..4192e783c 100644 --- a/wit/types.wit +++ b/wit/types.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Shared types. Positions are 0-based lines and UTF-16 code unit columns, /// as in the editor and LSP. diff --git a/wit/views.wit b/wit/views.wit index 78da35354..0f3b7d498 100644 --- a/wit/views.wit +++ b/wit/views.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; /// Declarative views: tool windows declared /// under `[[contributes.views]]` and custom editors under diff --git a/wit/workspace.wit b/wit/workspace.wit index 556dd0da8..851d14d57 100644 --- a/wit/workspace.wit +++ b/wit/workspace.wit @@ -1,4 +1,4 @@ -package openidea:plugin@1.3.0; +package openidea:plugin@1.4.0; interface workspace { use types.{error, location};