diff --git a/crates/ide-extension/src/capability.rs b/crates/ide-extension/src/capability.rs index da2b2aaad8..a11374df2a 100644 --- a/crates/ide-extension/src/capability.rs +++ b/crates/ide-extension/src/capability.rs @@ -20,6 +20,8 @@ pub enum Capability { EditorWrite, /// Create and replace files inside the project root. ProjectWrite, + /// Run arbitrary IDE actions and other plugins' commands. + IdeCommands, VcsRead, VcsWrite, /// The plugin's own key-value store and data directory. @@ -70,7 +72,7 @@ impl Capability { | Self::Secrets | Self::InputEvents | Self::Clipboard => Risk::Medium, - Self::Ipc(_) | Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High, + Self::IdeCommands | Self::Ipc(_) | Self::Process(_) | Self::FsRead(_) | Self::FsWrite(_) => Risk::High, } } @@ -87,6 +89,7 @@ impl Capability { Self::EditorRead => "Read the focused editor's file and selection".into(), Self::EditorWrite => "Change text in the editor".into(), Self::ProjectWrite => "Create and change files in the open project".into(), + Self::IdeCommands => "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing".into(), Self::VcsRead => "Read version control state".into(), Self::VcsWrite => "Change version control state (commit, fetch, checkout)".into(), Self::Storage => "Store its own data".into(), @@ -213,6 +216,7 @@ impl fmt::Display for Capability { Self::EditorRead => f.write_str("editor.read"), Self::EditorWrite => f.write_str("editor.write"), Self::ProjectWrite => f.write_str("project.write"), + Self::IdeCommands => f.write_str("ide.commands"), Self::VcsRead => f.write_str("vcs.read"), Self::VcsWrite => f.write_str("vcs.write"), Self::Storage => f.write_str("storage"), @@ -284,6 +288,7 @@ impl FromStr for Capability { "editor.read" | "editor-read" => Self::EditorRead, "editor.write" | "editor-write" => Self::EditorWrite, "project.write" => Self::ProjectWrite, + "ide.commands" => Self::IdeCommands, "vcs.read" => Self::VcsRead, "vcs.write" => Self::VcsWrite, "storage" => Self::Storage, @@ -424,3 +429,18 @@ mod api14_tests { } } } + +#[cfg(test)] +mod command_tests { + use super::*; + #[test] + fn ide_commands_is_explicit_and_high_risk() { + let cap: Capability = "ide.commands".parse().unwrap(); + assert_eq!(cap, Capability::IdeCommands); + assert_eq!(cap.to_string(), "ide.commands"); + assert_eq!(cap.risk(), Risk::High); + assert!(!cap.auto_migrates()); + assert!(!Capability::VcsWrite.covers(&cap)); + assert!(!Capability::Process("git".into()).covers(&cap)); + } +} diff --git a/crates/ide-extension/src/manifest.rs b/crates/ide-extension/src/manifest.rs index d1ad752ad2..732d9b76bb 100644 --- a/crates/ide-extension/src/manifest.rs +++ b/crates/ide-extension/src/manifest.rs @@ -326,7 +326,7 @@ impl Manifest { check_relative(icon, "icon")?; } for cap in self.capabilities.required.iter().chain(&self.capabilities.optional) { - if matches!(cap, Capability::NetHttp(_) | Capability::Ipc(_)) { + if matches!(cap, Capability::IdeCommands | Capability::NetHttp(_) | Capability::Ipc(_)) { self.needs_api(&format!("capability `{cap}`"), 4)?; } if matches!(cap, Capability::ProjectWrite | Capability::FsWrite(_)) { @@ -698,3 +698,14 @@ mod api14_tests { } } } + +#[cfg(test)] +mod commands_api_tests { + use super::*; + #[test] + fn ide_commands_requires_api_1_4() { + let manifest = "id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.3\"\n[capabilities]\nrequired = [\"ide.commands\"]\n"; + assert!(Manifest::parse(manifest).unwrap_err().contains("1.4")); + assert!(Manifest::parse(&manifest.replace("^1.3", "^1.4")).is_ok()); + } +} diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index b3ab936d29..c4a35aa71a 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -99,6 +99,14 @@ pub struct Host { const EXIT_SHUTDOWN_WAIT: std::time::Duration = std::time::Duration::from_secs(10); impl Host { + /// Windows whose current project has this root. + pub(crate) fn windows_for_root(&self, root: &std::path::Path) -> Vec { + let mut windows: Vec<_> = + self.projects.read().iter().filter(|(_, p)| p.root == root).map(|(w, _)| w.clone()).collect(); + windows.sort(); + windows + } + pub fn new(config: HostConfig) -> Self { let HostConfig { config_dir, diff --git a/crates/ide-host/src/mcp/reports.rs b/crates/ide-host/src/mcp/reports.rs index 00b360e233..343ddba774 100644 --- a/crates/ide-host/src/mcp/reports.rs +++ b/crates/ide-host/src/mcp/reports.rs @@ -91,7 +91,7 @@ impl Reports { pub(super) fn focused_window(&self) -> Option { self.0.read().focused.clone() } - pub(super) fn editors(&self, windows: &[String]) -> Vec { + pub(crate) fn editors(&self, windows: &[String]) -> Vec { let state = self.0.read(); let mut paths = Vec::new(); for window in windows.iter().filter_map(|w| state.windows.get(w)) { @@ -103,10 +103,10 @@ impl Reports { } paths } - pub(super) fn focused(&self, window: &str) -> Option { + pub(crate) fn focused(&self, window: &str) -> Option { self.0.read().windows.get(window).and_then(|w| w.focused.clone()) } - pub(super) fn problems(&self, windows: &[String]) -> Vec { + pub(crate) fn problems(&self, windows: &[String]) -> Vec { let state = self.0.read(); let mut files: BTreeMap> = BTreeMap::new(); for window in windows.iter().filter_map(|w| state.windows.get(w)) { diff --git a/crates/ide-host/src/ops/search.rs b/crates/ide-host/src/ops/search.rs index ac2de11689..61d90c3455 100644 --- a/crates/ide-host/src/ops/search.rs +++ b/crates/ide-host/src/ops/search.rs @@ -34,67 +34,12 @@ pub async fn start( // Excluded roots (Project Structure marks and detected `target`, `node_modules`, …) and // ignored names are never searched. query.exclude.extend(project.search_excludes()); - let roots = project.roots(); - let set = match query.scope { - ide_search::SearchScope::FileSet { set } => Some(set), - _ => None, - }; let cancel = host.begin_request(request); - let documents = project.documents.clone(); - let root = project.root.clone(); - let workspace = ide_workspace::workspace::Workspace::load(&root)?.is_some(); - // The whole project also covers the Project Structure content roots. - let content_roots = match query.scope { - ide_search::SearchScope::Project - | ide_search::SearchScope::FileSet { .. } - | ide_search::SearchScope::Pattern { .. } => project.content_roots(), - _ => Vec::new(), - }; - let include_root = !workspace - || matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. }); - let languages = project.languages.clone(); - let syntax = host.syntax(); let events = on_event.clone(); + let syntax = host.syntax(); let summary = host .blocking(move || { - let filter = |rel: &str| match set { - Some(ProjectFileSet::Production) => !roots.is_test(rel), - Some(ProjectFileSet::Test) => roots.is_test(rel), - Some(ProjectFileSet::All) | None => true, - }; - // Comments and string literals for the search context filter. - let literals = |path: &Path, text: &str| { - let language = languages.detect(path, text.lines().next()); - let found = syntax.literals(&language, text)?; - Some(found.into_iter().map(literal_range).collect()) - }; - let mut total = SearchSummary::default(); - for dir in std::iter::once(&root).filter(|_| include_root).chain(&content_roots) { - let s = ide_search::search_in_context( - dir, - &query, - Some(&filter), - Some(&literals), - &|p| documents.search_text_of(p), - &cancel, - &|mut file| { - if dir != &root { - let name = dir.file_name().unwrap_or_default().to_string_lossy(); - file.rel_path = format!("{name}/{}", file.rel_path); - } - events(SearchEvent::File { file }); - }, - )?; - total.files += s.files; - total.matches += s.matches; - total.elapsed_ms += s.elapsed_ms; - total.limit_hit |= s.limit_hit; - total.cancelled |= s.cancelled; - if total.limit_hit || total.cancelled { - break; - } - } - Ok(total) + search_project(&project, &syntax, &query, &cancel, &|file| events(SearchEvent::File { file })) }) .await; host.end_request(request); @@ -102,5 +47,69 @@ pub async fn start( Ok(()) } +/// Shared Find in Files engine: project excludes are added by the caller. +pub(crate) fn search_project( + project: &crate::project::Project, + syntax: &ide_language::Syntax, + query: &SearchQuery, + cancel: &ide_core::CancellationToken, + emit: &(dyn Fn(FileMatches) + Sync), +) -> IdeResult { + let root = &project.root; + let roots = project.roots(); + let set = match query.scope { + ide_search::SearchScope::FileSet { set } => Some(set), + _ => None, + }; + let workspace = ide_workspace::workspace::Workspace::load(root)?.is_some(); + let include_root = !workspace + || matches!(query.scope, ide_search::SearchScope::Directory { .. } | ide_search::SearchScope::Files { .. }); + let content_roots = match query.scope { + ide_search::SearchScope::Project + | ide_search::SearchScope::FileSet { .. } + | ide_search::SearchScope::Pattern { .. } => project.content_roots(), + _ => Vec::new(), + }; + let filter = |rel: &str| match set { + Some(ProjectFileSet::Production) => !roots.is_test(rel), + Some(ProjectFileSet::Test) => roots.is_test(rel), + _ => true, + }; + let literals = |path: &Path, text: &str| { + let language = project.languages.detect(path, text.lines().next()); + Some(syntax.literals(&language, text)?.into_iter().map(literal_range).collect()) + }; + let mut total = SearchSummary::default(); + for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) { + let mut remaining = query.clone(); + let max = if query.max_matches == 0 { 10_000 } else { query.max_matches }; + remaining.max_matches = max.saturating_sub(total.matches).max(1); + let summary = ide_search::search_in_context( + dir, + &remaining, + Some(&filter), + Some(&literals), + &|p| project.documents.search_text_of(p), + cancel, + &|mut file| { + if dir != root { + let name = dir.file_name().unwrap_or_default().to_string_lossy(); + file.rel_path = format!("{name}/{}", file.rel_path); + } + emit(file); + }, + )?; + total.files += summary.files; + total.matches += summary.matches; + total.elapsed_ms += summary.elapsed_ms; + total.limit_hit |= summary.limit_hit || total.matches >= max; + total.cancelled |= summary.cancelled; + if total.limit_hit || total.cancelled { + break; + } + } + Ok(total) +} + mod commands; pub use commands::*; diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 30bc34d7c5..248e8ffcab 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -38,10 +38,38 @@ type ContextKey = (Option, String, String); /// What plugins see of the open projects; provided by the app /// ([`super::PluginHost::set_workspace`]), over [`crate::Host`] on the desktop. pub trait PluginWorkspace: Send + Sync { + /// Window-owned reports shared with the MCP tools. + fn open_editors(&self, _client: &str) -> Result, HostError> { + Ok(Vec::new()) + } + /// Shared Find in Files service, preferring the invoking window's document store. + fn search_text( + &self, + _client: Option<&str>, + _root: &Path, + _query: ide_plugin::TextQuery, + _limit: u32, + _cancel: &CancellationToken, + ) -> Result { + Err(HostError::Failed("search unavailable".into())) + } + /// Problems view reports for this window's project. + fn problems(&self, _client: &str, _path: Option<&Path>) -> Result, HostError> { + Ok(Vec::new()) + } + /// Roots of the open projects. fn projects(&self) -> Vec; /// Unsaved text of the open document at `path`. fn buffer_text(&self, path: &Path) -> Option; + /// A window's unsaved text, with the normal project overlay as fallback. + fn buffer_text_in(&self, _client: Option<&str>, path: &Path) -> Option { + self.buffer_text(path) + } + /// An editor owned by this window. + fn document_in(&self, _client: &str, path: &Path) -> Option<(u64, String)> { + self.document(path) + } /// Whether the editor holds changes for `path` that are not on disk yet; /// writing such a file would lose them. fn buffer_dirty(&self, _path: &Path) -> bool { @@ -460,6 +488,7 @@ pub(super) struct Shared { next_prompt: AtomicU64, /// (plugin, item id) → item, for windows opened later. output: Mutex>, + decorations: Mutex>>, status: Mutex>, setting_snapshots: Mutex, window_status: Mutex>, @@ -520,6 +549,7 @@ impl Shared { next_prompt: AtomicU64::new(1), status: Mutex::default(), output: Mutex::default(), + decorations: Mutex::default(), window_status: Mutex::default(), setting_snapshots: Mutex::default(), contexts: Mutex::default(), @@ -728,6 +758,9 @@ impl Shared { self.sink .emit(Some(&window), PluginEvent::WindowStatusItemChanged { plugin_id: plugin.into(), id, item: None }); } + if self.decorations.lock().remove(plugin).is_some() { + self.sink.emit(None, PluginEvent::DecorationsChanged { plugin_id: plugin.into(), sets: Vec::new() }); + } self.withdraw_prompts(plugin); let removed: Vec<(Option, String)> = { let mut contexts = self.contexts.lock(); @@ -1190,6 +1223,169 @@ fn failed(e: impl std::fmt::Display) -> HostError { } impl HostApi for PluginApi { + fn owns_command(&self, id: &str) -> bool { + let commands = self.shared.ui.items(super::COMMANDS, None); + let mut matches = commands.iter().filter(|c| id == format!("plugin.{}.{}", c.plugin_id, c.key)).peekable(); + matches.peek().is_some() && matches.all(|c| c.plugin_id == self.id()) + } + + fn open_editors(&self, client: &str) -> Result, HostError> { + self.shared.workspace().ok_or_else(|| HostError::NotFound("window project".into()))?.open_editors(client) + } + fn editor_open(&self, client: &str, path: &Path, selection: Option) -> Result<(), HostError> { + self.shared.sink.emit(Some(client), PluginEvent::EditorOpen { path: path.into(), selection }); + Ok(()) + } + fn editor_ranges( + &self, + client: &str, + path: &Path, + ranges: Vec, + reveal: bool, + ) -> Result<(), HostError> { + let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("window project".into()))?; + if !workspace.open_editors(client)?.iter().any(|e| Path::new(&e.path) == path) { + return Err(HostError::Invalid("editor does not belong to the invoking window".into())); + } + let (_, text) = + workspace.document_in(client, path).ok_or_else(|| HostError::NotFound("editor is closed".into()))?; + let document = ide_text::Document::new(&text); + for r in &ranges { + if !valid_range(&document, *r) { + return Err(HostError::Invalid("range outside document".into())); + } + } + self.shared.sink.emit(Some(client), PluginEvent::EditorRanges { path: path.into(), ranges, reveal }); + Ok(()) + } + fn search_text( + &self, + client: Option<&str>, + root: &Path, + query: ide_plugin::TextQuery, + limit: u32, + cancel: &CancellationToken, + deadline: Instant, + ) -> Result { + let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("project closed".into()))?; + if query.pattern.len() > 16_384 || query.include.len() + query.exclude.len() > 256 { + return Err(HostError::Invalid("search query too large".into())); + } + let token = cancel.child_token(); + let timed = token.clone(); + let (done, wait) = std::sync::mpsc::channel(); + let timer = std::thread::spawn(move || { + if wait.recv_timeout(deadline.saturating_duration_since(Instant::now())).is_err() { + timed.cancel(); + } + }); + let result = workspace.search_text(client, root, query, limit.min(10_000), &token); + let _ = done.send(()); + let _ = timer.join(); + if cancel.is_cancelled() { + Err(HostError::Cancelled) + } else if Instant::now() >= deadline { + Err(HostError::Failed("text search timed out".into())) + } else { + result + } + } + fn problems(&self, client: &str, path: Option<&Path>) -> Result, HostError> { + self.shared.workspace().ok_or_else(|| HostError::NotFound("window project".into()))?.problems(client, path) + } + fn decorations(&self, path: Option<&Path>, set: &str, items: Vec) -> Result<(), HostError> { + self.set_decorations(path, set, items, None, false) + } + fn file_decorations( + &self, + path: Option<&Path>, + set: &str, + item: Option, + ) -> Result<(), HostError> { + self.set_decorations(path, set, Vec::new(), item, true) + } + fn vcs_log( + &self, + root: &Path, + path: Option<&str>, + limit: u32, + cancel: &CancellationToken, + ) -> Result, HostError> { + let repo = self.read_repo(root)?; + let path = path + .map(|p| ide_plugin::resolve_new_in_root(root, p).map(ide_core::IpcPath::from).map_err(HostError::Invalid)) + .transpose()?; + let Some(repo) = repo else { + return Ok(Vec::new()); + }; + if limit == 0 { + return Ok(Vec::new()); + } + let query = ide_vcs::LogQuery { path, limit: limit.min(1000), ..Default::default() }; + repo.log_cancellable(&query, cancel) + .map(|cs| { + cs.into_iter() + .map(|c| ide_plugin::CommitInfo { + id: c.id, + short_id: c.short_id, + author: c.author, + author_email: c.email, + date: (c.time_ms / 1000.0) as i64, + subject: c.summary, + body: c + .message + .split_once('\n') + .map_or(String::new(), |(_, body)| body.trim_start_matches('\n').into()), + parents: c.parents, + }) + .collect() + }) + .map_err(failed) + } + fn vcs_blame( + &self, + client: Option<&str>, + root: &Path, + path: &str, + ) -> Result, HostError> { + let repo = self.read_repo(root)?; + let path = ide_plugin::resolve_new_in_root(root, path).map_err(HostError::Invalid)?; + let Some(repo) = repo else { + return Ok(Vec::new()); + }; + let workspace = self.shared.workspace().unwrap(); + let text = workspace.buffer_text_in(client, &path); + repo.blame(&path, text.as_deref(), None, workspace.vcs_encoding(&path)) + .map(|lines| { + lines + .into_iter() + .enumerate() + .map(|(i, l)| ide_plugin::BlameLine { + line: i as u32, + commit: l.commit, + author: l.author, + date: (l.time_ms / 1000.0) as i64, + summary: l.summary, + }) + .collect() + }) + .map_err(failed) + } + fn vcs_diff( + &self, + root: &Path, + path: Option<&str>, + against: Option<&str>, + cancel: &CancellationToken, + ) -> Result, HostError> { + let repo = self.read_repo(root)?; + let path = path.map(|p| ide_plugin::resolve_new_in_root(root, p).map_err(HostError::Invalid)).transpose()?; + let Some(repo) = repo else { + return Ok(None); + }; + repo.working_tree_patch(path.as_deref(), against, 4 << 20, cancel).map(Some).map_err(failed) + } + fn execute_command( &self, invocation: &ide_plugin::Invocation, @@ -2264,6 +2460,13 @@ fn not_writable(path: &Path, e: ide_core::error::IdeError) -> HostError { pub struct HostWorkspace(pub std::sync::Weak); impl HostWorkspace { + fn project_for(&self, client: Option<&str>, root: &Path) -> Option> { + let host = self.0.upgrade()?; + client + .and_then(|w| host.project(w).ok()) + .filter(|p| p.root == root) + .or_else(|| host.windows_for_root(root).first().and_then(|w| host.project(w).ok())) + } fn projects(&self) -> Vec> { self.0.upgrade().map(|h| h.projects()).unwrap_or_default() } @@ -2275,6 +2478,146 @@ impl HostWorkspace { } impl PluginWorkspace for HostWorkspace { + fn buffer_text_in(&self, client: Option<&str>, path: &Path) -> Option { + client + .and_then(|w| self.0.upgrade()?.project(w).ok()?.documents.text_of(path)) + .or_else(|| self.buffer_text(path)) + } + fn document_in(&self, client: &str, path: &Path) -> Option<(u64, String)> { + let project = self.0.upgrade()?.project(client).ok()?; + let doc = project.documents.by_path(path)?; + let snapshot = project.documents.snapshot(doc).ok()?; + Some((u64::from(snapshot.version), snapshot.text)) + } + fn open_editors(&self, client: &str) -> Result, HostError> { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let project = host.project(client).map_err(failed)?; + let active = host.mcp_reports.focused(client).map(|e| e.path.into_path_buf()); + Ok(host + .mcp_reports + .editors(&[client.into()]) + .into_iter() + .map(|path| { + let language = project + .languages + .detect(&path, project.documents.text_of(&path).as_deref().and_then(|t| t.lines().next())); + ide_plugin::OpenEditor { + active: active.as_ref() == Some(&path), + dirty: project + .documents + .by_path(&path) + .is_some_and(|doc| project.documents.is_dirty(doc).unwrap_or(false)), + language: language.to_string(), + path: to_ipc(&path), + } + }) + .collect()) + } + fn search_text( + &self, + client: Option<&str>, + root: &Path, + query: ide_plugin::TextQuery, + limit: u32, + cancel: &CancellationToken, + ) -> Result { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let project = self.project_for(client, root).ok_or_else(|| HostError::NotFound("project closed".into()))?; + if limit == 0 { + return Ok(ide_plugin::TextSearch::default()); + } + let mut query = ide_search::SearchQuery { + pattern: query.pattern, + is_regex: query.regex, + case_sensitive: query.case_sensitive, + whole_word: query.whole_word, + include: query.include, + exclude: query.exclude, + scope: ide_search::SearchScope::Project, + max_matches: limit.min(10_000).saturating_add(1), + context: Default::default(), + }; + query.exclude.extend(project.search_excludes()); + let files = Mutex::new(Vec::new()); + let summary = crate::ops::search::search_project(&project, &host.syntax(), &query, cancel, &|file| { + files.lock().push(file) + }) + .map_err(failed)?; + if summary.cancelled || cancel.is_cancelled() { + return Err(HostError::Cancelled); + } + let mut out = ide_plugin::TextSearch { matches: Vec::new(), limit_hit: summary.limit_hit }; + let mut bytes = 0usize; + for file in files.into_inner() { + if cancel.is_cancelled() { + return Err(HostError::Cancelled); + } + // Restrict project.read to the project root, including symlink targets. + let Ok(path) = ide_plugin::resolve_in_root(root, &to_ipc(&file.path.0)) else { + continue; + }; + let text = project.documents.text_of(&path).or_else(|| { + let loaded = project.documents.load_file_bounded(&path, ide_plugin::MAX_READ_BYTES as usize).ok()?; + (!loaded.binary && !loaded.too_large) + .then(|| ide_text::normalize_line_endings(&loaded.text).into_owned()) + }); + let Some(text) = text else { + out.limit_hit = true; + continue; + }; + let doc = ide_text::Document::new(&text); + for (start, end) in ide_search::match_ranges(&text, &query).map_err(failed)? { + if out.matches.len() >= limit as usize { + out.limit_hit = true; + return Ok(out); + } + let range = ide_core::Range::new(doc.byte_to_pos(start), doc.byte_to_pos(end)); + let line = text[..start].rfind('\n').map_or(0, |i| i + 1); + let end_line = text[start..].find('\n').map_or(text.len(), |i| start + i); + let preview = text[line..end_line].trim_end_matches('\r'); + let mut cut = preview.len().min(4096); + while !preview.is_char_boundary(cut) { + cut -= 1; + } + let preview = &preview[..cut]; + bytes += preview.len() + path.as_os_str().len() + 64; + if bytes > 4 << 20 { + out.limit_hit = true; + return Ok(out); + } + out.matches.push(ide_plugin::TextMatch { + location: ide_plugin::Location { path: path.clone(), range }, + line: preview.into(), + }); + } + } + Ok(out) + } + fn problems(&self, client: &str, path: Option<&Path>) -> Result, HostError> { + let host = self.0.upgrade().ok_or(HostError::Cancelled)?; + let root = host.project(client).map_err(failed)?.root.clone(); + let windows = host.windows_for_root(&root); + let mut out = Vec::new(); + for file in host.mcp_reports.problems(&windows) { + if path.is_some_and(|p| p != file.path.0) { + continue; + } + if ide_plugin::resolve_new_in_root(&root, &to_ipc(&file.path.0)).is_err() { + continue; + } + let mut sources: BTreeMap> = BTreeMap::new(); + for d in file.items { + sources.entry(d.server.clone().or_else(|| d.source.clone()).unwrap_or_default()).or_default().push(d); + } + out.extend(sources.into_iter().map(|(source, diagnostics)| ide_plugin::FileProblems { + path: to_ipc(&file.path.0), + source, + diagnostics, + })); + } + Ok(out) + } + fn projects(&self) -> Vec { let mut roots: Vec = HostWorkspace::projects(self).iter().map(|p| p.root.clone()).collect(); roots.sort(); @@ -2871,3 +3214,309 @@ mod credential_tests { assert_eq!(from_window(Some("main"), "open a URL").unwrap(), "main"); } } + +fn valid_range(document: &ide_text::Document, range: ide_core::Range) -> bool { + range.start <= range.end + && [range.start, range.end].into_iter().all(|pos| document.byte_to_pos(document.pos_to_byte(pos)) == pos) +} + +impl PluginApi { + fn read_repo(&self, root: &Path) -> Result, HostError> { + if !self.shared.workspace().is_some_and(|w| w.trusted(root)) { + return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into())); + } + let repo = ide_vcs::Repo::discover(root).map_err(failed)?; + if let Some(repo) = &repo { + repo.set_execution_allowed(false); + } + Ok(repo) + } + fn set_decorations( + &self, + path: Option<&Path>, + set: &str, + mut items: Vec, + file: Option, + tree: bool, + ) -> Result<(), HostError> { + if set.is_empty() || set.len() > 128 { + return Err(HostError::Invalid("set id must be 1-128 bytes".into())); + } + if items.len() > 10_000 || file.as_ref().and_then(|f| f.badge.as_ref()).is_some_and(|b| b.chars().count() > 2) { + return Err(HostError::Invalid("decoration limit exceeded".into())); + } + items.retain(|d| decoration_style(&d.style)); + if items.iter().any(|d| d.range.start > d.range.end) { + return Err(HostError::Invalid("reversed decoration range".into())); + } + let replacement = if let Some(path) = path { + let workspace = self.shared.workspace().ok_or_else(|| HostError::NotFound("no project open".into()))?; + let (root, real) = workspace + .projects() + .into_iter() + .filter_map(|root| ide_plugin::resolve_new_in_root(&root, &to_ipc(path)).ok().map(|real| (root, real))) + .max_by_key(|(root, _)| root.components().count()) + .ok_or_else(|| HostError::Invalid("path outside open projects".into()))?; + Some(super::DecorationSet { + root: root.into(), + path: real.into(), + set_id: set.into(), + tree, + items, + file: file.filter(|f| decoration_style(&f.style)), + }) + } else { + None + }; + let mut all = self.shared.decorations.lock(); + let mut sets = all.get(self.id()).cloned().unwrap_or_default(); + sets.retain(|s| !(s.tree == tree && s.set_id == set && replacement.as_ref().is_none_or(|r| r.path == s.path))); + if let Some(replacement) = replacement { + sets.push(replacement); + } + let names: BTreeSet<_> = sets.iter().filter(|s| s.tree == tree).map(|s| &s.set_id).collect(); + if names.len() > 50 || serde_json::to_vec(&sets).map_err(failed)?.len() > 4 << 20 { + return Err(HostError::Invalid("decoration sets exceed plugin limits".into())); + } + // A plugin may spread one file's annotations across sets, but the combined limit is fixed. + let mut counts = BTreeMap::new(); + for s in &sets { + *counts.entry(&s.path).or_insert(0usize) += s.items.len(); + } + if counts.values().any(|n| *n > 10_000) { + return Err(HostError::Invalid("at most 10000 decorations per file".into())); + } + all.insert(self.id().into(), sets.clone()); + // Emit while holding the state lock so replacement snapshots cannot arrive out of order. + self.shared.sink.emit(None, PluginEvent::DecorationsChanged { plugin_id: self.id().into(), sets }); + Ok(()) + } +} +fn decoration_style(style: &str) -> bool { + matches!( + style, + "highlight" + | "search" + | "added" + | "modified" + | "removed" + | "warning" + | "error" + | "info" + | "underline" + | "strikethrough" + | "muted" + ) +} +impl Shared { + pub(super) fn decoration_sets(&self) -> BTreeMap> { + self.decorations.lock().clone() + } +} + +#[cfg(test)] +mod workbench_tests { + use super::*; + struct Workspace { + root: PathBuf, + trusted: bool, + text: Option, + } + impl PluginWorkspace for Workspace { + fn projects(&self) -> Vec { + vec![self.root.clone()] + } + fn buffer_text(&self, _: &Path) -> Option { + self.text.clone() + } + fn document(&self, _: &Path) -> Option<(u64, String)> { + self.text.clone().map(|s| (1, s)) + } + fn apply_edits(&self, _: &Path, _: u64, _: &[TextEdit]) -> Result { + Err(HostError::Stale) + } + fn trusted(&self, _: &Path) -> bool { + self.trusted + } + fn project_of(&self, _: &str) -> Option { + Some(self.root.clone()) + } + fn publish_diagnostics(&self, _: &str, _: &Path, _: Vec) -> Result<(), HostError> { + Ok(()) + } + fn open_editors(&self, client: &str) -> Result, HostError> { + Ok(if client == "main" { + vec![ide_plugin::OpenEditor { + path: to_ipc(&self.root.join("a.txt")), + language: "text".into(), + active: true, + dirty: true, + }] + } else { + Vec::new() + }) + } + } + fn api(root: &Path, trusted: bool, text: Option<&str>) -> PluginApi { + let manifest = ide_extension::Manifest::parse( + "id = \"test\"\nname = \"Test\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.4\"\n", + ) + .unwrap(); + let shared = Shared::new( + Arc::new(|_: Option<&str>, _: PluginEvent| {}), + root.join(".data"), + Arc::default(), + ide_extension::UiStore::new(), + ); + *shared.workspace.write() = + Some(Arc::new(Workspace { root: root.into(), trusted, text: text.map(str::to_owned) })); + PluginApi { pkg: Package::new(manifest, root.into()), shared } + } + #[test] + fn command_exemption_requires_a_declared_unambiguous_owner() { + let dir = tempfile::tempdir().unwrap(); + let api = api(dir.path(), true, None); + let own = api.shared.ui.insert(ide_extension::UiContribution { + plugin_id: "test".into(), + point: super::super::COMMANDS.into(), + key: "other.run".into(), + decl: serde_json::json!({}), + }); + assert!(api.owns_command("plugin.test.other.run")); + assert!(!api.owns_command("plugin.test.unknown")); + let other = api.shared.ui.insert(ide_extension::UiContribution { + plugin_id: "test.other".into(), + point: super::super::COMMANDS.into(), + key: "run".into(), + decl: serde_json::json!({}), + }); + assert!(!api.owns_command("plugin.test.other.run")); + drop(other); + assert!(api.owns_command("plugin.test.other.run")); + drop(own); + } + #[test] + fn selections_validate_window_and_utf16_without_requiring_a_grant() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let path = root.join("a.txt"); + let api = api(&root, true, Some("😀abc")); + let range = |col| ide_core::Range::point(ide_core::Pos::new(0, col)); + assert!(api.editor_ranges("main", &path, vec![range(2)], false).is_ok()); + assert!(api.editor_ranges("main", &path, vec![range(1)], true).is_err()); + assert!(api.editor_ranges("other", &path, vec![range(2)], false).is_err()); + } + #[test] + fn decoration_sets_validate_paths_limits_and_cleanup() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + let path = root.join("a.txt"); + std::fs::write(&path, "text").unwrap(); + let api = api(&root, true, None); + let item = |style: &str| ide_plugin::Decoration { + range: ide_core::Range::default(), + style: style.into(), + hover: None, + after: Some("after".into()), + }; + api.decorations(Some(&path), "set", vec![item("highlight"), item("unknown")]).unwrap(); + assert_eq!(api.shared.decoration_sets()["test"][0].items.len(), 1); + assert!(api.decorations(Some(&root.join("../outside.txt")), "set", vec![]).is_err()); + api.decorations(None, "set", vec![]).unwrap(); + for i in 0..50 { + api.decorations(Some(&path), &format!("s{i}"), vec![]).unwrap(); + } + assert!(api.decorations(Some(&path), "overflow", vec![]).is_err()); + api.decorations(Some(&path), "s0", vec![item("info"); 10_000]).unwrap(); + assert!(api.decorations(Some(&path), "s1", vec![item("info")]).is_err()); + assert!( + api.file_decorations( + Some(&path), + "tree", + Some(ide_plugin::FileDecoration { badge: Some("abc".into()), style: "info".into(), tooltip: None }) + ) + .is_err() + ); + api.shared.clear_plugin("test", true); + assert!(api.shared.decoration_sets().is_empty()); + } + fn git(root: &Path, args: &[&str]) { + let out = StdCommand::new("git").current_dir(root).args(args).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + } + #[test] + fn vcs_reads_reuse_history_and_dirty_blame_and_require_trust() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + git(&root, &["init", "-q"]); + git(&root, &["config", "user.name", "Test"]); + git(&root, &["config", "user.email", "test@example.com"]); + let path = root.join("a.txt"); + std::fs::write(&path, "committed\nsecond\n").unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "-qm", "Subject\n\nBody"]); + std::fs::write(&path, "disk\nsecond\n").unwrap(); + let api = api(&root, true, Some("unsaved\nsecond\nnew\n")); + let cancel = CancellationToken::new(); + let history = api.vcs_log(&root, Some("a.txt"), 10, &cancel).unwrap(); + assert_eq!(history.len(), 1); + assert_eq!(history[0].subject, "Subject"); + assert_eq!(history[0].body.trim(), "Body"); + assert!(history[0].date > 0); + let lines = api.vcs_blame(None, &root, "a.txt").unwrap(); + assert_eq!(lines.len(), 3); + assert!(lines[0].commit.bytes().all(|b| b == b'0')); + assert_eq!(lines[1].commit, history[0].id); + assert_eq!(lines[2].line, 2); + let patch = api.vcs_diff(&root, Some("a.txt"), None, &cancel).unwrap().unwrap(); + assert!(patch.contains("+disk")); + assert!(!patch.contains("+unsaved")); + assert!(api.vcs_diff(&root, None, Some("--output=outside"), &cancel).is_err()); + assert!(api.vcs_log(&root, Some("../outside"), 1, &cancel).is_err()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(api.vcs_log(&root, Some("a.txt"), 10, &cancel).unwrap().len(), 1); + assert!(api.vcs_diff(&root, Some("a.txt"), None, &cancel).unwrap().unwrap().contains("-committed")); + let restricted = super::workbench_tests::api(&root, false, None); + assert!(restricted.vcs_log(&root, None, 1, &cancel).is_err()); + assert!(restricted.vcs_blame(None, &root, "a.txt").is_err()); + assert!(restricted.vcs_diff(&root, None, None, &cancel).is_err()); + std::fs::write(&path, "x".repeat(5 << 20)).unwrap(); + assert!(api.vcs_diff(&root, None, None, &cancel).is_err()); + } + #[cfg(unix)] + #[test] + fn vcs_reads_never_run_repository_configured_helpers() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().canonicalize().unwrap(); + git(&root, &["init", "-q"]); + git(&root, &["config", "user.name", "Test"]); + git(&root, &["config", "user.email", "test@example.com"]); + std::fs::write(root.join("a.txt"), "base\n").unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "-qm", "base"]); + let marker = root.join("HELPER-RAN"); + let helper = format!("touch '{}'", marker.display()); + for key in [ + "core.fsmonitor", + "diff.external", + "diff.test.command", + "diff.test.textconv", + "filter.test.clean", + "filter.test.process", + ] { + git(&root, &["config", key, &helper]); + } + git(&root, &["config", "filter.test.required", "true"]); + assert!(!marker.exists(), "setup ran helper"); + std::fs::write(root.join(".gitattributes"), "*.txt diff=test filter=test\n").unwrap(); + std::fs::write(root.join("a.txt"), "changed\n").unwrap(); + let api = api(&root, true, Some("unsaved\n")); + let cancel = CancellationToken::new(); + api.vcs_log(&root, None, 10, &cancel).unwrap(); + assert!(!marker.exists(), "log ran helper"); + api.vcs_blame(None, &root, "a.txt").unwrap(); + assert!(!marker.exists(), "blame ran helper"); + api.vcs_diff(&root, None, None, &cancel).unwrap(); + assert!(!marker.exists()); + } +} diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index f8040e2af3..f55005216d 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -412,6 +412,11 @@ struct PendingUpdate { } impl PluginHost { + /// Current decoration snapshots for windows opening after a plugin published them. + pub fn decoration_sets(&self) -> std::collections::BTreeMap> { + self.shared.decoration_sets() + } + /// Creates the host; call [`load_all`](Self::load_all) to load installed plugins. pub fn new(plugins_dir: PathBuf, sink: Arc, limits: Limits) -> IdeResult { std::fs::create_dir_all(&plugins_dir)?; diff --git a/crates/ide-host/src/plugins/remote_host.rs b/crates/ide-host/src/plugins/remote_host.rs index b1818edb79..37e681f351 100644 --- a/crates/ide-host/src/plugins/remote_host.rs +++ b/crates/ide-host/src/plugins/remote_host.rs @@ -131,7 +131,10 @@ pub fn package_digest(dir: &Path, files: &[PathBuf]) -> IdeResult { pub fn forwarded(event: &PluginEvent) -> bool { matches!( event, - PluginEvent::Notification { .. } + PluginEvent::DecorationsChanged { .. } + | PluginEvent::EditorOpen { .. } + | PluginEvent::EditorRanges { .. } + | PluginEvent::Notification { .. } | PluginEvent::StatusItemChanged { .. } | PluginEvent::WindowStatusItemChanged { .. } | PluginEvent::ExecuteCommand { .. } @@ -528,6 +531,22 @@ impl RemotePlugins { .await } }); + d.add("mcp_set_open_editors", |c| async move { + let paths: Vec = c.arg("paths")?; + c.host.project(&c.window)?; + c.host.mcp_reports.set_open_editors(&c.window, paths.into_iter().map(PathBuf::from).collect()); + Ok(()) + }); + d.add("mcp_set_focused_editor", |c| async move { + c.host.project(&c.window)?; + c.host.mcp_reports.set_focused_editor(&c.window, c.arg("editor")?, c.arg("focused")?); + Ok(()) + }); + let h = host.clone(); + d.add("plugin_decoration_sets", move |_c| { + let h = h.clone(); + async move { Ok(alive(&h)?.decoration_sets()) } + }); let h = host.clone(); d.add("plugin_set_active_file", move |c| { let h = h.clone(); diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index cf28a960a7..9af9e482b6 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -166,6 +166,13 @@ pub struct PluginUpdate { pub enum PluginEvent { /// Plugins, their status or their contributions changed: re-fetch `plugin_list`. CommandsChanged, + /// Complete replacement of one plugin's project-scoped decorations. + #[serde(rename_all = "camelCase")] + DecorationsChanged { plugin_id: String, sets: Vec }, + /// Open a file in the invoking window. + EditorOpen { path: ide_core::IpcPath, selection: Option }, + /// Change selection or scrolling only in this window's already open editor. + EditorRanges { path: ide_core::IpcPath, ranges: Vec, reveal: bool }, /// A bounded output channel snapshot, or withdrawal when the plugin stops. #[serde(rename_all = "camelCase")] OutputChanged { plugin_id: String, channel: String, text: Option }, @@ -411,3 +418,15 @@ pub enum CommandAnswer { NotFound, Failed(String), } + +/// A plugin-owned editor or project-tree decoration set for one file. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct DecorationSet { + pub root: ide_core::IpcPath, + pub path: ide_core::IpcPath, + pub set_id: String, + pub tree: bool, + pub items: Vec, + pub file: Option, +} diff --git a/crates/ide-host/tests/plugin_workbench.rs b/crates/ide-host/tests/plugin_workbench.rs new file mode 100644 index 0000000000..d0bcce28c0 --- /dev/null +++ b/crates/ide-host/tests/plugin_workbench.rs @@ -0,0 +1,187 @@ +use ide_core::{CancellationToken, Diagnostic, Pos, Range, Severity}; +use ide_host::plugins::{HostWorkspace, PluginWorkspace}; +use ide_host::{Host, HostConfig}; +use ide_plugin::TextQuery; +use std::path::PathBuf; +use std::sync::Arc; + +struct Harness { + host: Arc, + root: PathBuf, + _tmp: tempfile::TempDir, +} +impl Harness { + fn new() -> Self { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap().join("project"); + std::fs::create_dir_all(&root).unwrap(); + let host = Arc::new(Host::new(HostConfig { + config_dir: tmp.path().join("config"), + data_dir: tmp.path().join("data"), + local_data_dir: tmp.path().join("local"), + languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: Arc::default(), + sink_for: Box::new(|_| Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + })); + host.open_project("main", &root).unwrap(); + host.open_project("second", &root).unwrap(); + Self { host, root, _tmp: tmp } + } + fn workspace(&self) -> HostWorkspace { + HostWorkspace(Arc::downgrade(&self.host)) + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn window_editor_reports_use_document_language_dirty_state_and_focus() { + let f = Harness::new(); + let path = f.root.join("main.rs"); + std::fs::write(&path, "fn main() {}\n").unwrap(); + let p = f.host.project("main").unwrap(); + let doc = p.documents.open(&path).unwrap(); + p.documents + .apply_edits(doc.id, &[ide_core::TextEdit { range: Range::default(), new_text: "// unsaved\n".into() }]) + .unwrap(); + f.host.mcp_reports.set_open_editors("main", vec![path.clone()]); + f.host.mcp_reports.set_focused_editor( + "main", + Some(ide_host::mcp::FocusedEditor { + path: path.clone().into(), + selection: Range::default(), + selected_text: String::new(), + }), + true, + ); + let workspace = f.workspace(); + let editors = workspace.open_editors("main").unwrap(); + assert_eq!(editors.len(), 1); + assert!(editors[0].dirty && editors[0].active); + assert_eq!(editors[0].language, "rust"); + assert!(workspace.open_editors("second").unwrap().is_empty()); + let second = f.host.project("second").unwrap(); + second.documents.open(&path).unwrap(); + f.host.mcp_reports.set_open_editors("second", vec![path.clone()]); + assert!(!workspace.open_editors("second").unwrap()[0].dirty); + assert!(workspace.open_editors("main").unwrap()[0].dirty); + assert!(workspace.buffer_text_in(Some("main"), &path).unwrap().contains("unsaved")); + assert!(!workspace.buffer_text_in(Some("second"), &path).unwrap().contains("unsaved")); + assert_ne!(workspace.document_in("main", &path), workspace.document_in("second", &path)); + f.host.mcp_reports.forget_window("main"); + assert!(workspace.open_editors("main").unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn text_search_uses_overlay_excludes_utf16_and_limits() { + let f = Harness::new(); + let path = f.root.join("a.txt"); + std::fs::write(&path, "disk\n").unwrap(); + std::fs::create_dir(f.root.join("target")).unwrap(); + std::fs::write(f.root.join("target/ignored.txt"), "needle").unwrap(); + let p = f.host.project("main").unwrap(); + p.settings + .set(ide_workspace::settings::SettingsScope::Project, "files.ignoredNames", serde_json::json!(["target"])) + .unwrap(); + let doc = p.documents.open(&path).unwrap(); + p.documents + .apply_edits(doc.id, &[ide_core::TextEdit { range: Range::default(), new_text: "😀needle\nneedle\n".into() }]) + .unwrap(); + f.host.project("second").unwrap().documents.open(&path).unwrap(); + let workspace = f.workspace(); + let query = TextQuery { pattern: "needle".into(), case_sensitive: true, ..Default::default() }; + let found = workspace.search_text(Some("main"), &f.root, query.clone(), 10, &CancellationToken::new()).unwrap(); + assert_eq!(found.matches.len(), 2, "{found:?}; text={:?}", workspace.buffer_text(&path)); + assert_eq!(found.matches[0].location.range, Range::new(Pos::new(0, 2), Pos::new(0, 8))); + assert!(found.matches.iter().all(|m| m.location.path == path)); + let only_file = TextQuery { include: vec!["a.txt".into()], ..query.clone() }; + assert!( + workspace + .search_text(Some("second"), &f.root, only_file, 10, &CancellationToken::new()) + .unwrap() + .matches + .is_empty() + ); + let capped = workspace.search_text(Some("main"), &f.root, query.clone(), 1, &CancellationToken::new()).unwrap(); + assert_eq!(capped.matches.len(), 1); + assert!(capped.limit_hit); + let excluded = TextQuery { exclude: vec!["*.txt".into()], ..query.clone() }; + assert!( + workspace + .search_text(Some("main"), &f.root, excluded, 10, &CancellationToken::new()) + .unwrap() + .matches + .is_empty() + ); + for query in [ + TextQuery { pattern: "NEEDLE".into(), case_sensitive: true, ..Default::default() }, + TextQuery { pattern: "need".into(), whole_word: true, ..Default::default() }, + TextQuery { include: vec!["*.rs".into()], ..query.clone() }, + ] { + assert!( + workspace + .search_text(Some("main"), &f.root, query, 10, &CancellationToken::new()) + .unwrap() + .matches + .is_empty() + ); + } + let multiline = TextQuery { pattern: "needle\nneedle".into(), regex: true, ..Default::default() }; + let found = workspace.search_text(Some("main"), &f.root, multiline, 10, &CancellationToken::new()).unwrap(); + assert_eq!(found.matches[0].location.range, Range::new(Pos::new(0, 2), Pos::new(1, 6))); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert!(matches!( + workspace.search_text(Some("main"), &f.root, query, 10, &cancelled), + Err(ide_plugin::HostError::Cancelled) + )); +} + +#[tokio::test(flavor = "multi_thread")] +async fn problems_share_project_reports_and_keep_sources_separate() { + let f = Harness::new(); + let path = f.root.join("a.txt"); + std::fs::write(&path, "text").unwrap(); + let diagnostic = |source: &str| Diagnostic { + range: Range::default(), + severity: Severity::Warning, + message: source.into(), + source: Some(source.into()), + code: None, + unnecessary: false, + deprecated: false, + server: None, + }; + f.host.mcp_reports.report_problems( + "second", + true, + vec![ide_host::mcp::FileProblems { + path: path.clone().into(), + items: vec![diagnostic("lsp"), diagnostic("plugin")], + }], + ); + let workspace = f.workspace(); + let files = workspace.problems("main", Some(&path)).unwrap(); + assert_eq!(files.len(), 2); + assert!(files.iter().all(|f| f.diagnostics.len() == 1)); + assert!(workspace.problems("main", Some(&f.root.join("other.txt"))).unwrap().is_empty()); + f.host.mcp_reports.forget_window("second"); + assert!(workspace.problems("main", None).unwrap().is_empty()); +} + +#[tokio::test(flavor = "multi_thread")] +async fn search_decodes_closed_documents_the_same_way_as_the_editor() { + let f = Harness::new(); + let path = f.root.join("utf16.txt"); + let mut bytes = vec![0xff, 0xfe]; + for unit in "😀needle\r\n".encode_utf16() { + bytes.extend_from_slice(&unit.to_le_bytes()); + } + std::fs::write(&path, bytes).unwrap(); + let query = TextQuery { pattern: "needle".into(), ..Default::default() }; + let result = f.workspace().search_text(Some("main"), &f.root, query, 10, &CancellationToken::new()).unwrap(); + assert_eq!(result.matches.len(), 1); + assert_eq!(result.matches[0].location.range, Range::new(Pos::new(0, 2), Pos::new(0, 8))); + assert_eq!(result.matches[0].line, "😀needle"); +} diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index b02ac264e9..f1928e970f 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -5649,6 +5649,20 @@ 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 [ + ("execute", "test.action", "ide.commands"), + ("execute", "plugin.other.run", "ide.commands"), + ("execute", "plugin.api14.other.run", "ide.commands"), + ("open-editors", "", "editor.read"), + ("open-editor", "a.txt", "project.read"), + ("search-text", "needle", "project.read"), + ("problems", "", "project.read"), + ("decorations", "a.txt", "project.read"), + ("clear-decorations", "", "project.read"), + ("file-decoration", "a.txt", "project.read"), + ("clear-file-decorations", "", "project.read"), + ("vcs-log", "", "vcs.read"), + ("vcs-blame", "a.txt", "vcs.read"), + ("vcs-diff", "", "vcs.read"), ("ipc", "/tmp/api14-no-grant", "ipc:"), ("fetch", "http://example.com/", "net.http:"), ("secret", "value", "secrets"), @@ -5661,6 +5675,8 @@ fn api14_denies_new_privileges_and_requires_an_invoking_window() { let error = f.host.run_command("api14", command, Some("value"), Invocation::default()).unwrap_err(); assert_eq!(error.kind, ErrorKind::InvalidInput, "{command}: {error:?}"); } + let own = f.run("api14", "execute", Some("plugin.api14.execute")).unwrap_err(); + assert!(own.contains("recursive") && !own.contains("not granted"), "{own}"); 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())); diff --git a/crates/ide-host/tests/remote_plugins.rs b/crates/ide-host/tests/remote_plugins.rs index 71784ca248..3c8fcef5ff 100644 --- a/crates/ide-host/tests/remote_plugins.rs +++ b/crates/ide-host/tests/remote_plugins.rs @@ -407,6 +407,25 @@ async fn api14_remote_calls_keep_browser_listeners_and_secrets_on_the_desktop() 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 }); + let remote_file = project.join("remote.txt"); + std::fs::write(&remote_file, "remote text").unwrap(); + invoke(&peer, "mcp_set_open_editors", json!({"paths": [remote_file]})).await.unwrap(); + invoke(&peer, "mcp_set_focused_editor", json!({"editor": {"path": remote_file, "selection": {"start": {"line": 0, "col": 0}, "end": {"line": 0, "col": 0}}, "selectedText": ""}, "focused": true})).await.unwrap(); + let editors = invoke(&peer, "plugin_run_command", run("open-editors", None)).await.unwrap(); + assert!(editors.as_str().unwrap().contains("remote.txt")); + assert!(editors.as_str().unwrap().contains("active: true")); + let problems = invoke(&peer, "plugin_run_command", run("problems", None)).await.unwrap(); + assert_eq!(problems.as_str(), Some("[]")); + invoke(&peer, "plugin_run_command", run("open-editor", Some("remote.txt"))).await.unwrap(); + invoke(&peer, "plugin_run_command", run("decorations", remote_file.to_str())).await.unwrap(); + let sets = invoke(&peer, "plugin_decoration_sets", json!({})).await.unwrap(); + assert_eq!(sets["api14"][0]["root"], project.to_str().unwrap()); + until("forwarded editor and decoration events", 5, || { + let events = client.plugin_events.lock(); + events.iter().any(|m| m.window.as_deref() == Some("main") && matches!(m.event, PluginEvent::EditorOpen { .. })) + && events.iter().any(|m| matches!(m.event, PluginEvent::DecorationsChanged { .. })) + }) + .await; 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(); diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index ea4d1d2357..46f43ae7dd 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -62,6 +62,88 @@ pub const CANCELLED: &str = "was cancelled"; /// which routes notifications and status items to windows and edits to open /// documents. Capabilities are already checked when these are called. pub trait HostApi: Send + Sync { + /// The invoking window's editors. + fn open_editors(&self, client: &str) -> Result, HostError> { + let _ = client; + Ok(Vec::new()) + } + /// Opens a validated file and optionally selects a range. + fn editor_open(&self, client: &str, path: &Path, selection: Option) -> Result<(), HostError> { + let _ = (client, path, selection); + Err(HostError::Failed("editor unavailable".into())) + } + /// Changes the selections, or reveals a range, only in an editor of this window. + fn editor_ranges( + &self, + client: &str, + path: &Path, + ranges: Vec, + reveal: bool, + ) -> Result<(), HostError> { + let _ = (client, path, ranges, reveal); + Err(HostError::Failed("editor unavailable".into())) + } + /// Find in Files with the project's document overlay. + fn search_text( + &self, + client: Option<&str>, + root: &Path, + query: crate::TextQuery, + limit: u32, + cancel: &CancellationToken, + deadline: Instant, + ) -> Result { + let _ = (client, root, query, limit, cancel, deadline); + Err(HostError::Failed("search unavailable".into())) + } + /// Window-reported Problems view snapshot. + fn problems(&self, client: &str, path: Option<&Path>) -> Result, HostError> { + let _ = (client, path); + Ok(Vec::new()) + } + /// Replace or clear an editor decoration set. + fn decorations(&self, path: Option<&Path>, set: &str, items: Vec) -> Result<(), HostError> { + let _ = (path, set, items); + Err(HostError::Failed("decorations unavailable".into())) + } + /// Replace or clear a tree decoration set. + fn file_decorations( + &self, + path: Option<&Path>, + set: &str, + item: Option, + ) -> Result<(), HostError> { + let _ = (path, set, item); + Err(HostError::Failed("decorations unavailable".into())) + } + /// Trusted repository history. + fn vcs_log( + &self, + root: &Path, + path: Option<&str>, + limit: u32, + cancel: &CancellationToken, + ) -> Result, HostError> { + let _ = (root, path, limit, cancel); + Err(HostError::Failed("git unavailable".into())) + } + /// Trusted repository attribution, including unsaved documents. + fn vcs_blame(&self, client: Option<&str>, root: &Path, path: &str) -> Result, HostError> { + let _ = (client, root, path); + Err(HostError::Failed("git unavailable".into())) + } + /// Trusted repository working-tree patch, bounded to 4 MiB. + fn vcs_diff( + &self, + root: &Path, + path: Option<&str>, + against: Option<&str>, + cancel: &CancellationToken, + ) -> Result, HostError> { + let _ = (root, path, against, cancel); + Err(HostError::Failed("git unavailable".into())) + } + /// Shows a notification; `actions` name commands the plugin declares. fn notify( &self, @@ -101,6 +183,11 @@ pub trait HostApi: Send + Sync { let _ = (client, view); Ok(()) } + /// Whether this stable id is a command declared by this plugin. + fn owns_command(&self, id: &str) -> bool { + let _ = id; + false + } /// Executes a stable command in the invoking window and waits for its result. fn execute_command( &self, diff --git a/crates/ide-plugin/src/types.rs b/crates/ide-plugin/src/types.rs index 9ee469204a..c3110b7d30 100644 --- a/crates/ide-plugin/src/types.rs +++ b/crates/ide-plugin/src/types.rs @@ -478,7 +478,7 @@ pub struct ProviderDocument { pub text: String, } -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] pub struct Location { pub path: PathBuf, pub range: ide_core::Range, @@ -746,3 +746,81 @@ pub struct NotificationAction { pub command: String, pub argument: Option, } + +/// An open editor reported by its window. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct OpenEditor { + pub path: String, + pub language: String, + pub dirty: bool, + pub active: bool, +} +/// Find in Files options. +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct TextQuery { + pub pattern: String, + pub regex: bool, + pub case_sensitive: bool, + pub whole_word: bool, + pub include: Vec, + pub exclude: Vec, +} +/// A search hit, using UTF-16 coordinates. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct TextMatch { + pub location: Location, + pub line: String, +} +/// Bounded search results. +#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct TextSearch { + pub matches: Vec, + pub limit_hit: bool, +} +/// A file's problems from one producer. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct FileProblems { + pub path: String, + pub source: String, + pub diagnostics: Vec, +} +/// An editor decoration. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +pub struct Decoration { + pub range: ide_core::Range, + pub style: String, + pub hover: Option, + pub after: Option, +} +/// A tree decoration. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +pub struct FileDecoration { + pub badge: Option, + pub style: String, + pub tooltip: Option, +} +/// Commit metadata, date in Unix seconds. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CommitInfo { + pub id: String, + pub short_id: String, + pub author: String, + pub author_email: String, + pub date: i64, + pub subject: String, + pub body: String, + pub parents: Vec, +} +/// One zero-based line's attribution, date in Unix seconds. +#[derive(Clone, Debug, Serialize, Deserialize, Type)] +pub struct BlameLine { + pub line: u32, + pub commit: String, + pub author: String, + pub date: i64, + pub summary: String, +} diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index 8fa1bce036..867edb5908 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -44,6 +44,7 @@ pub(crate) mod syntax_bindings { "openidea:plugin/storage": super::bindings::openidea::plugin::storage, "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/decorations": super::bindings::openidea::plugin::decorations, "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, "openidea:plugin/commit": super::bindings::openidea::plugin::commit, @@ -77,6 +78,7 @@ pub(crate) mod providers_bindings { "openidea:plugin/storage": super::bindings::openidea::plugin::storage, "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/decorations": super::bindings::openidea::plugin::decorations, "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, "openidea:plugin/commit": super::bindings::openidea::plugin::commit, @@ -110,6 +112,7 @@ pub(crate) mod views_bindings { "openidea:plugin/storage": super::bindings::openidea::plugin::storage, "openidea:plugin/workspace": super::bindings::openidea::plugin::workspace, "openidea:plugin/editor": super::bindings::openidea::plugin::editor, + "openidea:plugin/decorations": super::bindings::openidea::plugin::decorations, "openidea:plugin/invocation": super::bindings::openidea::plugin::invocation, "openidea:plugin/vcs": super::bindings::openidea::plugin::vcs, "openidea:plugin/commit": super::bindings::openidea::plugin::commit, @@ -577,6 +580,44 @@ impl workspace::Host for StoreData { } impl workspace::HostProject for StoreData { + fn search_text( + &mut self, + this: Resource, + query: workspace::TextQuery, + limit: u32, + ) -> Fallible { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let root = &self.table.get(&this)?.root; + let query = crate::TextQuery { + pattern: query.pattern, + regex: query.regex, + case_sensitive: query.case_sensitive, + whole_word: query.whole_word, + include: query.include, + exclude: query.exclude, + }; + Ok(self + .host + .search_text(self.client(), root, query, limit.min(10_000), &self.cancel.token(), self.deadline) + .map(|s| workspace::TextSearch { + limit_hit: s.limit_hit, + matches: s + .matches + .into_iter() + .map(|m| workspace::TextMatch { + location: wit::Location { + path: to_ipc(&m.location.path), + range: range_to_wit(&m.location.range), + }, + line: m.line, + }) + .collect(), + }) + .map_err(to_wit)) + } + fn root(&mut self, this: Resource) -> Fallible { if let Err(e) = self.require(Capability::ProjectRead) { return Ok(Err(e)); @@ -704,11 +745,94 @@ impl workspace::HostProject for StoreData { } } -impl editor::Host for StoreData {} +impl editor::Host for StoreData { + fn open_editors(&mut self) -> Fallible> { + if let Err(e) = self.require(Capability::EditorRead).and_then(|_| self.require_window()) { + return Ok(Err(e)); + } + Ok(self + .host + .open_editors(self.client().unwrap()) + .map(|items| { + items + .into_iter() + .map(|e| editor::OpenEditor { + path: e.path, + language: e.language, + dirty: e.dirty, + active: e.active, + }) + .collect() + }) + .map_err(to_wit)) + } + fn open(&mut self, path: String, selection: Option) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let real = match self.openable_path(&path) { + Ok(p) => p, + Err(e) => return Ok(Err(e)), + }; + Ok(self.host.editor_open(self.client().unwrap(), &real, selection.map(core_range)).map_err(to_wit)) + } +} + +fn core_range(r: wit::Range) -> ide_core::Range { + ide_core::Range::new(pos(r.start), pos(r.end)) +} +impl StoreData { + fn decoration_path(&self, path: &str) -> Result { + if Path::new(path).is_absolute() { + return Ok(PathBuf::from(path)); + } + let root = self + .invocation + .workspace_root + .as_ref() + .ok_or_else(|| wit::Error::Invalid("relative decorations need an invoking project".into()))?; + sandbox::resolve_in_root(root, path).map_err(wit::Error::Invalid) + } + fn openable_path(&self, path: &str) -> Result { + if let Ok(dir) = self.host.plugin_dir() + && let Ok(real) = sandbox::resolve_granted(&[Capability::FsRead(to_ipc(&dir))], path) + { + return Ok(real); + } + self.require(Capability::ProjectRead)?; + let root = self + .invocation + .workspace_root + .as_ref() + .ok_or_else(|| wit::Error::Invalid("no project is open in this window".into()))?; + sandbox::resolve_in_root(root, path).map_err(wit::Error::Invalid) + } +} impl detail_types::Host for StoreData {} impl editor::HostTextEditor for StoreData { + fn set_selections(&mut self, this: Resource, selections: Vec) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + if selections.is_empty() || selections.len() > 1000 { + return Ok(Err(wit::Error::Invalid("requires 1-1000 selections".into()))); + } + let path = &self.table.get(&this)?.ctx.path; + Ok(self + .host + .editor_ranges(self.client().unwrap(), path, selections.into_iter().map(core_range).collect(), false) + .map_err(to_wit)) + } + fn reveal(&mut self, this: Resource, range: wit::Range) -> Fallible<()> { + if let Err(e) = self.require_window() { + return Ok(Err(e)); + } + let path = &self.table.get(&this)?.ctx.path; + Ok(self.host.editor_ranges(self.client().unwrap(), path, vec![core_range(range)], true).map_err(to_wit)) + } + fn path(&mut self, this: Resource) -> wasmtime::Result { Ok(to_ipc(&self.table.get(&this)?.ctx.path)) } @@ -793,6 +917,69 @@ impl invocation::HostInvocation for StoreData { } impl vcs::Host for StoreData { + fn log( + &mut self, + project: Resource, + path: Option, + limit: u32, + ) -> Fallible> { + if let Err(e) = self.require(Capability::VcsRead) { + return Ok(Err(e)); + } + let root = &self.table.get(&project)?.root; + Ok(self + .host + .vcs_log(root, path.as_deref(), limit.min(1000), &self.cancel.token()) + .map(|v| { + v.into_iter() + .map(|c| vcs::CommitInfo { + id: c.id, + short_id: c.short_id, + author: c.author, + author_email: c.author_email, + date: c.date, + subject: c.subject, + body: c.body, + parents: c.parents, + }) + .collect() + }) + .map_err(to_wit)) + } + fn blame(&mut self, project: Resource, path: String) -> Fallible> { + if let Err(e) = self.require(Capability::VcsRead) { + return Ok(Err(e)); + } + let root = &self.table.get(&project)?.root; + Ok(self + .host + .vcs_blame(self.client(), root, &path) + .map(|v| { + v.into_iter() + .map(|c| vcs::BlameLine { + line: c.line, + commit: c.commit, + author: c.author, + date: c.date, + summary: c.summary, + }) + .collect() + }) + .map_err(to_wit)) + } + fn diff( + &mut self, + project: Resource, + path: Option, + against: Option, + ) -> Fallible> { + if let Err(e) = self.require(Capability::VcsRead) { + return Ok(Err(e)); + } + let root = &self.table.get(&project)?.root; + Ok(self.host.vcs_diff(root, path.as_deref(), against.as_deref(), &self.cancel.token()).map_err(to_wit)) + } + fn status(&mut self, project: Resource) -> Fallible> { if let Err(e) = self.require(Capability::VcsRead) { return Ok(Err(e)); @@ -991,6 +1178,40 @@ impl StoreData { } impl diagnostics::Host for StoreData { + fn problems(&mut self, path: Option) -> Fallible> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + if self.client().is_none() { + return Ok(Err(wit::Error::Invalid("requires an invoking window".into()))); + } + let real = match path { + None => None, + Some(path) => { + let Some(root) = self.invocation.workspace_root.as_ref() else { + return Ok(Err(wit::Error::Invalid("no project in this window".into()))); + }; + match sandbox::resolve_new_in_root(root, &path) { + Ok(p) => Some(p), + Err(e) => return Ok(Err(wit::Error::Invalid(e))), + } + } + }; + Ok(self + .host + .problems(self.client().unwrap(), real.as_deref()) + .map(|v| { + v.into_iter() + .map(|f| diagnostics::FileProblems { + path: f.path, + source: f.source, + diagnostics: f.diagnostics.into_iter().map(diagnostic_to_wit).collect(), + }) + .collect() + }) + .map_err(to_wit)) + } + fn publish(&mut self, path: String, items: Vec) -> Fallible<()> { if let Err(e) = self.require(Capability::ProjectRead) { return Ok(Err(e)); @@ -1618,6 +1839,11 @@ impl bindings::openidea::plugin::command_runner::Host for StoreData { if let Err(e) = self.require_window() { return Ok(Err(e)); } + if !self.host.owns_command(&id) + && let Err(e) = self.require(Capability::IdeCommands) + { + 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()))); } @@ -1686,3 +1912,82 @@ impl bindings::openidea::plugin::output::Host for StoreData { Ok(self.host.output_reveal(self.invocation.client.as_deref().expect("checked"), &channel).map_err(to_wit)) } } + +fn diagnostic_to_wit(d: ide_core::Diagnostic) -> diagnostics::Diagnostic { + diagnostics::Diagnostic { + range: range_to_wit(&d.range), + severity: match d.severity { + ide_core::Severity::Error => diagnostics::Severity::Error, + ide_core::Severity::Warning => diagnostics::Severity::Warning, + ide_core::Severity::Info => diagnostics::Severity::Info, + ide_core::Severity::Hint => diagnostics::Severity::Hint, + }, + message: d.message, + code: d.code, + source: d.source, + tags: [(d.unnecessary, "unnecessary"), (d.deprecated, "deprecated")] + .into_iter() + .filter(|(yes, _)| *yes) + .map(|(_, tag)| tag.into()) + .collect(), + related: Vec::new(), + } +} +impl bindings::openidea::plugin::decorations::Host for StoreData { + fn set( + &mut self, + path: String, + set_id: String, + items: Vec, + ) -> Fallible<()> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + if items.len() > 10_000 { + return Ok(Err(wit::Error::Invalid("at most 10000 decorations per file".into()))); + } + let items = items + .into_iter() + .map(|d| crate::Decoration { range: core_range(d.range), style: d.style, hover: d.hover, after: d.after }) + .collect(); + let real = match self.decoration_path(&path) { + Ok(real) => real, + Err(e) => return Ok(Err(e)), + }; + Ok(self.host.decorations(Some(&real), &set_id, items).map_err(to_wit)) + } + fn clear(&mut self, set_id: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + Ok(self.host.decorations(None, &set_id, Vec::new()).map_err(to_wit)) + } + fn set_file( + &mut self, + path: String, + set_id: String, + item: bindings::openidea::plugin::decorations::FileDecoration, + ) -> Fallible<()> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + let real = match self.decoration_path(&path) { + Ok(real) => real, + Err(e) => return Ok(Err(e)), + }; + Ok(self + .host + .file_decorations( + Some(&real), + &set_id, + Some(crate::FileDecoration { badge: item.badge, style: item.style, tooltip: item.tooltip }), + ) + .map_err(to_wit)) + } + fn clear_file(&mut self, set_id: String) -> Fallible<()> { + if let Err(e) = self.require(Capability::ProjectRead) { + return Ok(Err(e)); + } + Ok(self.host.file_decorations(None, &set_id, None).map_err(to_wit)) + } +} diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index 68d46d4387..d53ee4ea4b 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 495ea9bd1b..189de13d15 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -59145ee5ce6e05000c52d80174156c66e4fcdc5fa9ff329f0d803c15aa1f4fbc +760e61a20d8e86bef8dc33fd8f636c5984a68f0f1274b1afa1405e069ab6b1ef diff --git a/crates/ide-plugin/tests/fixtures/api14/plugin.toml b/crates/ide-plugin/tests/fixtures/api14/plugin.toml index bb06f2b02e..6bf8978670 100644 --- a/crates/ide-plugin/tests/fixtures/api14/plugin.toml +++ b/crates/ide-plugin/tests/fixtures/api14/plugin.toml @@ -7,7 +7,7 @@ activation = ["on-command:*", "on-event:file-closed", "on-event:settings-changed [capabilities] required = ["storage"] -optional = ["events", "events.input", "editor.read", "secrets", "net:localhost", "net.http:example.com", "ipc:$TMPDIR/api14-*"] +optional = ["ide.commands", "project.read", "vcs.read", "events", "events.input", "editor.read", "secrets", "net:localhost", "net.http:example.com", "ipc:$TMPDIR/api14-*"] [[contributes.secrets]] name = "token" @@ -83,3 +83,55 @@ title = "terminal" [[contributes.commands]] id = "log" title = "log" + +[[contributes.commands]] +id = "open-editors" +title = "open-editors" + +[[contributes.commands]] +id = "open-editor" +title = "open-editor" + +[[contributes.commands]] +id = "set-selections" +title = "set-selections" + +[[contributes.commands]] +id = "reveal" +title = "reveal" + +[[contributes.commands]] +id = "search-text" +title = "search-text" + +[[contributes.commands]] +id = "problems" +title = "problems" + +[[contributes.commands]] +id = "decorations" +title = "decorations" + +[[contributes.commands]] +id = "clear-decorations" +title = "clear-decorations" + +[[contributes.commands]] +id = "file-decoration" +title = "file-decoration" + +[[contributes.commands]] +id = "clear-file-decorations" +title = "clear-file-decorations" + +[[contributes.commands]] +id = "vcs-log" +title = "vcs-log" + +[[contributes.commands]] +id = "vcs-blame" +title = "vcs-blame" + +[[contributes.commands]] +id = "vcs-diff" +title = "vcs-diff" diff --git a/crates/ide-plugin/tests/fixtures/api14/src/lib.rs b/crates/ide-plugin/tests/fixtures/api14/src/lib.rs index 92c2597f52..659f147e33 100644 --- a/crates/ide-plugin/tests/fixtures/api14/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/api14/src/lib.rs @@ -2,9 +2,65 @@ use openidea_plugin::{Error, Event, Invocation, Plugin, StatusItem, host, regist #[derive(Default)] struct Api14; impl Plugin for Api14 { - fn run_command(&mut self, id: &str, _ctx: &Invocation, arg: Option<&str>) -> Result, Error> { + fn run_command(&mut self, id: &str, ctx: &Invocation, arg: Option<&str>) -> Result, Error> { let arg = arg.unwrap_or_default(); match id { + "open-editors" => Ok(Some(format!("{:?}", host::open_editors()?))), + "open-editor" => { + host::open_editor(arg, Some(openidea_plugin::Range::default()))?; + Ok(None) + } + "set-selections" => { + ctx.editor().unwrap().set_selections(&[openidea_plugin::Range::default()])?; + Ok(None) + } + "reveal" => { + ctx.editor().unwrap().reveal(openidea_plugin::Range::default())?; + Ok(None) + } + "search-text" => { + let result = ctx + .project() + .unwrap() + .search_text(&openidea_plugin::TextQuery { pattern: arg.into(), ..Default::default() }, 10)?; + Ok(Some(format!("{result:?}"))) + } + "problems" => Ok(Some(format!("{:?}", host::problems(if arg.is_empty() { None } else { Some(arg) })?))), + "decorations" => { + host::set_decorations( + arg, + "test", + &[openidea_plugin::Decoration { + range: openidea_plugin::Range::default(), + style: "highlight".into(), + hover: Some("hover".into()), + after: Some("after".into()), + }], + )?; + Ok(None) + } + "clear-decorations" => { + host::clear_decorations("test")?; + Ok(None) + } + "file-decoration" => { + host::set_file_decoration( + arg, + "test", + &openidea_plugin::FileDecoration { badge: Some("OK".into()), style: "added".into(), tooltip: None }, + )?; + Ok(None) + } + "clear-file-decorations" => { + host::clear_file_decorations("test")?; + Ok(None) + } + "vcs-log" => Ok(Some(format!( + "{:?}", + ctx.project().unwrap().vcs_log(if arg.is_empty() { None } else { Some(arg) }, 10)? + ))), + "vcs-blame" => Ok(Some(format!("{:?}", ctx.project().unwrap().vcs_blame(arg)?))), + "vcs-diff" => ctx.project().unwrap().vcs_diff(if arg.is_empty() { None } else { Some(arg) }, None), "ipc" => { let stream = host::ipc_connect(arg)?; stream.write(b"echo")?; diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index 24a909d97f..a6b9ba8e5b 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 f70006d168..6ed54c79fa 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 @@ -aae3c82c01b54387a4a18d95614e5275374bb5d1fde8685e11cc4b0ca54f3edb +d7ad5b0321ad2fc44a608a66bda95eb9ee3569de11997e2ad35527f7dc79457c 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 238e4a66f8..e7087a0385 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 0978e9f640..4f00a16bff 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 @@ -49a56737954cd79c7dcca5543856473bfe77b420e977c6091ab832bafadac8c1 +73d4e3aef6255b2b415de910e19707aef363e70a8a94682ede55d96d0949b0a2 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 889fbb2f2c..897e3c0ea3 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 9c13180a8d..10e1e540d0 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 @@ -07882856be39355607403ff5c2066c537333fc80e5fa4248f7193456c56e34c2 +1b13c0aaef2faa87c46de5c39df0ca60c8085a4da45b7b2654a14567b37e823e diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index ec882571b6..df7b44dfb0 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 153c0dd54d..e1d218a9ee 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 @@ -81f06d523eab81c3a930906750d110d49a2ea1028c41aa825551b854ad2c971c +bc80a8be86e557eba1e8dc13aa9886e22556b778e39e8ec60186b65c09fc1842 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 d2e36f1b26..c36e62db71 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 0febd991cc..9590385bdb 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 @@ -e5552be8e6bcb0dc1aed69b15ef6d56c4861bca507514fd11549387a85703e38 +e58b0dd4bb4b04634ba175c92336c53fea432ef81067f8d9a122909c3be25f3f 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 9610d6e85e..6dcace0cef 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 5f950f09f6..c9bfe07348 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 @@ -8184794f370596474b2fc306a3adce3f1ce8685bea748442133efd92abab5cdc +8dad66c2d9cf812296fdca2adccc249f3c1eeb17604fd63f8e8c041484c5979b 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 9e7dc88556..a668dcef74 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 002e4d4f81..1380b134fa 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 @@ -3b11fb8a7e61919808ef2c09c770be0b6cc86c2ba20abf62aa95b3e7f34c8453 +116292315ed8d5b48e79c129b139ffa9d0dc48e80b090f010ecc5551f2325d8b diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index 9ce6fd45d0..7d72321400 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 67a7344b48..192a6a3e83 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 @@ -1319e0b252577fc01c1b999bb35c43168d2416c985362d49e06e7d627205347b +f1643eb84e9ecde671d2393b4bd5ec91ff20deb27644ac44817a9a3ac4fc5676 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 97f2423cc6..824faf4920 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 2365590072..f4d9c5cd9a 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 @@ -d2e60f464a297332b55172cac4968fced00a7ec218af9c6ce7e01b259da515d7 +8db352eeb40963350d89a31131ef76d7ff31986d815baccc11a230d176773c5b diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index 6cde36bdc4..6add06a980 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 757b17a376..36a40bdd6c 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 @@ -4daf9ad04a2b10872799976debb792ce24f04fb128e0318e784e6a0a307db9de +1e775c72930fb2f9aea1054add4f3671872f6ed1736d15209b1cbe71557cb086 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 5df62c9e7b..5a52899d45 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 af57b8835c..caba43e7c0 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 @@ -73d73b1e33e2e7ad58db158744630cc53b263213940b8aca251c1fe36f6e9368 +5c8f6f665c6a328615c303dae05183f18fa994432aa8bfccf0d78e6be1cff228 diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 82155eeb14..ce46fef33d 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 d257a2bd47..9ce6abdb80 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 @@ -af621d99276ac3ad29a92c4c056e1bf8ab253b911a0fbd6562f0f227e2941177 +6a995f3eb26e892846fe57993ee1419b3351b1de9ecc8a192a21d789ea81fa55 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index 75246295e8..841cf58a51 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 94c17a282d..573ec06e7f 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 @@ -b5e51d67739b775dda14f342db2d0776a0fea5aaf6fe482416b99581c998dd55 +34543f2144eb9744949f64e5a60a1b3148522deb065bffe7969ca024a5c18de2 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 5d15d374e8..3dfaaa589a 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 95c6e8bf25..9f52883729 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 @@ -85e18a196e960ff9b1bc61bae84fd3f7ec5b08872de0df4b12d6843b0bcea467 +cd0102ffd14eaf396aa238d433a42f9c34415cd830233fe776615c1c21b03522 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 c05e178bcf..fad96d36c0 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 f54f9cab3f..cdc7e90867 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 @@ -15c74b27c3fc5809d061768df0abd84a785a641d685c33fc1ca4c637d7268008 +d0299ee80017812d651cb2603474eba2c7c7adcd0b9b661797ca30ba7ddd3211 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 e5e911de10..1a8b45df3c 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 fe5ca80815..d36da1228c 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 @@ -9e8e38868d12ca3ac2504fc6e537cb93efc3fa4db33e08b8abdaaa86e5f6e254 +0d06e711cbcc2d68bdf4103e2b4d8ea2f2476ad67b007416868abd1a82555f07 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 33b29836e8..fe005fd2e8 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 aeeec21ab1..dda7833da0 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 @@ -742f536436ef3a6034087a85f41765bbb9a55a8f7ec61e24e752e4dc4031a57b +7018de72c72ff4f81ffffbcbb0d335b5c77c27dacb9d41c3d47bb07543b71ecc diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 6b2120c585..4afb9bfc0a 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 f073f05551..2a8fe6532b 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 @@ -9c84ce120727c3a85e9d94e607a266b02faf70b5ca77e4b2ee4debcca272e2b1 +5ef5556fa62c863f5978d35994a55585fb818ac3b3ef314628cad214f212100f diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index db1b32148b..d0d5ff61d4 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 c36bdcd595..67215024f7 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 @@ -569e5be98fcf45288141fc40bcb50e0a3fb8038d679c6b9a06c73efd0d425494 +c97f5d74e908a2b84a32b54a16d530d0338a7dc6a017bb7512517876f7b1b15b diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index f9efbf7906..f4009a7fb6 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 7fc5b327f9..4da7658505 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 @@ -38c9e6fd9a8aa0b8c6ec830080fbba01a637a98fb0b19f77fbe98324271cb096 +27bacd1e897a5eee8334842a4a77e7c796daff6e8d82fb300820764e1ebf66bd 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 f8a218b236..5da820de55 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 52bf05d181..d8e95682eb 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 @@ -f9102292daa0fd169e55791b48dae2c10893cb3d867377e0745a013657b1496e +501f58d2e725fa34c14ca92f214d9b65bb926b3bae7277defa0456c2e467da8e 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 3b27422390..c9ff33c35d 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 2915a92aba..4e18c88806 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 @@ -371709b0820de67ce575df082776a9b3c5e116aa44f18c8be53851192431d4f2 +250ee4347b39db4dfa25940c9ef0eecae28d36bcf68aee96a383d996f077fa12 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 603a634469..cfc3583e77 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 800b7e2741..41c8cfcd74 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 @@ -81537fa6fb1212fda71bb081df1fceff3a2e27d3df43e89e1b7301d8b9efc306 +e272cfe6d39ba8bf37302337b177b88e15d79a31ac5f0c31d98833265029e1b5 diff --git a/crates/ide-vcs/src/cli.rs b/crates/ide-vcs/src/cli.rs index 3a73f2704b..56b20e9385 100644 --- a/crates/ide-vcs/src/cli.rs +++ b/crates/ide-vcs/src/cli.rs @@ -381,10 +381,46 @@ fn run_cancellable_raw_stdin( args: &[&str], stdin: Option<&[u8]>, cancel: &CancellationToken, +) -> IdeResult { + run_capture(root, args, stdin, cancel, usize::MAX) +} + +/// Neutralizes repository clean/process filters for a read of working-tree bytes. +/// Git still applies them with --no-ext-diff and --no-textconv. +pub(crate) fn filter_overrides(root: &Path, cancel: &CancellationToken) -> IdeResult> { + if crate::execution_allowed() { + return Ok(Vec::new()); + } + let config = run_bounded(root, &["config", "--null", "--list"], cancel, 4 << 20)?; + let mut overrides = Vec::new(); + for record in config.stdout_str().split('\0') { + let key = record.split('\n').next().unwrap_or_default(); + if key.starts_with("filter.") + && (key.ends_with(".clean") || key.ends_with(".process") || key.ends_with(".required")) + { + overrides.push("-c".into()); + overrides.push(format!("{key}={}", if key.ends_with(".required") { "false" } else { "" })); + } + } + Ok(overrides) +} + +/// Cancellable capture with bounded stdout and stderr; stops git on overflow. +pub(crate) fn run_bounded(root: &Path, args: &[&str], cancel: &CancellationToken, max: usize) -> IdeResult { + let out = run_capture(root, args, None, cancel, max)?; + if out.code == Some(0) { Ok(out) } else { Err(failure(args, &out.stderr, &out.stdout, out.code)) } +} +fn run_capture( + root: &Path, + args: &[&str], + stdin: Option<&[u8]>, + cancel: &CancellationToken, + max: usize, ) -> IdeResult { if cancel.is_cancelled() { return Err(IdeError::cancelled()); } + let overflow = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let mut cmd = command(root)?; cmd.args(args) .stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() }) @@ -404,22 +440,32 @@ fn run_cancellable_raw_stdin( _ => None, }; let capture = |mut pipe: Box| { + let overflow = overflow.clone(); std::thread::spawn(move || { let mut bytes = Vec::new(); - pipe.read_to_end(&mut bytes).map(|_| bytes) + (&mut pipe).take(max.saturating_add(1) as u64).read_to_end(&mut bytes)?; + if bytes.len() > max { + overflow.store(true, std::sync::atomic::Ordering::Release); + std::io::copy(&mut pipe, &mut std::io::sink())?; + } + Ok(bytes) }) }; let stdout = capture(Box::new(child.stdout.take().expect("piped stdout"))); let stderr = capture(Box::new(child.stderr.take().expect("piped stderr"))); let status = loop { - if cancel.is_cancelled() { + if cancel.is_cancelled() || overflow.load(std::sync::atomic::Ordering::Acquire) { terminate_tree(&mut child, KILL_GRACE); let _ = stdout.join(); let _ = stderr.join(); if let Some(w) = writer { let _ = w.join(); } - return Err(IdeError::cancelled()); + return Err(if cancel.is_cancelled() { + IdeError::cancelled() + } else { + IdeError::invalid(format!("git output exceeds {max} bytes")) + }); } if let Some(status) = child.try_wait()? { break status; @@ -434,6 +480,9 @@ fn run_cancellable_raw_stdin( }; let out = Output { stdout: join(stdout)?, stderr: join(stderr)?, code: status.code() }; session.finish(status.success(), &String::from_utf8_lossy(&out.stderr)); + if out.stdout.len() > max || out.stderr.len() > max { + return Err(IdeError::invalid(format!("git output exceeds {max} bytes"))); + } Ok(out) } diff --git a/crates/ide-vcs/src/compare.rs b/crates/ide-vcs/src/compare.rs index d2404185cc..6e1bc738bf 100644 --- a/crates/ide-vcs/src/compare.rs +++ b/crates/ide-vcs/src/compare.rs @@ -135,19 +135,7 @@ impl Repos { let mut compare = || -> IdeResult<(String, Vec)> { // Worktree comparisons must not run repository-defined clean/process filters // in Restricted Mode. External diff and textconv are disabled below as well. - let mut overrides = Vec::new(); - if !crate::execution_allowed() { - let config = cli::run_cancellable(repo.root(), &["config", "--null", "--list"], cancel)?; - for record in config.stdout_str().split('\0') { - let key = record.split('\n').next().unwrap_or_default(); - if key.starts_with("filter.") - && (key.ends_with(".clean") || key.ends_with(".process") || key.ends_with(".required")) - { - overrides.push("-c".to_owned()); - overrides.push(format!("{key}={}", if key.ends_with(".required") { "false" } else { "" })); - } - } - } + let overrides = cli::filter_overrides(repo.root(), cancel)?; let run = |args: &[&str]| { let mut full: Vec<&str> = overrides.iter().map(String::as_str).collect(); full.extend_from_slice(args); diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 9e59c7db3a..9c1c121062 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1013,6 +1013,30 @@ impl Repo { let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); refs::stashes(self) } + /// Working tree against a revision, optionally restricted to a file. Bounded and cancellable. + pub fn working_tree_patch( + &self, + path: Option<&Path>, + against: Option<&str>, + max_bytes: usize, + cancel: &CancellationToken, + ) -> IdeResult { + let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); + let rev = against.unwrap_or("HEAD"); + if rev.is_empty() || rev.starts_with('-') || rev.contains('\0') { + return Err(ide_core::IdeError::invalid("invalid revision")); + } + let rel = path.map(|p| self.rel_path(p)).transpose()?; + let overrides = cli::filter_overrides(self.root(), cancel)?; + let mut args: Vec<&str> = overrides.iter().map(String::as_str).collect(); + args.extend(["--literal-pathspecs", "--no-pager", "diff", "--no-ext-diff", "--no-textconv", rev, "--"]); + if let Some(rel) = &rel { + args.push(rel); + } + let out = cli::run_bounded(self.root(), &args, cancel, max_bytes)?; + Ok(out.stdout_str()) + } + /// Unified diff of a file: index↔worktree (`staged == false`, untracked files diff /// against /dev/null) or HEAD↔index (`staged == true`). Empty when unchanged. pub fn diff_text(&self, path: &Path, staged: bool, encoding: impl Into) -> IdeResult { diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index 64958f0fb4..21ae5f937e 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -146,7 +146,12 @@ fn converted_blame( let current = crate::diff::normalize_eol(text); let mut result = uncommitted_lines(current.split_inclusive('\n').count()); let Some(base) = r.file_bytes_at(path, Some(revision))? else { return Ok(result) }; - let out = run(r.root(), &["--literal-pathspecs", "blame", "--porcelain", revision, "--", rel], None)?; + let args: &[&str] = if crate::execution_allowed() { + &["--literal-pathspecs", "blame", "--porcelain", revision, "--", rel] + } else { + &["--literal-pathspecs", "blame", "--no-textconv", "--porcelain", revision, "--", rel] + }; + let out = run(r.root(), args, None)?; let physical = crate::blame::parse_porcelain(&out.stdout_str()); let raw = crate::text_encoding::decode_raw(&base, encoding); let raw = crate::diff::normalize_eol(&raw); diff --git a/plugins/README.md b/plugins/README.md index 2d3a138eed..21d09145c1 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -287,25 +287,26 @@ installing (or when a new version asks for more). Low-risk capabilities are listed; high-risk ones are called out as equivalent to running code on the machine. Users can revoke optional capabilities in Settings › Plugins. -| Capability | Risk | Unlocks today | -| ------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------- | -| `project.read` | low | `Project::root`, `read_file`, `find_files`, `symbols`, `host::projects`, `publish_diagnostics` | -| `project.write` | medium | `Project::write_file` — creates and replaces text files inside the open projects | -| `fs.read:` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | -| `fs.write:` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | -| `editor.read` | low | `TextEditor::document`, `selections` | -| `editor.write` | medium | `TextEditor::apply_edits` | -| `vcs.read` | low | `Project::vcs_status` (branch, upstream, ahead/behind, changes), `vcs_remotes`, `host::pending_commit`, before-commit checks | -| `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` and `input-mode-changed` events | -| `process:` | high | `Project::run_process`, language servers, debug adapters, runs | -| `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 | +| Capability | Risk | Unlocks today | +| ------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `ide.commands` | high | Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing. API 1.4; declared own commands are exempt. | +| `project.read` | low | `Project::root`, `read_file`, `find_files`, `symbols`, `search_text`, `host::projects`, `publish_diagnostics`, `problems`, editor opening and decorations | +| `project.write` | medium | `Project::write_file` — creates and replaces text files inside the open projects | +| `fs.read:` | high | `host::fs::read_file`, `read_bytes`, `stat`, `read_dir` — files outside the projects, under the grant's directory | +| `fs.write:` | high | `host::fs::write_file`, `write_bytes` — files under that path; doesn't imply reading | +| `editor.read` | low | `TextEditor::document`, `selections`, `host::open_editors` | +| `editor.write` | medium | `TextEditor::apply_edits` | +| `vcs.read` | low | `Project::vcs_status`, `vcs_remotes`, `vcs_log`, `vcs_blame`, `vcs_diff` (new reads require trust), `host::pending_commit`, before-commit checks | +| `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` and `input-mode-changed` events | +| `process:` | high | `Project::run_process`, language servers, debug adapters, runs | +| `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 language's `language-servers` and `debugger` commands and a run detector's @@ -440,51 +441,61 @@ 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_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. | +| 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). | +| `host::open_editors()` | `editor.open-editors` | API 1.4: invoking window's path/language/dirty/active snapshots; requires `editor.read`. Commands/events of a window only. | +| `host::open_editor(path, selection)` | `editor.open` | API 1.4: open/select a project file (`project.read`) or plugin-dir file; same path rules as `views.open-location`. Commands/events of a window only. | +| `TextEditor::set_selections(ranges)`, `reveal(range)` | `editor.text-editor` | API 1.4: selections or scrolling in this window's already open editor; no capability. Commands/events only, UTF-16 coordinates. | +| `host::set_decorations`, `clear_decorations` | `decorations.{set,clear}` | API 1.4: project-scoped editor annotations cleared on plugin stop. Requires `project.read`. | +| `host::set_file_decoration`, `clear_file_decorations` | `decorations.{set-file,clear-file}` | API 1.4: project-tree badges/styles. Requires `project.read`. | +| `Project::search_text(query, limit)` | `workspace.project.search-text` | API 1.4: cancellable Find in Files with unsaved documents and project excludes, at most 10,000 matches. Requires `project.read`. | +| `host::problems(path)` | `diagnostics.problems` | API 1.4: project Problems reports grouped by file/source, optional file filter. Requires `project.read` and an invoking window. Empty for remote projects. | +| `Project::vcs_log(path, limit)` | `vcs.log` | API 1.4: newest first, at most 1000 commits, optional file history. Requires `vcs.read` and trust. | +| `Project::vcs_blame(path)` | `vcs.blame` | API 1.4: attribution including unsaved editor text. Requires `vcs.read` and trust. | +| `Project::vcs_diff(path, against)` | `vcs.diff` | API 1.4: disk working tree against HEAD/revision, optionally one file. None outside Git; fails above 4 MiB. Requires `vcs.read` and trust. | +| `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: requires high-risk `ide.commands` for IDE actions and other plugins; this plugin's own commands are exempt. 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 @@ -513,6 +524,49 @@ plugin ends its children, as does closing the window that started them. `run-command` receives an optional string argument: `executeAction("plugin.<plugin id>.<command id>", "arg")` from another feature, or nothing when run from Search Everywhere / a shortcut. `ctx.selected_paths()` lists the files and folders a Project view or editor tab menu ran the command on (the argument is the first of them); it is empty otherwise. No capability is needed. +### Editor and project snapshots (API 1.4) + +Editor lists come from the invoking window's existing workbench reports; language +and dirty state come from the open documents. Selection and reveal operations +require an editor belonging to that window, even when another window has the same +project. Ranges use zero-based lines and UTF-16 columns. Selection changes accept +1–1000 ranges and do not change document text. Opening a file acknowledges a UI +request; the usual editor handles the actual open. + +`Project::search_text` takes `TextQuery { pattern, regex, case_sensitive, +whole_word, include, exclude }`. Globs follow Find in Files' masks. It uses the +same search engine and unsaved-document overlay as the built-in MCP tools, with +the project's exclusions; only files inside this project's root are returned. +Results contain `{ location, line }` and `limit_hit`; limits are capped at 10,000, +zero returns no matches. Line previews are capped at 4096 UTF-8 bytes and the +result budget is 4 MiB (`limit_hit` also covers that cap). Closed-file text is +read with the editor's encoding defaults, at most 16 MiB per file; a matched file +that cannot be materialized also sets `limit_hit`. Cancellation or the +call deadline interrupts the search. `host::problems` reuses the Problems view's +reports, including LSP and plugin diagnostics; a remote project currently returns +an empty list because it does not forward Problems reports. + +Decorations are plain text, with fixed styles mapped to theme tokens: +`highlight`, `search`, `added`, `modified`, `removed`, `warning`, `error`, `info`, +`underline`, `strikethrough`, `muted`. Unknown styles are ignored. Editor items +have `{ range, style, hover, after }`; tree items have `{ badge, style, tooltip }`, +where a badge has at most two Unicode characters. Paths must resolve inside an +open project; absolute paths select that project, relative paths use the invoking +project. Sets are isolated by plugin and project and shared by all windows of +that project. Setting replaces a set's items for one file; clearing removes that +set in all projects. Each plugin has at most 50 editor sets and 50 tree sets, +10,000 editor items per file across its sets, and 4 MiB total metadata. Disabling, +unloading or crashing the plugin withdraws them; idle reclamation preserves them. + +The new Git reads run on the project machine, require a trusted open project and +`vcs.read`, and disable repository-configured helpers, textconv and external diff +programs. `vcs_log` returns commit ids, author/email, Unix seconds, subject/body +and parents. `vcs_blame` uses the IDE annotate backend: unsaved changed/inserted +lines are uncommitted; `line` is zero-based and dates are Unix seconds. +`vcs_diff` uses disk text (including staged and unstaged changes) against HEAD or +`against`, and stops with an error if output exceeds 4 MiB. Without a repository, +log/blame return empty lists and diff returns `None`. + ### Events | Kind | Capability | Delivered | diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index 22ac344396..78a48cffb4 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 8e88788785..3978f91a88 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -8a1b87e6985c9bff6f034b56c4d4bf967a96f7579d5aff79213e631a95722408 +7e91ad700c74a55975f0e724c93e931855a8f8837f57e7ff766b866c1040b6ac diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index 36c90091f1..5e7ba4faf9 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 33cbdbb676..4679cd374e 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -1b68413078837975701fd58850a7f5dc1960de2ccc8e7f20effa57c2ca595eaf +3766b50f1bcfa9603724363eac893c40a73a7624683305ddf777b81128cd5c34 diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index 75da43a5e6..4aedc6203a 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 e35cd84a0a..6ff0213326 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -2282cc3959e7b3576714d5dad611b51c404143ffbdadba809d0e3bc2d2afad29 +6487cf35fb345aabe08bf2c8b28447f2f68a9b07f9673e0af468cf5be3df4c87 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index d804afddaf..36048b7c46 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 16d429c9cc..780cad3fb5 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -eeb7ccd4b23564f1bb61edd50c4e3c50e445a028a0b4f90371b16b39bd1a40b4 +60b20830b0a90eba550e7e7a1622b5aaef31a2dc514f76491c7fb34574a802d1 diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index 1d19283ce0..d4d2dddb74 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 0c75524100..f9ac0e0ce3 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -15d35ef3cbc8b81a16f66d645f6f4c8d20ccda9bbff911ca1548866d77d7b9a4 +d2c300d6e7d9bd8152265641a8c9aa8e1183ae93e19bc10f04d27cc6d740e10d diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 8bbb02c9cc..11e8257994 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 d5c4dacff8..986c51754a 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -418d6e2b7725cc1099997febd78705f27b2b1739121e98a3db4fe43ae3c21b02 +d6f040353ff1bb02592122a75db1fdac473eac5de9370a95379fd9aaadafca56 diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index e0d41b9b29..5abcb6d870 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 9c891801eb..b77588a0dc 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -f280966be4b29a792d1494bfbac1695b750895ded1011ba1a4b9501981b73997 +fb7966fd1b05b986328bd3f90ed685cc80b578744673f50b5a8c81005e67d2d5 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index 11534517b4..5fdd6b4594 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 8301808a2e..91523674e1 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -db4087cf4c2265c78508949d167d0c3e8b5c0b9434000101d201d12196bed3f1 +fdad66fdd54d20a722d4fa49b478614e969882850f0ce39ae1abf4ee50859aa3 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index ee16b48070..a873b4546c 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 972f7afa9c..1b7b727316 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -85653ef957f5e0483889ea750e486c79fe7e6630fee65ff2aa2e187abbcf7964 +def6c3f503d49005ad5289fdfa5a032f9fcddb3e97b212e9e243ad56f0a777ee diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index f6b2b7b713..14a2f5d959 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 5a0dd34c53..7552057da8 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -b488971480de36f755c1ed0e0d496ac356e24dae34ccf7b487468bf6688ab36a +8dc437232bafc3e65a665d2669997bfd4fbac9e26750057fbc506dbebf446386 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 7a51dcb0e6..573aa61fd5 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 d81f8708f7..7c08e443dc 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -a85560746a3ae5032ed463c3352ac6e8170b944dd896e16416e1a4c07ac35a59 +b9818aac64023965d85831055f194602351652647e0dc7b395399d5cbc9ab15a diff --git a/sdk/rust/openidea-plugin/src/host.rs b/sdk/rust/openidea-plugin/src/host.rs index 680fc3875f..7380ea23d5 100644 --- a/sdk/rust/openidea-plugin/src/host.rs +++ b/sdk/rust/openidea-plugin/src/host.rs @@ -263,6 +263,150 @@ mod imp { e.apply_edits(version, &edits).map_err(error) } + pub fn open_editors() -> Result<Vec<OpenEditor>, Error> { + wit::editor::open_editors() + .map(|v| { + v.into_iter() + .map(|e| OpenEditor { path: e.path, language: e.language, dirty: e.dirty, active: e.active }) + .collect() + }) + .map_err(error) + } + pub fn editor_open(path: &str, selection: Option<Range>) -> Result<(), Error> { + wit::editor::open(path, selection.map(range_out)).map_err(error) + } + pub fn editor_set_selections(e: &EditorRes, ranges: &[Range]) -> Result<(), Error> { + e.set_selections(&ranges.iter().copied().map(range_out).collect::<Vec<_>>()).map_err(error) + } + pub fn editor_reveal(e: &EditorRes, range: Range) -> Result<(), Error> { + e.reveal(range_out(range)).map_err(error) + } + pub fn project_search_text(p: &ProjectRes, q: &TextQuery, limit: u32) -> Result<TextSearch, Error> { + let q = wit::workspace::TextQuery { + pattern: q.pattern.clone(), + regex: q.regex, + case_sensitive: q.case_sensitive, + whole_word: q.whole_word, + include: q.include.clone(), + exclude: q.exclude.clone(), + }; + p.search_text(&q, limit) + .map(|s| TextSearch { + limit_hit: s.limit_hit, + matches: s + .matches + .into_iter() + .map(|m| TextMatch { + location: Location { path: m.location.path, range: range_in(m.location.range) }, + line: m.line, + }) + .collect(), + }) + .map_err(error) + } + fn diagnostic_in(d: wit::diagnostics::Diagnostic) -> Diagnostic { + Diagnostic { + range: range_in(d.range), + severity: match d.severity { + wit::diagnostics::Severity::Error => Severity::Error, + wit::diagnostics::Severity::Warning => Severity::Warning, + wit::diagnostics::Severity::Info => Severity::Info, + wit::diagnostics::Severity::Hint => Severity::Hint, + }, + message: d.message, + code: d.code, + source: d.source, + unnecessary: d.tags.iter().any(|s| s == "unnecessary"), + deprecated: d.tags.iter().any(|s| s == "deprecated"), + related: d + .related + .into_iter() + .map(|r| RelatedInformation { + location: Location { path: r.location.path, range: range_in(r.location.range) }, + message: r.message, + }) + .collect(), + } + } + pub fn problems(path: Option<&str>) -> Result<Vec<FileProblems>, Error> { + wit::diagnostics::problems(path) + .map(|v| { + v.into_iter() + .map(|f| FileProblems { + path: f.path, + source: f.source, + diagnostics: f.diagnostics.into_iter().map(diagnostic_in).collect(), + }) + .collect() + }) + .map_err(error) + } + pub fn set_decorations(path: &str, set: &str, items: &[Decoration]) -> Result<(), Error> { + let items = items + .iter() + .map(|d| wit::decorations::Decoration { + range: range_out(d.range), + style: d.style.clone(), + hover: d.hover.clone(), + after: d.after.clone(), + }) + .collect::<Vec<_>>(); + wit::decorations::set(path, set, &items).map_err(error) + } + pub fn clear_decorations(set: &str) -> Result<(), Error> { + wit::decorations::clear(set).map_err(error) + } + pub fn set_file_decoration(path: &str, set: &str, item: &FileDecoration) -> Result<(), Error> { + wit::decorations::set_file( + path, + set, + &wit::decorations::FileDecoration { + badge: item.badge.clone(), + style: item.style.clone(), + tooltip: item.tooltip.clone(), + }, + ) + .map_err(error) + } + pub fn clear_file_decorations(set: &str) -> Result<(), Error> { + wit::decorations::clear_file(set).map_err(error) + } + pub fn vcs_log(p: &ProjectRes, path: Option<&str>, limit: u32) -> Result<Vec<CommitInfo>, Error> { + wit::vcs::log(p, path, limit) + .map(|v| { + v.into_iter() + .map(|c| CommitInfo { + id: c.id, + short_id: c.short_id, + author: c.author, + author_email: c.author_email, + date: c.date, + subject: c.subject, + body: c.body, + parents: c.parents, + }) + .collect() + }) + .map_err(error) + } + pub fn vcs_blame(p: &ProjectRes, path: &str) -> Result<Vec<BlameLine>, Error> { + wit::vcs::blame(p, path) + .map(|v| { + v.into_iter() + .map(|c| BlameLine { + line: c.line, + commit: c.commit, + author: c.author, + date: c.date, + summary: c.summary, + }) + .collect() + }) + .map_err(error) + } + pub fn vcs_diff(p: &ProjectRes, path: Option<&str>, against: Option<&str>) -> Result<Option<String>, Error> { + wit::vcs::diff(p, path, against).map_err(error) + } pub fn vcs_status(p: &ProjectRes) -> Result<Option<RepositoryStatus>, Error> { wit::vcs::status(p) .map(|s| { @@ -641,6 +785,24 @@ pub struct Project { } impl Project { + /// Find in Files with unsaved text, project excludes, cancellation and a 10,000 match cap. + /// Requires project.read; locations use zero-based lines and UTF-16 columns. + pub fn search_text(&self, query: &TextQuery, limit: u32) -> Result<TextSearch, Error> { + imp::project_search_text(&self.inner, query, limit) + } + /// Trusted project history, newest first, at most 1000 commits. Requires vcs.read. + pub fn vcs_log(&self, path: Option<&str>, limit: u32) -> Result<Vec<CommitInfo>, Error> { + imp::vcs_log(&self.inner, path, limit) + } + /// Trusted project attribution including unsaved text. Requires vcs.read. + pub fn vcs_blame(&self, path: &str) -> Result<Vec<BlameLine>, Error> { + imp::vcs_blame(&self.inner, path) + } + /// Disk working tree versus HEAD or a revision, failing above 4 MiB. Requires vcs.read and trust. + pub fn vcs_diff(&self, path: Option<&str>, against: Option<&str>) -> Result<Option<String>, Error> { + imp::vcs_diff(&self.inner, path, against) + } + /// Absolute path of the root. Needs `project.read`. pub fn root(&self) -> Result<String, Error> { imp::project_root(&self.inner) @@ -925,6 +1087,15 @@ pub struct TextEditor { } impl TextEditor { + /// Changes this window's selections. Commands/events only; no capability needed. + pub fn set_selections(&self, ranges: &[Range]) -> Result<(), Error> { + imp::editor_set_selections(&self.inner, ranges) + } + /// Scrolls a range into view in this window. Commands/events only; no capability needed. + pub fn reveal(&self, range: Range) -> Result<(), Error> { + imp::editor_reveal(&self.inner, range) + } + pub fn path(&self) -> String { imp::editor_path(&self.inner) } @@ -1266,8 +1437,10 @@ 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). +/// Executes a stable action or plugin command in the invoking window (API 1.4). +/// Requires high-risk `ide.commands`, except for this plugin's declared commands. +/// IDE actions return `None`; plugin commands return their result. Waiting instances +/// cannot re-enter themselves; command nesting is bounded. pub fn execute_command(id: &str, arg: Option<&str>) -> Result<Option<String>, Error> { imp::execute_command(id, arg) } @@ -1311,3 +1484,33 @@ pub fn output_clear(channel: &str) -> Result<(), Error> { pub fn output_reveal(channel: &str) -> Result<(), Error> { imp::output_reveal(channel) } + +/// The invoking window's open editors. Requires editor.read; commands/events only. +pub fn open_editors() -> Result<Vec<OpenEditor>, Error> { + imp::open_editors() +} +/// Opens a project file (project.read) or plugin-dir file, optionally selecting a range. +/// Only available in commands/events of a window. +pub fn open_editor(path: &str, selection: Option<Range>) -> Result<(), Error> { + imp::editor_open(path, selection) +} +/// The invoking window's project Problems view. Requires project.read. Empty for remote projects. +pub fn problems(path: Option<&str>) -> Result<Vec<FileProblems>, Error> { + imp::problems(path) +} +/// Replace a file's editor decorations. Requires project.read; 10,000 items/file, 50 sets. +pub fn set_decorations(path: &str, set: &str, items: &[Decoration]) -> Result<(), Error> { + imp::set_decorations(path, set, items) +} +/// Clear this plugin's editor decoration set in all projects. Requires project.read. +pub fn clear_decorations(set: &str) -> Result<(), Error> { + imp::clear_decorations(set) +} +/// Set a project-tree badge/style. Requires project.read. Badge is at most two characters. +pub fn set_file_decoration(path: &str, set: &str, item: &FileDecoration) -> Result<(), Error> { + imp::set_file_decoration(path, set, item) +} +/// Clear this plugin's tree decoration set in all projects. Requires project.read. +pub fn clear_file_decorations(set: &str) -> Result<(), Error> { + imp::clear_file_decorations(set) +} diff --git a/sdk/rust/openidea-plugin/src/mock.rs b/sdk/rust/openidea-plugin/src/mock.rs index c9067e9063..ec2a0131ed 100644 --- a/sdk/rust/openidea-plugin/src/mock.rs +++ b/sdk/rust/openidea-plugin/src/mock.rs @@ -38,6 +38,8 @@ pub struct MockTask { type CommandHandler = dyn Fn(Option<&str>) -> Result<Option<String>, Error>; +type SearchHandler = Box<dyn Fn(&TextQuery, u32) -> Result<TextSearch, Error>>; + type NetHandler = Box<dyn Fn(&HttpRequest) -> Result<HttpResponse, Error>>; type ProcessHandler = Box<dyn Fn(&[String], Option<&str>) -> Result<ProcessOutput, Error>>; @@ -124,6 +126,15 @@ struct State { declared_secrets: BTreeSet<String>, commands: BTreeMap<String, Rc<CommandHandler>>, command_depth: usize, + owned_commands: BTreeSet<String>, + search: Option<SearchHandler>, + commits: Vec<CommitInfo>, + blame: BTreeMap<String, Vec<BlameLine>>, + patch: Option<String>, + restricted: bool, + decorations: BTreeMap<(String, String), Vec<Decoration>>, + file_decorations: BTreeMap<(String, String), FileDecoration>, + revealed_ranges: Vec<Range>, loopback_queries: VecDeque<Option<String>>, net: Option<NetHandler>, requests: Vec<HttpRequest>, @@ -171,6 +182,7 @@ pub struct MockHost { /// Every capability a plugin can hold, except `process:`/`net:`/`fs.read:`. const ALL: &[&str] = &[ + "ide.commands", "project.read", "editor.read", "editor.write", @@ -183,6 +195,41 @@ const ALL: &[&str] = &[ ]; impl MockHost { + /// Registers one of this plugin's declared commands, callable without ide.commands. + pub fn on_own_command(&self, id: &str, handler: impl Fn(Option<&str>) -> Result<Option<String>, Error> + 'static) { + let stable = format!("plugin.mock.{id}"); + self.on_command(&stable, handler); + self.state.borrow_mut().owned_commands.insert(stable); + } + + /// Supplies search responses without duplicating the IDE search engine. + pub fn on_search(&self, handler: impl Fn(&TextQuery, u32) -> Result<TextSearch, Error> + 'static) { + self.state.borrow_mut().search = Some(Box::new(handler)); + } + /// Supplies read-only repository data. + pub fn set_vcs_reads(&self, commits: Vec<CommitInfo>, path: &str, blame: Vec<BlameLine>, patch: Option<String>) { + let mut s = self.state.borrow_mut(); + s.commits = commits; + s.blame.insert(path.into(), blame); + s.patch = patch; + } + /// Simulates Restricted Mode for new VCS read APIs. + pub fn set_restricted(&self, restricted: bool) { + self.state.borrow_mut().restricted = restricted; + } + /// Editor decoration snapshots keyed by (set id, absolute path). + pub fn decorations(&self) -> BTreeMap<(String, String), Vec<Decoration>> { + self.state.borrow().decorations.clone() + } + /// Tree decoration snapshots keyed by (set id, absolute path). + pub fn file_decorations(&self) -> BTreeMap<(String, String), FileDecoration> { + self.state.borrow().file_decorations.clone() + } + /// Ranges requested to scroll into view. + pub fn revealed_ranges(&self) -> Vec<Range> { + self.state.borrow().revealed_ranges.clone() + } + /// Installs a mock granting the usual capabilities, with project `/project`. pub fn install() -> Self { let state = Rc::new(RefCell::new(State { @@ -447,7 +494,9 @@ impl MockHost { /// 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)); + let mut state = self.state.borrow_mut(); + state.owned_commands.remove(id); + state.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>) { @@ -710,6 +759,9 @@ pub mod current { } pub fn execute_command(id: &str, arg: Option<&str>) -> Result<Option<String>, Error> { let handler = with(|s| { + if !s.owned_commands.contains(id) { + require(s, "ide.commands")?; + } if s.command_depth >= 8 { return Err(Error::Invalid("command nesting limit (8)".into())); } @@ -1207,6 +1259,204 @@ pub mod current { }) } + pub fn open_editors() -> Result<Vec<OpenEditor>, Error> { + with(|s| { + require(s, "editor.read")?; + Ok(s.editor + .iter() + .map(|e| OpenEditor { + path: e.path.clone(), + language: e.language.clone(), + dirty: e.version > 1, + active: true, + }) + .collect()) + }) + } + pub fn editor_open(path: &str, selection: Option<Range>) -> Result<(), Error> { + let text = with(|s| { + if is_private_path(path) { + return s.external.get(path).cloned().ok_or_else(|| Error::NotFound(path.into())); + } + require(s, "project.read")?; + let p = MockProject { root: s.root.clone().ok_or_else(|| Error::Invalid("no project".into()))? }; + let rel = rel_in_root(&p, path)?; + s.files.get(rel).or_else(|| s.files.get(path)).cloned().ok_or_else(|| Error::NotFound(path.into())) + })?; + with(|s| { + let path = + if path.starts_with('/') { path.into() } else { format!("{}/{path}", s.root.as_deref().unwrap()) }; + s.editor = Some(Editor { + path, + language: "text".into(), + text, + version: 1, + selections: selection.into_iter().collect(), + }); + }); + Ok(()) + } + fn valid_ranges(text: &str, ranges: &[Range]) -> bool { + ranges.iter().all(|r| matches!((crate::text::offset(text, r.start), crate::text::offset(text, r.end)), (Some(a), Some(b)) if a <= b)) + } + pub fn editor_set_selections(_: &EditorRes, ranges: &[Range]) -> Result<(), Error> { + editor(|_, e| { + if ranges.is_empty() || ranges.len() > 1000 || !valid_ranges(&e.text, ranges) { + return Err(Error::Invalid("invalid selections".into())); + } + e.selections = ranges.to_vec(); + Ok(()) + }) + } + pub fn editor_reveal(_: &EditorRes, range: Range) -> Result<(), Error> { + editor(|s, e| { + if !valid_ranges(&e.text, &[range]) { + return Err(Error::Invalid("invalid range".into())); + } + s.revealed_ranges.push(range); + Ok(()) + }) + } + pub fn project_search_text(_: &ProjectRes, query: &TextQuery, limit: u32) -> Result<TextSearch, Error> { + with(|s| { + require(s, "project.read")?; + if limit == 0 { + return Ok(TextSearch::default()); + } + let mut result = match &s.search { + Some(f) => f(query, limit.min(10_000))?, + None => TextSearch::default(), + }; + result.limit_hit |= result.matches.len() > limit.min(10_000) as usize; + result.matches.truncate(limit.min(10_000) as usize); + Ok(result) + }) + } + pub fn problems(path: Option<&str>) -> Result<Vec<FileProblems>, Error> { + with(|s| { + require(s, "project.read")?; + let p = MockProject { root: s.root.clone().ok_or_else(|| Error::Invalid("no project".into()))? }; + let wanted = path.map(|path| rel_in_root(&p, path).map(|rel| format!("{}/{rel}", p.root))).transpose()?; + Ok(s.diagnostics + .iter() + .chain(s.provider_diagnostics.iter()) + .filter(|(path, _)| wanted.as_ref().is_none_or(|p| p == *path)) + .map(|(path, diagnostics)| FileProblems { + path: path.clone(), + source: "mock".into(), + diagnostics: diagnostics.clone(), + }) + .collect()) + }) + } + fn decoration_path(s: &State, path: &str) -> Result<String, Error> { + let p = MockProject { root: s.root.clone().ok_or_else(|| Error::Invalid("no project".into()))? }; + Ok(format!("{}/{}", p.root, rel_in_root(&p, path)?)) + } + fn style(s: &str) -> bool { + matches!( + s, + "highlight" + | "search" + | "added" + | "modified" + | "removed" + | "warning" + | "error" + | "info" + | "underline" + | "strikethrough" + | "muted" + ) + } + pub fn set_decorations(path: &str, set: &str, items: &[Decoration]) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + let path = decoration_path(s, path)?; + let mut next = s.decorations.clone(); + next.insert((set.into(), path.clone()), items.iter().filter(|d| style(&d.style)).cloned().collect()); + let names: BTreeSet<_> = next.keys().map(|(set, _)| set).collect(); + let count: usize = next.iter().filter(|((_, p), _)| *p == path).map(|(_, i)| i.len()).sum(); + if set.is_empty() || set.len() > 128 || names.len() > 50 || count > 10_000 { + return Err(Error::Invalid("decoration limit".into())); + } + s.decorations = next; + Ok(()) + }) + } + pub fn clear_decorations(set: &str) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + s.decorations.retain(|(id, _), _| id != set); + Ok(()) + }) + } + pub fn set_file_decoration(path: &str, set: &str, item: &FileDecoration) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + let path = decoration_path(s, path)?; + let mut next = s.file_decorations.clone(); + next.remove(&(set.into(), path.clone())); + if style(&item.style) { + next.insert((set.into(), path), item.clone()); + } + let names: BTreeSet<_> = next.keys().map(|(set, _)| set).collect(); + if set.is_empty() + || set.len() > 128 + || names.len() > 50 + || item.badge.as_ref().is_some_and(|b| b.chars().count() > 2) + { + return Err(Error::Invalid("file decoration limit".into())); + } + s.file_decorations = next; + Ok(()) + }) + } + pub fn clear_file_decorations(set: &str) -> Result<(), Error> { + with(|s| { + require(s, "project.read")?; + s.file_decorations.retain(|(id, _), _| id != set); + Ok(()) + }) + } + fn vcs_read(s: &State) -> Result<(), Error> { + require(s, "vcs.read")?; + if s.restricted { + return Err(Error::Failed("project is in Restricted Mode".into())); + } + Ok(()) + } + pub fn vcs_log(p: &ProjectRes, path: Option<&str>, limit: u32) -> Result<Vec<CommitInfo>, Error> { + with(|s| { + vcs_read(s)?; + if let Some(path) = path { + rel_in_root(p, path)?; + } + Ok(s.commits.iter().take(limit.min(1000) as usize).cloned().collect()) + }) + } + pub fn vcs_blame(p: &ProjectRes, path: &str) -> Result<Vec<BlameLine>, Error> { + with(|s| { + vcs_read(s)?; + rel_in_root(p, path)?; + Ok(s.blame.get(path).cloned().unwrap_or_default()) + }) + } + pub fn vcs_diff(p: &ProjectRes, path: Option<&str>, against: Option<&str>) -> Result<Option<String>, Error> { + with(|s| { + vcs_read(s)?; + if let Some(path) = path { + rel_in_root(p, path)?; + } + if against.is_some_and(|r| r.is_empty() || r.starts_with('-') || r.contains('\0')) { + return Err(Error::Invalid("invalid revision".into())); + } + if s.patch.as_ref().is_some_and(|p| p.len() > 4 << 20) { + return Err(Error::Failed("diff exceeds 4 MiB".into())); + } + Ok(s.patch.clone()) + }) + } pub fn vcs_status(_: &ProjectRes) -> Result<Option<RepositoryStatus>, Error> { with(|s| { require(s, "vcs.read")?; diff --git a/sdk/rust/openidea-plugin/src/types.rs b/sdk/rust/openidea-plugin/src/types.rs index 7d59cdaec4..0311a17213 100644 --- a/sdk/rust/openidea-plugin/src/types.rs +++ b/sdk/rust/openidea-plugin/src/types.rs @@ -523,3 +523,77 @@ impl Event { Self::Other { kind, data } } } + +/// An editor in the invoking window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpenEditor { + pub path: String, + pub language: String, + pub dirty: bool, + pub active: bool, +} +/// Find in Files options. Include and exclude are project-relative globs. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextQuery { + pub pattern: String, + pub regex: bool, + pub case_sensitive: bool, + pub whole_word: bool, + pub include: Vec<String>, + pub exclude: Vec<String>, +} +/// A text search match with zero-based UTF-16 coordinates. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TextMatch { + pub location: Location, + pub line: String, +} +/// Bounded text search result. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct TextSearch { + pub matches: Vec<TextMatch>, + pub limit_hit: bool, +} +/// A file's Problems view diagnostics from one source. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileProblems { + pub path: String, + pub source: String, + pub diagnostics: Vec<Diagnostic>, +} +/// An editor annotation. Styles are fixed theme-token names; unknown names are ignored. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Decoration { + pub range: Range, + pub style: String, + pub hover: Option<String>, + pub after: Option<String>, +} +/// A project-tree annotation. Badge is at most two Unicode characters. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FileDecoration { + pub badge: Option<String>, + pub style: String, + pub tooltip: Option<String>, +} +/// Repository history metadata. Date is Unix seconds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CommitInfo { + pub id: String, + pub short_id: String, + pub author: String, + pub author_email: String, + pub date: i64, + pub subject: String, + pub body: String, + pub parents: Vec<String>, +} +/// Attribution for a zero-based document line. Date is Unix seconds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BlameLine { + pub line: u32, + pub commit: String, + pub author: String, + pub date: i64, + pub summary: String, +} diff --git a/sdk/rust/openidea-plugin/tests/api14_stage2.rs b/sdk/rust/openidea-plugin/tests/api14_stage2.rs new file mode 100644 index 0000000000..2241d3792d --- /dev/null +++ b/sdk/rust/openidea-plugin/tests/api14_stage2.rs @@ -0,0 +1,94 @@ +use openidea_plugin::{Decoration, Error, FileDecoration, Range, TextQuery, TextSearch, host, mock::MockHost}; + +#[test] +fn command_permission_distinguishes_own_commands() { + let mock = MockHost::install().with_capabilities(&[]); + for id in ["test.action", "plugin.other.run", "plugin.mock.other.run"] { + mock.on_command(id, |_| Ok(Some("ok".into()))); + } + mock.on_own_command("run", |_| Ok(Some("ok".into()))); + for id in ["test.action", "plugin.other.run", "plugin.mock.other.run"] { + assert!(matches!(host::execute_command(id, None), Err(Error::Denied(c)) if c == "ide.commands")); + } + assert_eq!(host::execute_command("plugin.mock.run", None).unwrap().as_deref(), Some("ok")); + let _mock = mock.with_capabilities(&["ide.commands"]); + assert!(host::execute_command("test.action", None).is_ok()); + assert!(host::execute_command("plugin.other.run", None).is_ok()); +} + +#[test] +fn workbench_wrappers_enforce_grants_and_editor_ranges_need_no_grant() { + let mock = MockHost::install().with_capabilities(&[]); + mock.open_editor("/project/a.txt", "text", "😀text", &[]); + mock.add_file("a.txt", "disk"); + let ctx = mock.invocation(); + let editor = ctx.editor().unwrap(); + editor + .set_selections(&[Range::new(openidea_plugin::Position::new(0, 2), openidea_plugin::Position::new(0, 4))]) + .unwrap(); + editor.reveal(Range::default()).unwrap(); + assert_eq!(mock.revealed_ranges(), [Range::default()]); + let project = ctx.project().unwrap(); + assert!(matches!(host::open_editors(), Err(Error::Denied(c)) if c == "editor.read")); + assert!(host::open_editor("a.txt", None).is_err()); + assert!(project.search_text(&TextQuery::default(), 1).is_err()); + assert!(host::problems(None).is_err()); + assert!(host::set_decorations("a.txt", "set", &[]).is_err()); + assert!(host::clear_decorations("set").is_err()); + assert!(host::clear_file_decorations("set").is_err()); + assert!(project.vcs_log(None, 1).is_err()); + assert!(project.vcs_blame("a.txt").is_err()); + assert!(project.vcs_diff(None, None).is_err()); + let _mock = mock.with_capabilities(&["project.read", "editor.read", "vcs.read"]); + assert_eq!(host::open_editors().unwrap()[0].language, "text"); + host::open_editor("a.txt", Some(Range::default())).unwrap(); + assert!(host::open_editor("../outside", None).is_err()); + assert!(host::problems(None).unwrap().is_empty()); +} + +#[test] +fn decorations_replace_clear_validate_styles_badges_paths_and_limits() { + let mock = MockHost::install(); + let item = |style: &str| Decoration { + range: Range::default(), + style: style.into(), + hover: None, + after: Some("text".into()), + }; + host::set_decorations("a.txt", "test", &[item("highlight"), item("unknown")]).unwrap(); + assert_eq!(mock.decorations().values().next().unwrap().len(), 1); + assert!(host::set_decorations("../outside", "test", &[]).is_err()); + host::set_decorations("a.txt", "test", &[]).unwrap(); + assert!(mock.decorations().values().next().unwrap().is_empty()); + host::clear_decorations("test").unwrap(); + assert!(mock.decorations().is_empty()); + let file = |badge: &str| FileDecoration { badge: Some(badge.into()), style: "added".into(), tooltip: None }; + assert!(host::set_file_decoration("a.txt", "test", &file("abc")).is_err()); + host::set_file_decoration("a.txt", "test", &file("😀a")).unwrap(); + host::clear_file_decorations("test").unwrap(); + assert!(mock.file_decorations().is_empty()); + for i in 0..50 { + host::set_decorations("a.txt", &format!("set{i}"), &[]).unwrap(); + } + assert!(host::set_decorations("a.txt", "overflow", &[]).is_err()); +} + +#[test] +fn search_limits_and_vcs_trust_are_modelled() { + let mock = MockHost::install(); + mock.on_search(|query, limit| { + assert_eq!(query.pattern, "needle"); + assert_eq!(limit, 10_000); + Ok(TextSearch::default()) + }); + let ctx = mock.invocation(); + let project = ctx.project().unwrap(); + project.search_text(&TextQuery { pattern: "needle".into(), ..Default::default() }, u32::MAX).unwrap(); + mock.set_vcs_reads(Vec::new(), "a.txt", Vec::new(), Some("patch".into())); + assert_eq!(project.vcs_diff(None, None).unwrap().as_deref(), Some("patch")); + assert!(project.vcs_diff(None, Some("--output=x")).is_err()); + mock.set_restricted(true); + assert!(project.vcs_log(None, 1).is_err()); + assert!(project.vcs_blame("a.txt").is_err()); + assert!(project.vcs_diff(None, None).is_err()); +} diff --git a/sdk/rust/openidea-plugin/wit/decorations.wit b/sdk/rust/openidea-plugin/wit/decorations.wit new file mode 100644 index 0000000000..1c5a033e6c --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/decorations.wit @@ -0,0 +1,22 @@ +package openidea:plugin@1.4.0; + +/// Project-scoped decorations (API 1.4). Requires project.read; paths must be inside +/// an open project. Sets belong to the plugin and disappear when it stops. +/// Styles: highlight, search, added, modified, removed, warning, error, info, +/// underline, strikethrough, muted. Unknown styles are ignored. Theme tokens only. +interface decorations { + use types.{error, range}; + /// An editor annotation; after is plain text shown after the range. + record decoration { range: range, style: string, hover: option<string>, after: option<string> } + /// A project-tree annotation; badge is at most two Unicode characters. + record file-decoration { badge: option<string>, style: string, tooltip: option<string> } + /// Replace this set for a file. At most 10,000 items/file and 50 editor sets/plugin. + /// Metadata is bounded to 4 MiB per plugin. Unknown styles are ignored. + set: func(path: string, set-id: string, items: list<decoration>) -> result<_, error>; + /// Remove this editor set from every file/project. + clear: func(set-id: string) -> result<_, error>; + /// Replace this set's tree annotation for a file; at most 50 tree sets/plugin. + set-file: func(path: string, set-id: string, item: file-decoration) -> result<_, error>; + /// Remove this tree set from every file/project. + clear-file: func(set-id: string) -> result<_, error>; +} diff --git a/sdk/rust/openidea-plugin/wit/host.wit b/sdk/rust/openidea-plugin/wit/host.wit index d81877524c..c5ce20fbec 100644 --- a/sdk/rust/openidea-plugin/wit/host.wit +++ b/sdk/rust/openidea-plugin/wit/host.wit @@ -115,6 +115,7 @@ 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. + /// Requires high-risk `ide.commands`, except for this plugin's own commands. execute: func(id: string, arg: option<string>) -> result<option<string>, error>; } diff --git a/sdk/rust/openidea-plugin/wit/io.wit b/sdk/rust/openidea-plugin/wit/io.wit index 2ebc7a889d..b27e48d622 100644 --- a/sdk/rust/openidea-plugin/wit/io.wit +++ b/sdk/rust/openidea-plugin/wit/io.wit @@ -3,6 +3,11 @@ package openidea:plugin@1.4.0; /// Problems in files, shown in the editor and the Problems view. interface diagnostics { use types.{error, range, location}; + /// Problems reported by a source for a file in this window's project. + record file-problems { path: string, source: string, diagnostics: list<diagnostic> } + /// Current Problems view snapshot, optionally filtered to a project file. + /// Requires project.read and an invoking window. Empty for remote projects. + problems: func(path: option<string>) -> result<list<file-problems>, error>; enum severity { error, diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index acb2a8e7aa..3a804b2b95 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -17,6 +17,7 @@ world plugin { import fs; import workspace; import editor; + import decorations; import invocation; import vcs; import commit; diff --git a/sdk/rust/openidea-plugin/wit/workspace.wit b/sdk/rust/openidea-plugin/wit/workspace.wit index 851d14d578..7c1e9dd19b 100644 --- a/sdk/rust/openidea-plugin/wit/workspace.wit +++ b/sdk/rust/openidea-plugin/wit/workspace.wit @@ -39,10 +39,28 @@ interface workspace { location: location, } + /// Text search options. Include/exclude are project-relative globs, as in Find in Files. + record text-query { + pattern: string, + regex: bool, + case-sensitive: bool, + whole-word: bool, + %include: list<string>, + exclude: list<string>, + } + /// A match with zero-based lines and UTF-16 columns, and its displayed line. + record text-match { location: location, line: string } + /// Bounded search results; limit-hit says there may be more matches. + record text-search { matches: list<text-match>, limit-hit: bool } + /// A project open in the IDE. resource project { /// Absolute path of the project root. Requires `project.read`. root: func() -> result<string, error>; + /// Find in Files with unsaved documents and project excludes. Requires project.read. + /// Cancellable, at most 10,000 matches. Zero limit returns no matches. + /// Line previews are capped at 4096 UTF-8 bytes, results at 4 MiB (limit-hit). + search-text: func(query: text-query, limit: u32) -> result<text-search, error>; /// Reads a UTF-8 text file inside the project (absolute, or relative /// to the root); paths leaving the root are refused. Unsaved editor /// contents win over the disk. A missing path is `not-found`. @@ -94,10 +112,22 @@ interface editor { text: string, } + /// An editor in the invoking window. + record open-editor { path: string, language: string, dirty: bool, active: bool } + /// Only from commands/events of a window. Requires editor.read. + open-editors: func() -> result<list<open-editor>, error>; + /// Open a project file (project.read) or a file in plugin-dir, selecting a range. + /// Only from commands/events of a window. Paths follow views.open-location. + open: func(path: string, selection: option<range>) -> result<_, error>; + /// A file open in an editor. resource text-editor { /// Absolute path of the file. path: func() -> string; + /// Replace selections in this window's editor. No capability; commands/events only. + set-selections: func(selections: list<range>) -> result<_, error>; + /// Scroll a range into view in this window's editor. No capability; commands/events only. + reveal: func(range: range) -> result<_, error>; /// Language id (`rust`, `solidity`, …). language: func() -> string; /// Current version and text. Requires `editor.read`. @@ -151,6 +181,22 @@ interface vcs { changed-files: u32, } + /// A commit in repository history; date is Unix seconds. + record commit-info { + id: string, short-id: string, author: string, author-email: string, + date: s64, subject: string, body: string, parents: list<string>, + } + /// One zero-based document line's attribution; date is Unix seconds. + record blame-line { line: u32, commit: string, author: string, date: s64, summary: string } + /// Newest commits first, at most 1000. Trusted projects only; requires vcs.read. + log: func(project: borrow<project>, path: option<string>, limit: u32) -> result<list<commit-info>, error>; + /// Includes unsaved text, with changed lines attributed to uncommitted changes. + /// Trusted projects only; requires vcs.read. Paths must be inside the project. + blame: func(project: borrow<project>, path: string) -> result<list<blame-line>, error>; + /// Working tree versus HEAD or against. None outside a repository. Disk text only. + /// Fails above 4 MiB. Trusted projects only; requires vcs.read. + diff: func(project: borrow<project>, path: option<string>, against: option<string>) -> result<option<string>, error>; + /// `none` when the project is not in a repository. Requires `vcs.read`. status: func(project: borrow<project>) -> result<option<repository-status>, error>; /// Configured remotes (`name`, fetch `url`), in order. Requires `vcs.read`. diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rs index 9fda5603e7..62da25497b 100644 --- a/src-tauri/src/commands/mod.rs +++ b/src-tauri/src/commands/mod.rs @@ -500,6 +500,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> { plugin::plugin_post_events, plugin::plugin_event_kinds, plugin::plugin_status_items, + plugin::plugin_decoration_sets, plugin::plugin_context_keys, plugin::plugin_cancel_task, plugin::plugin_answer_prompt, diff --git a/src-tauri/src/commands/plugin.rs b/src-tauri/src/commands/plugin.rs index aa52f4e111..64bffa3e1d 100644 --- a/src-tauri/src/commands/plugin.rs +++ b/src-tauri/src/commands/plugin.rs @@ -927,3 +927,12 @@ pub async fn plugin_program( }; blocking(move || host.program_for_project(&plugin_id, &program, root.as_deref()).map(Into::into)).await } + +/// Project-scoped decoration snapshots; the window filters to its current root. +#[tauri::command] +#[specta::specta] +pub fn plugin_decoration_sets( + state: State<'_, AppState>, +) -> std::collections::BTreeMap<String, Vec<ide_host::plugins::DecorationSet>> { + state.plugins.decoration_sets() +} diff --git a/src/bindings.ts b/src/bindings.ts index 38966e761a..e191938677 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1114,6 +1114,8 @@ export const commands = { pluginEventKinds: () => __TAURI_INVOKE<EventKind[]>("plugin_event_kinds"), /** Every plugin status bar item (later changes arrive as `statusItemChanged`). */ pluginStatusItems: () => __TAURI_INVOKE<PluginStatusItem[]>("plugin_status_items"), + /** Project-scoped decoration snapshots; the window filters to its current root. */ + pluginDecorationSets: () => __TAURI_INVOKE<{ [key in string]: DecorationSet[] }>("plugin_decoration_sets"), /** Plugin context keys in effect for this window (later changes arrive as `contextChanged`). */ pluginContextKeys: () => __TAURI_INVOKE<PluginContextKey[]>("plugin_context_keys"), /** Cancels a plugin task (`taskStarted` with `cancellable`). */ @@ -3199,6 +3201,24 @@ export type DebuggerSettings = { python?: PythonDebuggerSettings, }; +/** An editor decoration. */ +export type Decoration = { + range: Range, + style: string, + hover: string | null, + after: string | null, +}; + +/** A plugin-owned editor or project-tree decoration set for one file. */ +export type DecorationSet = { + root: IpcPath, + path: IpcPath, + setId: string, + tree: boolean, + items: Decoration[], + file: FileDecoration | null, +}; + /** A deleted local branch, enough to restore it (IDEA's "Restore" notification action). */ export type DeletedBranch = { name: string, @@ -3906,6 +3926,13 @@ export type FileCoverage = { branchesCovered: number, }; +/** A tree decoration. */ +export type FileDecoration = { + badge: string | null, + style: string, + tooltip: string | null, +}; + export type FileEdit = { kind: "edit"; path: IpcPath; edits: TextEdit[]; /** LSP TextDocumentEdit version; null/unversioned edits use content preconditions. */ version?: number | null } | { kind: "create"; path: IpcPath; overwrite: boolean } | { kind: "rename"; from: IpcPath; to: IpcPath } | { kind: "delete"; path: IpcPath; recursive: boolean }; @@ -6145,6 +6172,12 @@ export type PluginEndpoint = { export type PluginEvent = /** Plugins, their status or their contributions changed: re-fetch `plugin_list`. */ { type: "commandsChanged" } | +/** Complete replacement of one plugin's project-scoped decorations. */ +{ type: "decorationsChanged"; pluginId: string; sets: DecorationSet[] } | +/** Open a file in the invoking window. */ +{ type: "editorOpen"; path: IpcPath; selection: Range | null } | +/** Change selection or scrolling only in this window's already open editor. */ +{ type: "editorRanges"; path: IpcPath; ranges: Range[]; reveal: boolean } | /** 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. */ diff --git a/src/features/mcp/index.ts b/src/features/mcp/index.ts index ce7163ef2a..a64faeef54 100644 --- a/src/features/mcp/index.ts +++ b/src/features/mcp/index.ts @@ -30,7 +30,7 @@ export function activate(): () => void { let timer: ReturnType<typeof setTimeout> | null = null; const report = () => { timer = null; - if (isRemoteWindow() || !useProject.getState().project) return; + if (!useProject.getState().project) return; const paths = openEditorPaths(); const editor = activeEditor(); const focused = document.hasFocus(); diff --git a/src/features/mcp/reporters.test.ts b/src/features/mcp/reporters.test.ts index 2c1598c0f6..4741eb2c7f 100644 --- a/src/features/mcp/reporters.test.ts +++ b/src/features/mcp/reporters.test.ts @@ -106,10 +106,11 @@ describe("MCP editor reports", () => { expect(state.reportOpen).toHaveBeenCalledTimes(2); expect(state.reportFocused).toHaveBeenCalledTimes(2); }); - it("does not report remote windows or after disposal", async () => { + it("forwards remote editor reports and stops after disposal", async () => { state.remote = true; await vi.advanceTimersByTimeAsync(300); - expect(state.reportOpen).not.toHaveBeenCalled(); + expect(state.reportOpen).toHaveBeenCalledWith(["/p/a.txt"]); + state.reportOpen.mockClear(); state.remote = false; state.registryChanged(); stop(); diff --git a/src/features/plugins/__tests__/decorations.test.ts b/src/features/plugins/__tests__/decorations.test.ts new file mode 100644 index 0000000000..1f8460f034 --- /dev/null +++ b/src/features/plugins/__tests__/decorations.test.ts @@ -0,0 +1,93 @@ +import { afterEach, beforeEach, expect, it } from "vitest"; +import { EditorState } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import type { DecorationSet } from "@/bindings"; +import { _addEditor, _removeEditor, type EditorDocContext, type TextEditorHandle } from "@/editor/api"; +import { useProject } from "@/platform/project"; +import { getFileDecoration } from "@/workbench/contributions"; +import { decorationExtension, setPluginDecorations } from "../decorations"; +import { capabilityDescription } from "../consent"; +import { handleRuntimeEvent } from "../runtimeUi"; + +const ctx: EditorDocContext = { doc: 1, path: "/p/a.txt", language: "text", uiMode: null, readOnly: false }; +let editor: TextEditorHandle; +const range = { start: { line: 0, col: 2 }, end: { line: 0, col: 4 } }; +const set = (root = "/p"): DecorationSet => ({ + root, + path: "/p/a.txt", + setId: "test", + tree: false, + items: [{ range, style: "highlight", hover: "hover", after: "<plain>" }], + file: null, +}); +beforeEach(() => { + useProject.setState({ project: { root: "/p", trusted: true } as never }); + editor = { + ctx, + view: new EditorView({ + state: EditorState.create({ + doc: "😀text", + extensions: [EditorState.allowMultipleSelections.of(true), decorationExtension(ctx)], + }), + parent: document.body, + }), + }; + _addEditor(editor); +}); +afterEach(() => { + setPluginDecorations("test", []); + _removeEditor(editor); + editor.view.destroy(); + useProject.setState({ project: null }); +}); + +it("renders plain annotations, maps them through edits, and withdraws them", () => { + setPluginDecorations("test", [set()]); + expect(editor.view.dom.textContent).toContain("<plain>"); + expect(editor.view.dom.querySelector('[title="hover"]')?.textContent).toBe("te"); + expect(editor.view.dom.querySelector("plain")).toBeNull(); + editor.view.dispatch({ changes: { from: 0, insert: "x" } }); + expect(editor.view.dom.querySelector('[title="hover"]')?.textContent).toBe("te"); + setPluginDecorations("test", []); + expect(editor.view.dom.textContent).not.toContain("<plain>"); +}); + +it("filters project roots and unknown styles and replaces tree badges", () => { + setPluginDecorations("test", [set("/other")]); + expect(editor.view.dom.textContent).not.toContain("<plain>"); + const unknown = set(); + unknown.items[0]!.style = "unknown"; + setPluginDecorations("test", [unknown]); + expect(editor.view.dom.textContent).not.toContain("<plain>"); + const tree = { ...set(), tree: true, items: [], file: { style: "modified", badge: "M", tooltip: "changed" } }; + setPluginDecorations("test", [tree]); + expect(getFileDecoration("/p/a.txt")?.badge).toBe("M"); + setPluginDecorations("test", []); + expect(getFileDecoration("/p/a.txt")?.badge).toBeUndefined(); +}); + +it("selects UTF-16 ranges and reveals without changing text", () => { + handleRuntimeEvent({ type: "editorRanges", path: ctx.path, ranges: [range], reveal: false }); + expect(editor.view.state.selection.main.from).toBe(2); + expect(editor.view.state.selection.main.to).toBe(4); + handleRuntimeEvent({ type: "editorRanges", path: ctx.path, ranges: [range], reveal: true }); + expect(editor.view.state.doc.toString()).toBe("😀text"); + handleRuntimeEvent({ + type: "editorRanges", + path: "/other/a.txt", + ranges: [{ start: { line: 0, col: 0 }, end: { line: 0, col: 1 } }], + reveal: false, + }); + expect(editor.view.state.selection.main.from).toBe(2); +}); + +it("describes ide.commands explicitly in consent", () => { + const description = capabilityDescription({ + id: "ide.commands", + description: "", + optional: false, + granted: false, + risk: "high", + }); + expect(description).toContain("including running programs, committing and pushing"); +}); diff --git a/src/features/plugins/consent.tsx b/src/features/plugins/consent.tsx index 1355a85c34..5e4a6b5f65 100644 --- a/src/features/plugins/consent.tsx +++ b/src/features/plugins/consent.tsx @@ -32,6 +32,11 @@ export function sortByRisk(caps: readonly CapabilityInfo[]): CapabilityInfo[] { /** Parameterised permission text, translated independently of the granted host/path. */ export function capabilityDescription(cap: CapabilityInfo): string { + if (cap.id === "ide.commands") { + return tx( + "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing", + ); + } 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)`; diff --git a/src/features/plugins/decorations.module.css b/src/features/plugins/decorations.module.css new file mode 100644 index 0000000000..572ea515f8 --- /dev/null +++ b/src/features/plugins/decorations.module.css @@ -0,0 +1,39 @@ +.highlight { + background: var(--accent-soft); +} +.search { + background: var(--bg-search-match); + color: var(--fg-search-match); +} +.added { + background: color-mix(in srgb, var(--vcs-added) 18%, transparent); +} +.modified { + background: color-mix(in srgb, var(--vcs-modified) 18%, transparent); +} +.removed { + background: color-mix(in srgb, var(--vcs-deleted) 18%, transparent); +} +.warning { + text-decoration: underline wavy var(--warning); +} +.error { + text-decoration: underline wavy var(--danger); +} +.info { + text-decoration: underline dotted var(--info); +} +.underline { + text-decoration: underline; +} +.strikethrough { + text-decoration: line-through; +} +.muted { + color: var(--fg-muted); +} +.after { + white-space: pre; + margin-inline-start: calc(var(--space-2) / 2); + color: var(--fg-muted); +} diff --git a/src/features/plugins/decorations.ts b/src/features/plugins/decorations.ts new file mode 100644 index 0000000000..cdf6e439e6 --- /dev/null +++ b/src/features/plugins/decorations.ts @@ -0,0 +1,149 @@ +import { StateEffect, StateField, type Text } from "@codemirror/state"; +import { Decoration, EditorView, WidgetType, type DecorationSet as CmDecorations } from "@codemirror/view"; +import type { DecorationSet, Range } from "@/bindings"; +import { registerEditorContribution, useEditorRegistry, type EditorDocContext } from "@/editor/api"; +import { commands, isTauri } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { setFileDecorations, type FileDecoration } from "@/workbench/contributions"; +import styles from "./decorations.module.css"; + +const snapshots = new Map<string, DecorationSet[]>(); +const refresh = StateEffect.define<null>(); +const versions = new Map<string, number>(); +const colors: Record<string, string> = { + highlight: "var(--accent)", + search: "var(--fg-search-match)", + added: "var(--vcs-added)", + modified: "var(--vcs-modified)", + removed: "var(--vcs-deleted)", + warning: "var(--warning)", + error: "var(--danger)", + info: "var(--info)", + underline: "var(--fg-editor)", + strikethrough: "var(--fg-editor)", + muted: "var(--fg-muted)", +}; + +function currentSets(sets: DecorationSet[]) { + const root = useProject.getState().project?.root; + return sets.filter((s) => s.root === root); +} + +function updateTree(plugin: string, sets: DecorationSet[]) { + const items = new Map<string, FileDecoration>(); + for (const s of currentSets(sets)) + if (s.tree && s.file && Object.hasOwn(colors, s.file.style)) { + items.set(s.path, { + color: colors[s.file.style], + badge: s.file.badge ?? undefined, + tooltip: s.file.tooltip ?? undefined, + faded: s.file.style === "muted", + error: s.file.style === "error", + }); + } + setFileDecorations(`plugin:${plugin}`, items); +} + +/** Replace a plugin's snapshots. Project roots are filtered on every render. */ +export function setPluginDecorations(plugin: string, sets: DecorationSet[]) { + versions.set(plugin, (versions.get(plugin) ?? 0) + 1); + snapshots.set(plugin, sets); + updateTree(plugin, sets); + for (const editor of useEditorRegistry.getState().editors) editor.view.dispatch({ effects: refresh.of(null) }); +} + +function offset(doc: Text, pos: Range["start"]): number | null { + if (pos.line >= doc.lines) return null; + const line = doc.line(pos.line + 1); + return pos.col <= line.length ? line.from + pos.col : null; +} + +class AfterText extends WidgetType { + constructor( + readonly text: string, + readonly style: string, + readonly hover: string | null, + ) { + super(); + } + override eq(other: AfterText) { + return this.text === other.text && this.style === other.style && this.hover === other.hover; + } + override toDOM() { + const span = document.createElement("span"); + span.className = `${styles.after} ${this.style}`; + span.textContent = this.text; + if (this.hover) span.title = this.hover; + return span; + } +} + +export function decorationExtension(ctx: EditorDocContext) { + const build = (doc: Text): CmDecorations => { + const ranges = []; + for (const sets of snapshots.values()) + for (const set of currentSets(sets)) + if (!set.tree && set.path === ctx.path) { + for (const item of set.items) { + const className = Object.hasOwn(colors, item.style) ? styles[item.style] : undefined; + if (!className) continue; + const from = offset(doc, item.range.start), + to = offset(doc, item.range.end); + if (from == null || to == null || from > to) continue; + if (from < to) + ranges.push( + Decoration.mark({ class: className, attributes: item.hover ? { title: item.hover } : {} }).range( + from, + to, + ), + ); + if (item.after) + ranges.push( + Decoration.widget({ widget: new AfterText(item.after, className, item.hover), side: 1 }).range(to), + ); + } + } + return Decoration.set(ranges, true); + }; + return StateField.define<CmDecorations>({ + create: (state) => build(state.doc), + update: (value, tr) => (tr.effects.some((e) => e.is(refresh)) ? build(tr.state.doc) : value.map(tr.changes)), + provide: (field) => EditorView.decorations.from(field), + }); +} + +/** Catch up editors and project trees opened after publication. */ +export function startPluginDecorations(): () => void { + let disposed = false; + let revision = 0; + const load = () => { + const at = ++revision; + const before = new Map(versions); + if (isTauri()) + void Promise.resolve(commands.pluginDecorationSets()) + .then((all) => { + if (disposed || at !== revision) return; + for (const plugin of snapshots.keys()) + if (!all[plugin] && versions.get(plugin) === before.get(plugin)) setPluginDecorations(plugin, []); + for (const [plugin, sets] of Object.entries(all)) + if (versions.get(plugin) === before.get(plugin)) setPluginDecorations(plugin, sets); + }) + .catch(() => {}); + }; + const offProject = useProject.subscribe((s, prev) => { + if (s.project?.root === prev.project?.root) return; + for (const [plugin, sets] of snapshots) updateTree(plugin, sets); + for (const editor of useEditorRegistry.getState().editors) editor.view.dispatch({ effects: refresh.of(null) }); + load(); + }); + const off = registerEditorContribution({ id: "plugins.decorations", extensions: decorationExtension }); + load(); + return () => { + disposed = true; + offProject(); + off(); + for (const plugin of snapshots.keys()) setPluginDecorations(plugin, []); + snapshots.clear(); + versions.clear(); + }; +} diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index d2cf79c392..e37bf2456c 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -33,6 +33,7 @@ import { defineBuiltinUiPoints } from "./points"; import { startViewUi } from "./uiPoints"; import { showInstalledIntellijThemes, useIntellijThemesDialog } from "./intellijThemesDialogStore"; import { startWorkspaceContains } from "./workspaceContains"; +import { startPluginDecorations } from "./decorations"; import { startIndexedMarkers } from "./indexedMarkers"; import { startPluginNavigation } from "./navigation"; import { installFromDisk, refreshPlugins, reloadPlugin, SETTINGS_PAGE_ID, updateAllPlugins, usePlugins } from "./store"; @@ -151,6 +152,7 @@ export function activate(): () => void { startPluginBridge(), startPluginNavigation(), startIndexedMarkers(), + startPluginDecorations(), // Plugin custom editors (tab kind) and context menu entries. startViewUi((input) => void editorService().openInput(input)), startWorkspaceContains(), diff --git a/src/features/plugins/runtimeUi.tsx b/src/features/plugins/runtimeUi.tsx index 9c07ee929c..bc9c11b081 100644 --- a/src/features/plugins/runtimeUi.tsx +++ b/src/features/plugins/runtimeUi.tsx @@ -16,7 +16,10 @@ import type { StatusItem, WorkbenchEvent, } from "@/bindings"; -import { onEditorEvent } from "@/editor/api"; +import { EditorSelection } from "@codemirror/state"; +import { EditorView } from "@codemirror/view"; +import { setPluginDecorations } from "./decorations"; +import { editorsFor, onEditorEvent } from "@/editor/api"; import { executeAction, getAction, onActionExecuted } from "@/platform/actions"; import { clearContext, setContext, type ContextValue } from "@/platform/context"; import { onIdeEvent } from "@/platform/ipc"; @@ -463,6 +466,34 @@ async function answerCommand(e: Extract<PluginEvent, { type: "executeCommand" }> /** Handles the runtime UI events; returns whether `e` was one. */ export function handleRuntimeEvent(e: PluginEvent): boolean { switch (e.type) { + case "decorationsChanged": + setPluginDecorations(e.pluginId, e.sets); + return true; + case "editorOpen": { + const r = e.selection; + void maybeEditorService()?.openFile(e.path, { + focus: true, + selection: r ? { line: r.start.line, col: r.start.col, endLine: r.end.line, endCol: r.end.col } : undefined, + }); + return true; + } + case "editorRanges": { + for (const editor of editorsFor(e.path)) { + const doc = editor.view.state.doc; + const ranges = e.ranges.map((r) => { + if (r.start.line >= doc.lines || r.end.line >= doc.lines) return null; + const start = doc.line(r.start.line + 1), + end = doc.line(r.end.line + 1); + if (r.start.col > start.length || r.end.col > end.length) return null; + return EditorSelection.range(start.from + r.start.col, end.from + r.end.col); + }); + if (!ranges.length || ranges.some((r) => r == null)) continue; + const valid = ranges.filter((r) => r != null); + if (e.reveal) editor.view.dispatch({ effects: EditorView.scrollIntoView(valid[0]!, { y: "center" }) }); + else editor.view.dispatch({ selection: EditorSelection.create(valid) }); + } + return true; + } case "executeCommand": void answerCommand(e); return true; diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 885a3f72e7..ba177948fa 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -572,5 +572,6 @@ "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." + "You can close this tab.": "You can close this tab.", + "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing": "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index be17c1e8db..d5e657adc4 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6915,5 +6915,6 @@ "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.": "你可以关闭此标签页。" + "You can close this tab.": "你可以关闭此标签页。", + "Run any IDE action or other plugins' commands as if you chose them, including running programs, committing and pushing": "如同您亲自选择一样运行任意 IDE 操作或其他插件的命令,包括运行程序、提交和推送" } diff --git a/wit/decorations.wit b/wit/decorations.wit new file mode 100644 index 0000000000..1c5a033e6c --- /dev/null +++ b/wit/decorations.wit @@ -0,0 +1,22 @@ +package openidea:plugin@1.4.0; + +/// Project-scoped decorations (API 1.4). Requires project.read; paths must be inside +/// an open project. Sets belong to the plugin and disappear when it stops. +/// Styles: highlight, search, added, modified, removed, warning, error, info, +/// underline, strikethrough, muted. Unknown styles are ignored. Theme tokens only. +interface decorations { + use types.{error, range}; + /// An editor annotation; after is plain text shown after the range. + record decoration { range: range, style: string, hover: option<string>, after: option<string> } + /// A project-tree annotation; badge is at most two Unicode characters. + record file-decoration { badge: option<string>, style: string, tooltip: option<string> } + /// Replace this set for a file. At most 10,000 items/file and 50 editor sets/plugin. + /// Metadata is bounded to 4 MiB per plugin. Unknown styles are ignored. + set: func(path: string, set-id: string, items: list<decoration>) -> result<_, error>; + /// Remove this editor set from every file/project. + clear: func(set-id: string) -> result<_, error>; + /// Replace this set's tree annotation for a file; at most 50 tree sets/plugin. + set-file: func(path: string, set-id: string, item: file-decoration) -> result<_, error>; + /// Remove this tree set from every file/project. + clear-file: func(set-id: string) -> result<_, error>; +} diff --git a/wit/host.wit b/wit/host.wit index d81877524c..c5ce20fbec 100644 --- a/wit/host.wit +++ b/wit/host.wit @@ -115,6 +115,7 @@ 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. + /// Requires high-risk `ide.commands`, except for this plugin's own commands. execute: func(id: string, arg: option<string>) -> result<option<string>, error>; } diff --git a/wit/io.wit b/wit/io.wit index 2ebc7a889d..b27e48d622 100644 --- a/wit/io.wit +++ b/wit/io.wit @@ -3,6 +3,11 @@ package openidea:plugin@1.4.0; /// Problems in files, shown in the editor and the Problems view. interface diagnostics { use types.{error, range, location}; + /// Problems reported by a source for a file in this window's project. + record file-problems { path: string, source: string, diagnostics: list<diagnostic> } + /// Current Problems view snapshot, optionally filtered to a project file. + /// Requires project.read and an invoking window. Empty for remote projects. + problems: func(path: option<string>) -> result<list<file-problems>, error>; enum severity { error, diff --git a/wit/plugin.wit b/wit/plugin.wit index acb2a8e7aa..3a804b2b95 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -17,6 +17,7 @@ world plugin { import fs; import workspace; import editor; + import decorations; import invocation; import vcs; import commit; diff --git a/wit/workspace.wit b/wit/workspace.wit index 851d14d578..7c1e9dd19b 100644 --- a/wit/workspace.wit +++ b/wit/workspace.wit @@ -39,10 +39,28 @@ interface workspace { location: location, } + /// Text search options. Include/exclude are project-relative globs, as in Find in Files. + record text-query { + pattern: string, + regex: bool, + case-sensitive: bool, + whole-word: bool, + %include: list<string>, + exclude: list<string>, + } + /// A match with zero-based lines and UTF-16 columns, and its displayed line. + record text-match { location: location, line: string } + /// Bounded search results; limit-hit says there may be more matches. + record text-search { matches: list<text-match>, limit-hit: bool } + /// A project open in the IDE. resource project { /// Absolute path of the project root. Requires `project.read`. root: func() -> result<string, error>; + /// Find in Files with unsaved documents and project excludes. Requires project.read. + /// Cancellable, at most 10,000 matches. Zero limit returns no matches. + /// Line previews are capped at 4096 UTF-8 bytes, results at 4 MiB (limit-hit). + search-text: func(query: text-query, limit: u32) -> result<text-search, error>; /// Reads a UTF-8 text file inside the project (absolute, or relative /// to the root); paths leaving the root are refused. Unsaved editor /// contents win over the disk. A missing path is `not-found`. @@ -94,10 +112,22 @@ interface editor { text: string, } + /// An editor in the invoking window. + record open-editor { path: string, language: string, dirty: bool, active: bool } + /// Only from commands/events of a window. Requires editor.read. + open-editors: func() -> result<list<open-editor>, error>; + /// Open a project file (project.read) or a file in plugin-dir, selecting a range. + /// Only from commands/events of a window. Paths follow views.open-location. + open: func(path: string, selection: option<range>) -> result<_, error>; + /// A file open in an editor. resource text-editor { /// Absolute path of the file. path: func() -> string; + /// Replace selections in this window's editor. No capability; commands/events only. + set-selections: func(selections: list<range>) -> result<_, error>; + /// Scroll a range into view in this window's editor. No capability; commands/events only. + reveal: func(range: range) -> result<_, error>; /// Language id (`rust`, `solidity`, …). language: func() -> string; /// Current version and text. Requires `editor.read`. @@ -151,6 +181,22 @@ interface vcs { changed-files: u32, } + /// A commit in repository history; date is Unix seconds. + record commit-info { + id: string, short-id: string, author: string, author-email: string, + date: s64, subject: string, body: string, parents: list<string>, + } + /// One zero-based document line's attribution; date is Unix seconds. + record blame-line { line: u32, commit: string, author: string, date: s64, summary: string } + /// Newest commits first, at most 1000. Trusted projects only; requires vcs.read. + log: func(project: borrow<project>, path: option<string>, limit: u32) -> result<list<commit-info>, error>; + /// Includes unsaved text, with changed lines attributed to uncommitted changes. + /// Trusted projects only; requires vcs.read. Paths must be inside the project. + blame: func(project: borrow<project>, path: string) -> result<list<blame-line>, error>; + /// Working tree versus HEAD or against. None outside a repository. Disk text only. + /// Fails above 4 MiB. Trusted projects only; requires vcs.read. + diff: func(project: borrow<project>, path: option<string>, against: option<string>) -> result<option<string>, error>; + /// `none` when the project is not in a repository. Requires `vcs.read`. status: func(project: borrow<project>) -> result<option<repository-status>, error>; /// Configured remotes (`name`, fetch `url`), in order. Requires `vcs.read`.