diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 493a6136..eb8f0e0a 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -511,6 +511,7 @@ or removing a command fails until the table changes in the same commit. | `toolchains.discoveryPlan` | Return platform-filtered definition-owned scan declarations, layouts, probes, PATH entries, login-shell home variables, project-file candidates and budgets; never scans native directories | | `toolchains.candidates` | List one tool's root project-file candidates, login-shell homes (declared `environment` variables and, from the optional `commandHomes`, declared commands found on the PATH) and host-scanned installations with checked executables, versions or skip reasons, and the automatic-layer choice; never starts a probe. A shell home that checks out is also an `installations` entry with provider `host:shell`, once per canonical home, so a picker can offer every home the resolver may run; `selected` remains the automatic layer's own choice | | `toolchains.instantiateLaunch` | Expand an enabled tool definition's `launch` template for a selected executable, entry, runtime arguments and arguments; a part the template cannot carry is `plugin.toolchain.launchMismatch`; performs no I/O | +| `toolchains.settingsView` | Project the settings list of every enabled tool from host-held facts: classify each resolver reason as `error`, `warning` or `ok`, filter by text and by problems, pins or pending edits, group by definition category (plugin-only runtimes last), plugin or nothing, apply default and user folding, and return rows, the first issues and counts; performs no resolution or I/O | | `run.decodeStart` | Validate a plugin backend's `lithe/host/run/start` params against its manifest and the workspace, and return the normalized start with temporary-file paths substituted | | `debug.decodeBackendConfiguration` | Validate a plugin backend's `lithe/host/debug/start` params against its manifest and return the qualified adapter, request, label and configuration | | `outputLinks.match` | Find the links plugin `outputLinkMatchers` declare in Run or Test console lines, as UTF-16 ranges with candidate paths or a backend function to resolve them, and the web addresses the lines print, as `url` links the host opens in the browser | @@ -7133,11 +7134,14 @@ Names come from enabled language/build declarations, with opaque ID fallback. section titles translated when the state is. Catalog contributor sections keep the manifest headings. -`plugins.settings.navigation` accepts at most 576 two-level `items` (512 contributed pages plus 64 host entries) with stable -`id`, `title`, nullable `parent`, `group`, `expanded`, optional `keywords`, plus -`query` (at most 1024 bytes). It returns `rows` containing id/title/group/expanded/level. -Search retains ancestors and expands matching groups; ordering follows input. -Duplicate IDs, invalid parents and excessive input are rejected. +`plugins.settings.navigation` accepts at most 576 `items` (512 contributed pages plus 64 host entries), up to three levels +deep, with stable `id`, `title`, nullable `parent`, `group`, `expanded`, optional `keywords` and optional `limit` +(1–512), plus `query` (at most 1024 bytes). It returns `rows` containing id/title/group/expanded/level, `matched` +(the row itself matches the query) and `path` (ancestor titles, root first). Outside search, an item with `limit` +shows that many children followed by one overflow row `{id,title,level,path,overflow}` that carries the item's own +ID and the total child count, so the host can open the item's directory page. Search retains ancestors, shows every +descendant of a matched item and ignores `limit`; ordering follows input. Duplicate IDs, a parent chain that is +missing, cyclic or deeper than three levels, a zero limit and excessive input are rejected. `plugins.settings.delivery` accepts `scope` (global/project), native equality facts `samePreferences`, `sameWorkspace`, `sameVersion`, current `enabled`, and diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index b70eb2cd..f861345d 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -427,6 +427,8 @@ pub enum ToolchainsCommand { Candidates, /// Expands a tool definition's launch template for a selected executable. InstantiateLaunch, + /// Projects the settings list of every enabled tool: status, filter, groups and counts. + SettingsView, } #[derive(Debug, Clone)] @@ -1170,6 +1172,7 @@ impl CoreCommand { "toolchains.instantiateLaunch" => { Some(Self::Toolchains(ToolchainsCommand::InstantiateLaunch)) } + "toolchains.settingsView" => Some(Self::Toolchains(ToolchainsCommand::SettingsView)), "run.decodeStart" => Some(Self::RunDecodeStart), "debug.decodeBackendConfiguration" => { Some(Self::Debug(DebugCommand::DecodeBackendConfiguration)) diff --git a/rust/crates/core/src/runtime/dispatcher/toolchains.rs b/rust/crates/core/src/runtime/dispatcher/toolchains.rs index 694e7571..eb572756 100644 --- a/rust/crates/core/src/runtime/dispatcher/toolchains.rs +++ b/rust/crates/core/src/runtime/dispatcher/toolchains.rs @@ -88,5 +88,8 @@ pub(super) fn dispatch( lithe_plugin_manifest::validated_manifest_json, ) }), + ToolchainsCommand::SettingsView => { + plugin_response(id, payload, crate::toolchain::settings_view_command) + } } } diff --git a/rust/crates/core/src/tests/plugin_settings_documents.rs b/rust/crates/core/src/tests/plugin_settings_documents.rs index 9404ea9e..916ea1ce 100644 --- a/rust/crates/core/src/tests/plugin_settings_documents.rs +++ b/rust/crates/core/src/tests/plugin_settings_documents.rs @@ -376,6 +376,73 @@ fn settings_navigation_reserves_capacity_for_host_rows() { assert_eq!(response["data"]["rows"].as_array().unwrap().len(), 513); } +fn build_tree(languages: usize) -> Vec { + let mut items = vec![ + json!({"id":"build","title":"Build","parent":null,"group":true,"expanded":true}), + json!({"id":"toolchains","title":"Toolchains","parent":"build","group":false,"expanded":false}), + json!({"id":"kind:language","title":"Languages","parent":"build","group":true,"expanded":true,"limit":6}), + ]; + for index in 0..languages { + items.push(json!({"id":format!("language:{index}"),"title":format!("Language {index}"),"parent":"kind:language","group":false,"expanded":false,"keywords":if index == 9 {"cargo"} else {""}})); + } + items +} + +fn navigation_rows(items: Vec, query: &str) -> Vec { + let response = execute( + "plugins.settings.navigation", + json!({"items":items,"query":query}), + ); + assert_eq!(response["data"]["status"], "ok", "{response}"); + response["data"]["rows"].as_array().unwrap().clone() +} + +/// A kind fold under a group shows its first `limit` pages and one overflow row +/// that counts every page; search ignores the limit and lists hits with their path. +#[test] +fn settings_navigation_folds_a_third_level_behind_an_overflow_row() { + let rows = navigation_rows(build_tree(12), ""); + assert_eq!(rows.len(), 3 + 6 + 1); + assert_eq!(rows[2]["level"], 1); + assert_eq!(rows[3]["level"], 2); + let overflow = &rows[9]; + assert_eq!(overflow["id"], "kind:language"); + assert_eq!(overflow["overflow"], 12); + assert_eq!(overflow["level"], 2); + assert_eq!(overflow["path"], json!(["Build", "Languages"])); + assert!(rows.iter().all(|row| row["matched"] == false)); + + let rows = navigation_rows(build_tree(12), "CARGO"); + let ids: Vec<_> = rows.iter().map(|row| row["id"].clone()).collect(); + assert_eq!(ids, ["build", "kind:language", "language:9"]); + assert_eq!(rows[2]["matched"], true); + assert_eq!(rows[2]["path"], json!(["Build", "Languages"])); + assert_eq!(rows[0]["matched"], false); + + // A matched fold shows every page below it, still without the limit. + let rows = navigation_rows(build_tree(12), "languages"); + assert_eq!(rows.len(), 2 + 12); + assert!(rows.iter().all(|row| row.get("overflow").is_none())); +} + +#[test] +fn settings_navigation_rejects_a_fourth_level_cycles_and_empty_limits() { + let mut deep = build_tree(1); + deep.push(json!({"id":"too-deep","title":"Deep","parent":"language:0","group":false,"expanded":false})); + let mut cycle = build_tree(0); + cycle.push(json!({"id":"a","title":"A","parent":"b","group":false,"expanded":false})); + cycle.push(json!({"id":"b","title":"B","parent":"a","group":false,"expanded":false})); + let mut empty = build_tree(1); + empty[2]["limit"] = json!(0); + for items in [deep, cycle, empty] { + let response = execute( + "plugins.settings.navigation", + json!({"items":items,"query":""}), + ); + assert_eq!(response["data"]["status"], "rejected", "{response}"); + } +} + fn contract_settings_file(name: &str) -> String { std::fs::read_to_string(format!( "{}/../../../shared/plugins/contract/v1/fixtures/settings/{name}", diff --git a/rust/crates/core/src/tests/toolchain_definitions.rs b/rust/crates/core/src/tests/toolchain_definitions.rs index 4d99ba11..0dfd7eef 100644 --- a/rust/crates/core/src/tests/toolchain_definitions.rs +++ b/rust/crates/core/src/tests/toolchain_definitions.rs @@ -60,6 +60,43 @@ fn tool_definitions_second_tool_needs_only_plugin_data() { } } +/// `category` and `audience` only group a tool on the settings page, so they pass +/// through the registry unchanged and accept only the fixed display values. +#[test] +fn tool_definitions_declare_settings_category_and_audience() { + let mut tagged = definition("dev.lithe.fixture.compiler:compiler"); + tagged["category"] = json!("build"); + tagged["audience"] = json!("plugin"); + let mut plugin = manifest("dev.lithe.fixture.compiler", tagged); + // The fields are toolDefinitions 1, so a host that supports only 0 never installs it. + let rejected = validate_manifest_value(plugin.clone()) + .err() + .expect("version 0 refuses settings categories"); + assert_eq!(rejected.field.as_deref(), Some("requires.toolDefinitions")); + plugin["requires"]["toolDefinitions"] = json!(1); + assert!(validate_manifest_value(plugin.clone()).is_ok()); + let result = registry( + &json!({"plugins":[{"manifest":plugin}]}), + validated_manifest_json, + ) + .unwrap(); + let registered = &result["definitions"][0]["definition"]; + assert_eq!(registered["category"], "build"); + assert_eq!(registered["audience"], "plugin"); + for (field, value) in [ + ("category", json!("compiler")), + ("category", json!(1)), + ("audience", json!("system")), + ] { + let mut changed = definition("dev.lithe.fixture.compiler:compiler"); + changed[field] = value; + assert!( + validate_declarations("dev.lithe.fixture.compiler", &[changed], &[]).is_err(), + "{field}" + ); + } +} + /// No plugin needs a host-attested origin for a short ID. #[test] fn registry_accepts_short_ids_from_any_enabled_plugin() { diff --git a/rust/crates/core/src/tests/toolchain_resolution.rs b/rust/crates/core/src/tests/toolchain_resolution.rs index b9f5cc1a..5c0cf28e 100644 --- a/rust/crates/core/src/tests/toolchain_resolution.rs +++ b/rust/crates/core/src/tests/toolchain_resolution.rs @@ -472,6 +472,11 @@ fn toolchain_commands_cross_the_json_dispatch_boundary() { ), ("toolchains.resolve", input(), "resolution"), ("toolchains.candidates", listing(&input()), "candidates"), + ( + "toolchains.settingsView", + json!({"tools":[{"id":"java","displayName":"JDK","pluginID":"dev.lithe.fixture","reason":"notFound"}],"query":{"filter":"problems"}}), + "view", + ), ] { let response: Value = serde_json::from_str(&crate::execute_json( &json!({"id":"toolchains","command":command,"payload":payload}).to_string(), diff --git a/rust/crates/plugin-manifest/src/settings_surfaces.rs b/rust/crates/plugin-manifest/src/settings_surfaces.rs index 01597d60..c8b12e21 100644 --- a/rust/crates/plugin-manifest/src/settings_surfaces.rs +++ b/rust/crates/plugin-manifest/src/settings_surfaces.rs @@ -104,7 +104,7 @@ pub fn settings_catalog_command(payload: Value) -> Result { } /// Native static page labels and stable identifiers. Hierarchy is supplied once; -/// search, expansion and ancestor retention are shared projection rules. +/// search, expansion, folding and ancestor retention are shared projection rules. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct NavigationItem { @@ -115,6 +115,10 @@ struct NavigationItem { expanded: bool, #[serde(default)] keywords: String, + /// Shows at most this many children outside search; the rest fold into one + /// overflow row that opens the group's own directory page. + #[serde(default)] + limit: Option, } #[derive(Deserialize)] @@ -124,64 +128,120 @@ struct NavigationRequest { query: String, } -/// Projects a bounded two-level settings tree; matched descendants retain their -/// parent and a matched parent shows its children, including dynamic surfaces. +/// The deepest level a row may sit at: group, kind fold, page. +const MAX_LEVEL: usize = 2; + +struct Navigation<'a> { + items: &'a [NavigationItem], + query: String, + rows: Vec, +} + +impl<'a> Navigation<'a> { + fn matches(&self, item: &NavigationItem) -> bool { + !self.query.is_empty() + && (item.title.to_lowercase().contains(&self.query) + || item.keywords.to_lowercase().contains(&self.query)) + } + + fn children(&self, id: &str) -> Vec<&'a NavigationItem> { + self.items + .iter() + .filter(|item| item.parent.as_deref() == Some(id)) + .collect() + } + + /// Whether the item, or any item below it, matches the search. + fn hit(&self, item: &NavigationItem) -> bool { + self.matches(item) || self.children(&item.id).iter().any(|child| self.hit(child)) + } + + fn emit(&mut self, item: &'a NavigationItem, level: usize, path: &[&'a str], shown: bool) { + let searching = !self.query.is_empty(); + let own = self.matches(item); + // A matched item shows everything below it; otherwise only matching branches. + if searching && !shown && !self.hit(item) { + return; + } + self.rows.push(json!({ + "id":item.id,"title":item.title,"group":item.group, + "expanded":searching || item.expanded,"level":level, + "matched":own,"path":path, + })); + if item.group && !item.expanded && !searching { + return; + } + let children = self.children(&item.id); + let limit = match item.limit { + Some(limit) if !searching => limit, + _ => children.len(), + }; + let mut below = path.to_vec(); + below.push(&item.title); + for child in children.iter().take(limit) { + self.emit(child, level + 1, &below, shown || own); + } + if children.len() > limit { + self.rows.push(json!({ + "id":item.id,"title":item.title,"group":false,"expanded":false, + "level":level + 1,"matched":false,"path":below,"overflow":children.len(), + })); + } + } +} + +/// Projects a bounded settings tree of up to three levels: a matched item keeps its +/// ancestors and shows its descendants, including dynamic surfaces. Each row carries +/// `matched` and the ancestor `path`, so a host can list search hits flat with their +/// location. pub fn settings_navigation_command(payload: Value) -> Result { let request: NavigationRequest = decode_payload(payload, "plugins.settings.navigation")?; Ok(outcome((|| { if request.items.len() > MAX_PAGES + 64 || request.query.len() > 1024 { return Err(rejected("navigation")); } - let query = request.query.trim().to_lowercase(); let mut ids = BTreeSet::new(); for item in &request.items { if item.id.is_empty() || item.id.len() > 256 || item.title.len() > 1024 || item.keywords.len() > 16384 + || item + .limit + .is_some_and(|limit| limit == 0 || limit > MAX_PAGES) || !ids.insert(&item.id) { return Err(rejected("items")); } } + let parent_of = |id: &str| { + request + .items + .iter() + .find(|candidate| candidate.id == id) + .map(|candidate| candidate.parent.as_deref()) + }; for item in &request.items { - if let Some(parent) = &item.parent { - if !request - .items - .iter() - .any(|candidate| &candidate.id == parent && candidate.parent.is_none()) - { - return Err(rejected("parent")); - } + // Walking up must reach a root within MAX_LEVEL steps; this also rules out cycles. + let mut current = item.parent.as_deref(); + let mut depth = 0; + while let Some(parent) = current { + depth += 1; + current = match parent_of(parent) { + Some(next) if depth <= MAX_LEVEL => next, + _ => return Err(rejected("parent")), + }; } } - let matches = |item: &NavigationItem| { - item.title.to_lowercase().contains(&query) - || item.keywords.to_lowercase().contains(&query) + let mut navigation = Navigation { + items: &request.items, + query: request.query.trim().to_lowercase(), + rows: Vec::new(), }; - let row = |item: &NavigationItem, level: usize| json!({"id":item.id,"title":item.title,"group":item.group,"expanded":!query.is_empty() || item.expanded,"level":level}); - let mut result = Vec::new(); - for parent in request.items.iter().filter(|item| item.parent.is_none()) { - let children: Vec<_> = request - .items - .iter() - .filter(|item| item.parent.as_ref() == Some(&parent.id)) - .collect(); - let own = matches(parent); - if !own && !children.iter().any(|child| matches(child)) { - continue; - } - result.push(row(parent, 0)); - if !parent.group || parent.expanded || !query.is_empty() { - result.extend( - children - .into_iter() - .filter(|child| own || matches(child)) - .map(|child| row(child, 1)), - ); - } + for root in request.items.iter().filter(|item| item.parent.is_none()) { + navigation.emit(root, 0, &[], false); } - Ok(("rows", json!(result))) + Ok(("rows", json!(navigation.rows))) })())) } diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index ac3e5729..cd86bee0 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -127,6 +127,18 @@ impl DeclarativePluginManifest { "Entrypoint runs need buildProviders 1.", )); } + if self.tool_definitions.iter().any(|definition| { + definition.get("category").is_some() || definition.get("audience").is_some() + }) && self + .requires + .get(capabilities::TOOL_DEFINITIONS) + .is_none_or(|version| *version < 1) + { + return Err(invalid( + "requires.toolDefinitions", + "Settings categories and audiences need toolDefinitions 1.", + )); + } if self.languages.is_empty() && self.ui.is_none() && self.build_systems.is_empty() diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index b9e44e12..cee6d632 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -5,8 +5,9 @@ //! capabilities it uses, each with the version of that capability's contract //! it was written against, so a plugin without build systems never depends on //! the build-system contract and a later version of one capability only -//! affects plugins that opt into it. Every capability currently supports only -//! version 0. Everything outside the capability sections, including launches, +//! affects plugins that opt into it. Every capability starts at version 0; +//! `SUPPORTED_CAPABILITIES` lists the later versions this build accepts. +//! Everything outside the capability sections, including launches, //! tool references, and executable candidates, belongs to the base contract //! (`pluginAPIVersion`) and is never listed in `requires`. //! @@ -107,7 +108,8 @@ pub const KEYMAP_IMPORT_PROVIDERS: &str = "keymapImportProviders"; /// see `lithe_plugin_functions`. pub const PLUGIN_FUNCTIONS: &str = "pluginFunctions"; /// `toolDefinitions[]`: plugin-owned tool identities, discovery policy, and -/// executable candidates. +/// executable candidates. Version 1 adds the display-only `category` and +/// `audience` that place a tool in the settings list. pub const TOOL_DEFINITIONS: &str = "toolDefinitions"; /// Backend facts that can influence the executable selected for a defined tool. pub const TOOLCHAIN_PROVIDERS: &str = "toolchainProviders"; @@ -136,7 +138,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (RUN_CONFIGURATION_TYPES, &[0]), (SETTINGS, &[0]), (SOURCE_SETTINGS, &[0, 1]), - (TOOL_DEFINITIONS, &[0]), + (TOOL_DEFINITIONS, &[0, 1]), (TOOLCHAIN_PROVIDERS, &[0]), (UI, &[0]), (VCS_PROVIDERS, &[0]), diff --git a/rust/crates/toolchain/src/definitions.rs b/rust/crates/toolchain/src/definitions.rs index 6638e2a9..69ae70ef 100644 --- a/rust/crates/toolchain/src/definitions.rs +++ b/rust/crates/toolchain/src/definitions.rs @@ -424,6 +424,8 @@ fn definition(plugin_id: &str, value: &Value) -> Validation<()> { "exports", "pathPrepend", "launch", + "category", + "audience", ], &[ "id", @@ -448,6 +450,29 @@ fn definition(plugin_id: &str, value: &Value) -> Validation<()> { )); } text(&value["displayName"], 64, "toolDefinitions.displayName")?; + // Display grouping only: neither field changes discovery, resolution or launch. + if let Some(category) = value.get("category") { + if !category + .as_str() + .is_some_and(|value| crate::settings_view::CATEGORIES.contains(&value)) + { + return Err(invalid( + "toolDefinitions.category", + "The category is not one of the fixed display groups.", + )); + } + } + if let Some(audience) = value.get("audience") { + if !audience + .as_str() + .is_some_and(|value| crate::settings_view::AUDIENCES.contains(&value)) + { + return Err(invalid( + "toolDefinitions.audience", + "The audience must be user or plugin.", + )); + } + } if let Some(icon) = value.get("icon") { let icon: UIIcon = serde_json::from_value(icon.clone()) .map_err(|_| invalid("toolDefinitions.icon", "The icon shape is invalid."))?; diff --git a/rust/crates/toolchain/src/lib.rs b/rust/crates/toolchain/src/lib.rs index 45d9118d..ab3a7ea1 100644 --- a/rust/crates/toolchain/src/lib.rs +++ b/rust/crates/toolchain/src/lib.rs @@ -11,6 +11,7 @@ pub mod pins; pub mod preferences; pub mod query; mod resolution; +pub mod settings_view; use lithe_plugin_model::{PluginRejection, Validation}; use lithe_protocol::CoreError; @@ -68,6 +69,11 @@ pub fn decode_reply_command( ) } +/// Projects the settings list of every enabled tool: status, filter, groups and counts. +pub fn settings_view_command(input: Value) -> Result { + command(input, settings_view::settings_view, "view") +} + /// Builds the error reply for a query that timed out or found no backend. pub fn failure_reply_command(input: Value) -> Result { command(input, query::failure_reply, "reply") diff --git a/rust/crates/toolchain/src/settings_view.rs b/rust/crates/toolchain/src/settings_view.rs new file mode 100644 index 00000000..1c60fce4 --- /dev/null +++ b/rust/crates/toolchain/src/settings_view.rs @@ -0,0 +1,527 @@ +//! Projects the toolchain settings list: status classes, filters, groups, ordering and +//! counts for every enabled tool. Hosts render only the rows they can see; they never +//! re-sort, re-count or classify resolver reasons themselves. + +use lithe_plugin_model::{invalid, Validation}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +/// Display groups a definition may declare; the order is the on-screen group order. +pub const CATEGORIES: [&str; 6] = ["runtime", "build", "package", "debug", "lint", "other"]; +/// Who a tool is for: a user-facing tool, or a runtime a plugin runs for itself. +pub const AUDIENCES: [&str; 2] = ["user", "plugin"]; +/// Resolver reasons the user can clear without installing anything: trusting the +/// project, choosing between equal installations, or rerunning a probe. +const WARNING_REASONS: [&str; 3] = [ + "projectCodeRequiresAction", + "ambiguousInstallation", + "probeFailed", +]; +/// Sized for thousands of enabled plugins; the 4 MiB command budget still applies. +const MAX_TOOLS: usize = 20_000; +const MAX_TERMS: usize = 16; +const MAX_GROUP_KEYS: usize = 20_000; +/// Grouping by plugin starts collapsed above this many groups, so the first screen +/// lists plugins rather than thousands of tools. +const PLUGIN_GROUPS_EXPANDED_UP_TO: usize = 40; +const DEFAULT_ISSUES: usize = 5; +const MAX_ISSUES: usize = 50; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Tool { + id: String, + display_name: String, + #[serde(rename = "pluginID")] + plugin_id: String, + plugin_name: Option, + category: Option, + audience: Option, + /// The resolver's stable reason when no installation applies; absent when resolved. + reason: Option, + #[serde(default)] + pinned: bool, + #[serde(default)] + changed: bool, + /// Extra searchable text such as versions and installation paths. + #[serde(default)] + terms: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Query { + #[serde(default)] + text: String, + #[serde(default = "all")] + filter: String, + #[serde(default = "category")] + group_by: String, + /// Group keys the user collapsed or expanded; they override the defaults. + #[serde(default)] + collapsed: Vec, + #[serde(default)] + expanded: Vec, +} + +fn all() -> String { + "all".to_owned() +} + +fn category() -> String { + "category".to_owned() +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + tools: Vec, + query: Query, + issue_limit: Option, +} + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Status { + Error, + Warning, + Ok, +} + +impl Status { + fn of(reason: Option<&str>) -> Self { + match reason { + None => Self::Ok, + Some(code) if WARNING_REASONS.contains(&code) => Self::Warning, + Some(_) => Self::Error, + } + } + + fn name(self) -> &'static str { + match self { + Self::Error => "error", + Self::Warning => "warning", + Self::Ok => "ok", + } + } + + fn problem(self) -> bool { + self != Self::Ok + } +} + +fn bounded(value: &str, max: usize) -> bool { + !value.is_empty() && value.len() <= max && !value.chars().any(char::is_control) +} + +fn validate(request: &Request) -> Validation<()> { + if request.tools.len() > MAX_TOOLS { + return Err(invalid( + "tools", + "The settings view exceeds its tool limit.", + )); + } + let mut ids = BTreeSet::new(); + for tool in &request.tools { + let names_ok = bounded(&tool.id, 192) + && bounded(&tool.display_name, 256) + && bounded(&tool.plugin_id, 128) + && tool + .plugin_name + .as_deref() + .is_none_or(|name| bounded(name, 256)); + let enums_ok = tool + .category + .as_deref() + .is_none_or(|value| CATEGORIES.contains(&value)) + && tool + .audience + .as_deref() + .is_none_or(|value| AUDIENCES.contains(&value)) + && tool.reason.as_deref().is_none_or(|code| bounded(code, 64)); + let terms_ok = tool.terms.len() <= MAX_TERMS + && tool + .terms + .iter() + .all(|term| term.len() <= 1024 && !term.chars().any(char::is_control)); + if !names_ok || !enums_ok || !terms_ok { + return Err(invalid("tools", "Expected bounded tool facts.")); + } + // A tool ID appears once: the registry already dropped contested short IDs. + if !ids.insert(tool.id.as_str()) { + return Err(invalid("tools.id", "Tool IDs must be unique.")); + } + } + let query = &request.query; + if query.text.len() > 1024 + || !matches!( + query.filter.as_str(), + "all" | "problems" | "pinned" | "changed" + ) + || !matches!(query.group_by.as_str(), "category" | "plugin" | "none") + || query.collapsed.len() + query.expanded.len() > MAX_GROUP_KEYS + || query + .collapsed + .iter() + .chain(&query.expanded) + .any(|key| !bounded(key, 256)) + { + return Err(invalid("query", "Expected a bounded settings view query.")); + } + if request.issue_limit.is_some_and(|limit| limit > MAX_ISSUES) { + return Err(invalid("issueLimit", "At most 50 issues are listed.")); + } + Ok(()) +} + +fn matches(tool: &Tool, needle: &str) -> bool { + needle.is_empty() + || [ + Some(tool.display_name.as_str()), + Some(tool.id.as_str()), + Some(tool.plugin_id.as_str()), + tool.plugin_name.as_deref(), + ] + .into_iter() + .flatten() + .chain(tool.terms.iter().map(String::as_str)) + .any(|text| text.to_lowercase().contains(needle)) +} + +fn plugin_title(tool: &Tool) -> &str { + tool.plugin_name.as_deref().unwrap_or(&tool.plugin_id) +} + +/// Problems first, then by name; the ID breaks ties so equal names never reorder. +fn tool_order(tools: &[Tool], statuses: &[Status], left: usize, right: usize) -> Ordering { + statuses[left] + .cmp(&statuses[right]) + .then_with(|| { + tools[left] + .display_name + .to_lowercase() + .cmp(&tools[right].display_name.to_lowercase()) + }) + .then_with(|| tools[left].id.cmp(&tools[right].id)) +} + +/// One group: its stable key, the fields that name it, and its member tools. +struct Group { + key: String, + head: Value, + order: (usize, String, String), + members: Vec, +} + +fn group_of(tool: &Tool, by: &str) -> (String, Value, (usize, String, String)) { + if by == "plugin" { + let title = plugin_title(tool); + return ( + format!("plugin:{}", tool.plugin_id), + json!({"pluginID":tool.plugin_id,"title":title}), + (0, title.to_lowercase(), tool.plugin_id.clone()), + ); + } + // A plugin's own runtime is grouped apart from user tools in every category. + if tool.audience.as_deref() == Some("plugin") { + return ( + "audience:plugin".to_owned(), + json!({"audience":"plugin"}), + (CATEGORIES.len(), String::new(), String::new()), + ); + } + let category = tool.category.as_deref().unwrap_or("other"); + let rank = CATEGORIES + .iter() + .position(|value| *value == category) + .unwrap_or(CATEGORIES.len() - 1); + ( + format!("category:{category}"), + json!({"category":category}), + (rank, String::new(), String::new()), + ) +} + +/// Builds the projection. Filtering expands every group so a match is never hidden +/// behind a collapsed header; counts always cover every tool, not only matches. +pub fn settings_view(input: &Value) -> Validation { + let request: Request = serde_json::from_value(input.clone()).map_err(|_| { + invalid( + "settingsView", + "Expected a toolchain settings view request.", + ) + })?; + validate(&request)?; + let tools = &request.tools; + let query = &request.query; + let statuses: Vec = tools + .iter() + .map(|tool| Status::of(tool.reason.as_deref())) + .collect(); + let needle = query.text.trim().to_lowercase(); + let filtering = !needle.is_empty() || query.filter != "all"; + let visible: Vec = (0..tools.len()) + .filter(|index| { + let tool = &tools[*index]; + matches(tool, &needle) + && match query.filter.as_str() { + "problems" => statuses[*index].problem(), + "pinned" => tool.pinned, + "changed" => tool.changed, + _ => true, + } + }) + .collect(); + let tool_row = + |index: usize| json!({"kind":"tool","index":index,"status":statuses[index].name()}); + let mut rows = Vec::new(); + if query.group_by == "none" { + let mut sorted = visible.clone(); + sorted.sort_by(|left, right| tool_order(tools, &statuses, *left, *right)); + rows.extend(sorted.into_iter().map(tool_row)); + } else { + let mut groups: BTreeMap = BTreeMap::new(); + for index in &visible { + let (key, head, order) = group_of(&tools[*index], &query.group_by); + groups + .entry(key.clone()) + .or_insert_with(|| Group { + key, + head, + order, + members: Vec::new(), + }) + .members + .push(*index); + } + let mut groups: Vec = groups.into_values().collect(); + groups.sort_by(|left, right| left.order.cmp(&right.order)); + let collapsed: BTreeSet<&str> = query.collapsed.iter().map(String::as_str).collect(); + let expanded: BTreeSet<&str> = query.expanded.iter().map(String::as_str).collect(); + let many = query.group_by == "plugin" && groups.len() > PLUGIN_GROUPS_EXPANDED_UP_TO; + for mut group in groups { + group + .members + .sort_by(|left, right| tool_order(tools, &statuses, *left, *right)); + let problems = group + .members + .iter() + .filter(|index| statuses[**index].problem()) + .count(); + let folded = !filtering + && if collapsed.contains(group.key.as_str()) { + true + } else if expanded.contains(group.key.as_str()) { + false + } else { + many || group.key == "audience:plugin" + }; + let mut head = json!({"kind":"group","key":group.key,"count":group.members.len(),"problems":problems,"collapsed":folded}); + if let (Some(target), Some(fields)) = (head.as_object_mut(), group.head.as_object()) { + target.extend(fields.clone()); + } + rows.push(head); + if !folded { + rows.extend(group.members.into_iter().map(tool_row)); + } + } + } + let mut problems: Vec = (0..tools.len()) + .filter(|index| statuses[*index].problem()) + .collect(); + problems.sort_by(|left, right| tool_order(tools, &statuses, *left, *right)); + let errors = statuses.iter().filter(|s| **s == Status::Error).count(); + let warnings = statuses.iter().filter(|s| **s == Status::Warning).count(); + let issues: Vec = problems + .iter() + .take(request.issue_limit.unwrap_or(DEFAULT_ISSUES)) + .map(|index| json!({"index":index,"status":statuses[*index].name()})) + .collect(); + Ok(json!({ + "rows":rows, + "issues":issues, + "counts":{ + "total":tools.len(), + "matched":visible.len(), + "problems":errors + warnings, + "errors":errors, + "warnings":warnings, + "pinned":tools.iter().filter(|tool| tool.pinned).count(), + "changed":tools.iter().filter(|tool| tool.changed).count(), + }, + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tool(id: &str, name: &str, plugin: &str, extra: Value) -> Value { + let mut value = json!({"id":id,"displayName":name,"pluginID":plugin}); + if let (Some(target), Some(fields)) = (value.as_object_mut(), extra.as_object()) { + target.extend(fields.clone()); + } + value + } + + fn sample() -> Vec { + vec![ + tool( + "jdk", + "JDK", + "java", + json!({"category":"runtime","pinned":true,"terms":["21.0.5","/opt/jdk"]}), + ), + tool( + "go", + "Go", + "go", + json!({"category":"runtime","reason":"notFound"}), + ), + tool( + "maven", + "Maven", + "maven", + json!({"category":"build","reason":"projectCodeRequiresAction"}), + ), + tool( + "gradle", + "Gradle", + "gradle", + json!({"category":"build","changed":true}), + ), + tool( + "jdtls.jdk", + "JDK for jdtls", + "java", + json!({"category":"runtime","audience":"plugin","reason":"versionUnsatisfied"}), + ), + tool("misc", "Misc", "other", json!({})), + ] + } + + fn view(tools: Vec, query: Value) -> Value { + settings_view(&json!({"tools":tools,"query":query})).expect("view") + } + + fn keys(rows: &Value) -> Vec { + rows.as_array() + .expect("rows") + .iter() + .map(|row| match row["kind"].as_str() { + Some("group") => row["key"].as_str().unwrap_or_default().to_owned(), + _ => format!( + "{}:{}", + row["index"], + row["status"].as_str().unwrap_or_default() + ), + }) + .collect() + } + + #[test] + fn groups_by_fixed_category_order_with_problems_first() { + let result = view(sample(), json!({})); + assert_eq!( + keys(&result["rows"]), + [ + "category:runtime", + "1:error", + "0:ok", + "category:build", + "2:warning", + "3:ok", + "category:other", + "5:ok", + "audience:plugin", + ] + ); + let plugin_group = &result["rows"][8]; + assert_eq!(plugin_group["collapsed"], true); + assert_eq!(plugin_group["problems"], 1); + assert_eq!( + result["counts"], + json!({"total":6,"matched":6,"problems":3,"errors":2,"warnings":1,"pinned":1,"changed":1}) + ); + assert_eq!(keys(&result["issues"]), ["1:error", "4:error", "2:warning"]); + } + + #[test] + fn filters_expand_groups_and_keep_counts_global() { + let result = view(sample(), json!({"filter":"problems"})); + assert_eq!( + keys(&result["rows"]), + [ + "category:runtime", + "1:error", + "category:build", + "2:warning", + "audience:plugin", + "4:error" + ] + ); + assert_eq!(result["counts"]["matched"], 3); + assert_eq!(result["counts"]["total"], 6); + let text = view(sample(), json!({"text":"/OPT"})); + assert_eq!(keys(&text["rows"]), ["category:runtime", "0:ok"]); + let pinned = view(sample(), json!({"filter":"pinned","groupBy":"none"})); + assert_eq!(keys(&pinned["rows"]), ["0:ok"]); + let changed = view(sample(), json!({"filter":"changed","groupBy":"none"})); + assert_eq!(keys(&changed["rows"]), ["3:ok"]); + } + + #[test] + fn user_overrides_and_plugin_grouping() { + let result = view( + sample(), + json!({"collapsed":["category:runtime"],"expanded":["audience:plugin"]}), + ); + assert_eq!(result["rows"][0]["collapsed"], true); + assert!( + keys(&result["rows"]).ends_with(&["audience:plugin".to_owned(), "4:error".to_owned()]) + ); + let by_plugin = view(sample(), json!({"groupBy":"plugin"})); + assert_eq!(by_plugin["rows"][0]["key"], "plugin:go"); + assert_eq!(by_plugin["rows"][0]["title"], "go"); + let many: Vec = (0..41) + .map(|index| { + tool( + &format!("t{index}"), + "T", + &format!("p{index:02}"), + json!({}), + ) + }) + .collect(); + let folded = view(many, json!({"groupBy":"plugin","expanded":["plugin:p00"]})); + assert_eq!(folded["rows"][0]["collapsed"], false); + assert_eq!(folded["rows"][2]["collapsed"], true); + } + + #[test] + fn rejects_unknown_values_and_duplicates() { + for (tools, query) in [ + ( + vec![tool("a", "A", "p", json!({"category":"compiler"}))], + json!({}), + ), + ( + vec![tool("a", "A", "p", json!({"audience":"system"}))], + json!({}), + ), + ( + vec![ + tool("a", "A", "p", json!({})), + tool("a", "B", "q", json!({})), + ], + json!({}), + ), + (vec![], json!({"filter":"broken"})), + (vec![], json!({"groupBy":"version"})), + ] { + assert!(settings_view(&json!({"tools":tools,"query":query})).is_err()); + } + assert!(settings_view(&json!({"tools":[],"query":{},"issueLimit":51})).is_err()); + } +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 5e689337..d1dab24e 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -182,7 +182,7 @@ symbolic links. A host treats an installed package as read-only. | `buildSystems` | Project-level build tools. | | `commandInstallers` | How the host installs a bare command a `systemCommand` launch needs; requires `commandInstallers: 0` and `commands.install`; see [Command installers](#command-installers). | | `managedRuntimes` | Pinned dependencies qualified by a packaged backend and installed in host-owned storage independent of plugin version; requires `managedRuntimes: 0` and `runtimes.install`; see [Managed runtimes](#managed-runtimes). | -| `toolDefinitions` | Plugin-owned tool policy ([Core foundation](toolchains/README.md)); requires `toolDefinitions: 0`; a host may offer read-only discovery and resolve Build and run tools. | +| `toolDefinitions` | Plugin-owned tool policy ([Core foundation](toolchains/README.md)); requires `toolDefinitions: 0`, or `1` when a definition sets the settings-list `category` or `audience`; a host may offer read-only discovery and resolve Build and run tools. | | `toolchainProviders` | Backend fact-provider declarations ([Core foundation](toolchains/README.md)); requires `toolchainProviders: 0`, `backend: 0` and `toolchains.provide`. | | `keymapImportProviders` | Independent shortcut import providers; requires `keymapImportProviders: 0`, `backend: 0` and `keymaps.provide`. A host provides access to explicitly selected sources. | | `pluginFunctions` | [Functions the plugin exports to, and calls from, other plugins](#cross-plugin-calls); requires `pluginFunctions: 0` and `backend: 0`, and grants no permission. A host that advertises this capability relays the calls. | diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 429cf2aa..efcd6c6d 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -31,7 +31,7 @@ "properties": { "backend": { "description": "Required exactly when backend is present: the plugin's own process. It serves its web pages, may also start on onWorkspaceOpen or a plugin command, receives workspace contexts through the litheFunctions protocol, and may be granted workspace.metadata.", "enum": [0] }, "buildModelInputs": {"description": "Optional public model sharing between already enabled workspace plugins; no installation, private function, or process authority. Required exactly when modelSharing or modelInputs is used. Consumers require buildProviders. A producer cannot also consume inputs.", "enum": [0]}, - "buildProviders": { "description": "Required exactly when any buildSystems[].provider is present, including own-process and shared language-server providers. Declares host support for Provider orchestration (task execution, test execution and discovery, run preparation, native debug preparation, optional read-only model inputs, non-sensitive native configuration sources, inline test reports, opaque semantic test selectors, typed run options and service/task preparation, registry-selected adapters and host-owned connection targets for service debugging), independent of declarative buildSystems.", "enum": [0] }, + "buildProviders": { "description": "Required exactly when any buildSystems[].provider is present, including own-process and shared language-server providers. Declares host support for Provider orchestration (task execution, test execution and discovery, run preparation, native debug preparation, optional read-only model inputs, non-sensitive native configuration sources, inline test reports, opaque semantic test selectors, typed run options and service/task preparation, registry-selected adapters and host-owned connection targets for service debugging), independent of declarative buildSystems. Version 1 adds entrypoint runs (lithe/build/runEntrypoints).", "enum": [0, 1] }, "buildSystems": { "description": "Declarative build detection, models, and command plans, including the executable setting adapter, instance-scoped options, and declarative preparation roles; does not imply buildProviders support.", "enum": [0] }, "commandInstallers": { "description": "Required exactly when commandInstallers is non-empty: installations of bare commands that systemCommand launches name, run by the host only after the user confirms them.", "enum": [0] }, "debugAdapters": { "description": "Required exactly when debugAdapters is non-empty. Covers bounded target argument and environment bindings and debugAdapters[].features and defaults. The DAP session itself is negotiated by the adapter in initialize.", "enum": [0] }, @@ -45,7 +45,7 @@ "runConfigurationTypes": { "description": "Required exactly when any buildSystems[].runConfigurationTypes is non-empty: kinds of run configuration the user creates in the Run/Debug Configurations dialog, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "settings": { "description": "Required exactly when settings or settingActions is non-empty. Covers integer, enum, boolean, multiSelect, text, file, and directory options, scope, effect, page, section, and settingActions.", "enum": [0] }, "sourceSettings": { "description": "Required exactly when a setting action declares sourceEditor. Native-source settings projection, compiler placement, confirmed staging and read-back. Version 1 adds sidebar groups, nested sources, field sections and entry lists.", "enum": [0, 1] }, - "toolDefinitions": { "enum": [0] }, + "toolDefinitions": { "description": "Required exactly when toolDefinitions is present. Version 1 adds the display-only category and audience of a definition.", "enum": [0, 1] }, "toolchainProviders": { "enum": [0] }, "keymapImportProviders": { "enum": [0] }, "pluginFunctions": { "description": "Required exactly when pluginFunctions is present: functions this plugin's backend exports to other plugins, and exported functions it calls. Needs backend.", "enum": [0] }, @@ -4135,6 +4135,14 @@ "icon": { "$ref": "#/$defs/uiIcon" }, + "category": { + "description": "toolDefinitions 1: settings display group; absent means other. Does not affect discovery or resolution.", + "enum": ["runtime", "build", "package", "debug", "lint", "other"] + }, + "audience": { + "description": "toolDefinitions 1: user (default) for a tool people run; plugin for a runtime the plugin runs for itself, such as a language server's JDK.", + "enum": ["user", "plugin"] + }, "executableLayouts": { "type": "array", "minItems": 1, diff --git a/shared/plugins/contract/v1/toolchains/README.md b/shared/plugins/contract/v1/toolchains/README.md index 4146e0f5..0b0533e1 100644 --- a/shared/plugins/contract/v1/toolchains/README.md +++ b/shared/plugins/contract/v1/toolchains/README.md @@ -28,7 +28,8 @@ contribution. Executable candidate sets keep their strict source types; the does not gain definition-owned candidate fields (see [Executable resolution](../README.md#executable-resolution)). -Definitions own IDs, labels/icons, `executableLayouts`, ordered `executables`, +Definitions own IDs, labels/icons, optional display `category` and `audience`, +`executableLayouts`, ordered `executables`, `version`, `homeLayouts`, `discovery`, `homeVariable`, `commands`, `wrappers`, `exports`, `pathPrepend` and argv `launch`. Counts, relative paths, bounded globs, platforms, templates and version expressions are validated recursively; unknown @@ -36,6 +37,16 @@ fields fail closed. Candidate graph ordering reuses the existing shared graph validator and cannot cross layer barriers. This slice does not support a definition candidate of `kind: runtime`, or `toolchainConsumers`. +`category` places the tool in one settings group: `runtime` (runtimes and SDKs), +`build`, `package` (package managers), `debug` (debuggers and profilers), `lint` +(checkers and formatters) or `other`; it defaults to `other`. `audience` is +`user` (the default) or `plugin` for a runtime a plugin only runs for itself, +such as the JVM behind a language server. Both change only where the settings +list shows the tool; resolution, pins and launches ignore them. Other values +reject the manifest. They are `toolDefinitions` version 1: a manifest that sets +either requires `toolDefinitions: 1`, and a host that supports only version 0 +does not install it. Definitions without them keep requiring `0`. + `version` is `{arguments, pattern}`. `arguments` lists one to eight distinct literal words of at most 64 bytes. The first is a flag (`-version`, `--version`) or a subcommand (`version`, for a tool such as Go that prints its @@ -122,6 +133,7 @@ are not a substitute for that adapter. These commands perform no native I/O. | `toolchains.instantiateLaunch` | `{registry,tool,executable,home?,entry?,runtimeArguments,arguments}` | `launch` | | `toolchains.discoveryPlan` | `{registry,platform}` | `plan` | | `toolchains.candidates` | Captured discovery input described below | `candidates` | +| `toolchains.settingsView` | `{tools,query,issueLimit?}` described below | `view` | Every `registry` input is the raw `{plugins:[{manifest}]}` request of the enabled plugins, not a previously normalized result. Core revalidates complete production @@ -459,6 +471,48 @@ so a project program is never run passively to read its version. The desktop hos bounds probes by count, concurrency and total time, and reports skipped work as diagnostics rather than a missing tool. +## Settings list + +`settingsView` projects the settings list of every enabled tool, so a host never +classifies resolver reasons, filters, groups, sorts or counts by itself. It reads +facts the host already holds and performs no resolution. Input: + +- `tools` (at most 20,000) are `{id,displayName,pluginID,pluginName?,category?, + audience?,reason?,pinned?,changed?,terms?}`. `category` and `audience` come + from the registry definition. `reason` is the stable code the resolver returned + for the effective layer, absent when an installation applies. `pinned` marks a + manually chosen installation, `changed` an edit that is not applied yet. + `terms` (at most 16) is further searchable text such as versions and paths. + IDs are unique. +- `query` is `{text?,filter?,groupBy?,collapsed?,expanded?}`. `filter` is `all` + (default), `problems`, `pinned` or `changed`; `groupBy` is `category` + (default), `plugin` or `none`. `collapsed` and `expanded` list group keys the + user toggled. +- `issueLimit` (default 5, at most 50) bounds `issues`. + +Each tool has a status. No `reason` is `ok`. `projectCodeRequiresAction`, +`ambiguousInstallation` and `probeFailed` are `warning`: the user clears them by +trusting the project, choosing an installation or probing again. Any other +reason is `error`. The output `view` is `{rows,issues,counts}`: + +- `rows` is the list to render, top to bottom. A group row is + `{kind:"group",key,count,problems,collapsed}` with `category`, `audience` or + `pluginID` and `title`; a tool row is `{kind:"tool",index,status}`, where + `index` points into `tools`. Grouping by category uses keys `category:` + in the order listed above, and puts every `audience: plugin` tool last under + `audience:plugin`. Grouping by plugin uses `plugin:`, ordered by + plugin name. Inside a group, and in the `none` list, errors come first, then + warnings, then the rest, each by name. +- A group is collapsed when the user collapsed it; otherwise `audience:plugin` + starts collapsed, and so does every plugin group when there are more than 40. + While `text` or a filter other than `all` applies, no group is collapsed, so a + match is never hidden. +- `issues` lists the first problems in the same order as `{index,status}`. +- `counts` is `{total,matched,problems,errors,warnings,pinned,changed}`. Only + `matched` depends on the query. + +## Fixtures and acceptance vectors + Production-shape examples are [tool-definition.plugin.json](../fixtures/toolchains/tool-definition.plugin.json) and [toolchain-provider.plugin.json](../fixtures/toolchains/toolchain-provider.plugin.json). Core acceptance vectors are in diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 94ec6a61..6eebd607 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -36,7 +36,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https ### 能力版本(`requires`) -每一行是一个能力。`requires` 必须**恰好**列出清单用到的能力:漏一个或多列一个都是 `plugin.manifest.invalid`;每个能力的值都是 `0`。启动进程([Process start](../contract/v1/README.md#process-start))和可执行文件解析([Executable resolution](../contract/v1/README.md#executable-resolution))属于基础契约,不是能力;写 `requires.serverProcess` 会像未知能力一样被拒绝。 +每一行是一个能力。`requires` 必须**恰好**列出清单用到的能力:漏一个或多列一个都是 `plugin.manifest.invalid`;每个能力的值是能覆盖插件用法的最低版本,没有用到 `1` 的新内容就写 `0`。启动进程([Process start](../contract/v1/README.md#process-start))和可执行文件解析([Executable resolution](../contract/v1/README.md#executable-resolution))属于基础契约,不是能力;写 `requires.serverProcess` 会像未知能力一样被拒绝。 | 版本 | 内容 | Core | Lithe 桌面端 | 详见 | | --- | --- | --- | --- | --- | @@ -61,6 +61,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | +| `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | 未声明 | [工具链](domains/toolchains.md) | | `pluginFunctions` `0` | 清单顶层 [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls):导出的函数(`exports`)和要调用的其他插件函数(`calls`);不授予任何清单权限,调用经 Core 中转 | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | | `keymapImportProviders` `0` | `keymapImportProviders[]`:[独立的快捷键导入提供者](../contract/v1/README.md#shortcut-import-providers-core-foundation);说 `litheKeymapImport` | ✅ | 未声明 | [快捷键导入](domains/keymap-import.md) | @@ -148,7 +149,7 @@ Future changes follow the contract's rules: ### Capability versions (`requires`) -Each row is one capability. `requires` lists **exactly** the capabilities a manifest uses: leaving one out or listing an unused one is `plugin.manifest.invalid`; every value is `0`. [Process start](../contract/v1/README.md#process-start) and [Executable resolution](../contract/v1/README.md#executable-resolution) belong to the base contract and are not capabilities; `requires.serverProcess` is refused like any unknown capability. +Each row is one capability. `requires` lists **exactly** the capabilities a manifest uses: leaving one out or listing an unused one is `plugin.manifest.invalid`; each value is the lowest version that covers the plugin's use, so `0` unless the plugin uses something a version `1` added. [Process start](../contract/v1/README.md#process-start) and [Executable resolution](../contract/v1/README.md#executable-resolution) belong to the base contract and are not capabilities; `requires.serverProcess` is refused like any unknown capability. | Version | Content | Core | Lithe desktop | See | | --- | --- | --- | --- | --- | @@ -173,6 +174,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | +| `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | Not declared | [Toolchains](domains/toolchains.md) | | `pluginFunctions` `0` | The manifest's top-level [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls): the functions the plugin exports (`exports`) and the functions of other plugins it calls (`calls`); grants no manifest permission, and Core relays the calls | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | | `keymapImportProviders` `0` | `keymapImportProviders[]`: [independent shortcut import providers](../contract/v1/README.md#shortcut-import-providers-core-foundation); they speak `litheKeymapImport` | ✅ | Not declared | [Shortcut import](domains/keymap-import.md) | diff --git a/shared/plugins/reference/domains/toolchains.md b/shared/plugins/reference/domains/toolchains.md index 9c816b91..4c999db3 100644 --- a/shared/plugins/reference/domains/toolchains.md +++ b/shared/plugins/reference/domains/toolchains.md @@ -9,7 +9,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `toolDefinitions[]`(工具定义)、`toolchainProviders[]`(工具链提供者)、顶层 `requiresTools`(启动时引用的工具定义 ID) | -| 能力 | `toolDefinitions` 0;`toolchainProviders` 0(还需要 `backend` 0) | +| 能力 | `toolDefinitions` 0(用到 `category`、`audience` 时为 1);`toolchainProviders` 0(还需要 `backend` 0) | | 协议 | 工具链提供者协议 `litheToolchains`,版本 `0`:宿主通过 `toolchains/query` 向提供者的后端查询。协商见[契约](../../contract/v1/toolchains/README.md#provider-backend-negotiation) | | API 编号 | [API-23](../api-catalog.md#现在能用的-api):工具链与受管进程(部分完成) | | 权限 | 工具定义不需要权限;提供者需要 `backend.launch` 和 `toolchains.provide` | @@ -51,6 +51,10 @@ - 注册表的输出带 `conflicts: [{tool, pluginIDs}]`:每个被争用的工具一条,按 `tool` 排序,`pluginIDs` 是所有定义它的插件 ID(也排序)。宿主应当告诉用户是哪些插件在争用。 - 同一个插件 ID 在一批输入里重复出现,仍然拒绝整批,不会替换先前登记的归属。 +### 设置页里的分组 + +工具定义可以写 `category`,决定它在设置页「工具链」列表里归哪一组:`runtime`(运行时与 SDK)、`build`(构建工具)、`package`(包管理器)、`debug`(调试与分析)、`lint`(检查与格式化)、`other`(其他,默认)。插件只给自己用的运行时(例如语言服务器背后的 JVM)写 `audience: "plugin"`,它们单独放在最后一组,默认折叠;默认是 `user`。这两个字段只影响显示位置,不影响解析、固定和启动。写别的值会拒绝整个清单。它们属于 `toolDefinitions` 版本 1:用到任一字段的插件声明 `toolDefinitions: 1`,只支持 0 的宿主不会安装;不用它们的插件继续写 `0`。 + ### Core 命令 所有命令都只处理 UTF-8 JSON,输入上限 4 MiB,不做任何本机 I/O。成功返回 `{status: "ok", <键>: 值}`,拒绝返回 `{status: "rejected", error: {code, message, field?}}`。 @@ -66,6 +70,7 @@ | `toolchains.instantiateLaunch` | `{registry, tool, executable, home?, entry?, runtimeArguments, arguments}` | `launch` | 按工具定义的 `launch` 模板,为宿主选中的可执行文件展开启动参数,返回 `{executable, arguments, versionArguments}`;见“按工具定义 ID 启动进程” | | `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | 每个工具的扫描计划、声明它的提供者、登录 shell 变量和平台过滤后的 `projectFiles`;最多 256 个根目录、4096 个条目、64 层祖先 | | `toolchains.candidates` | 设置页的发现输入 | `candidates` | 设置页显示的根级项目候选、登录 shell 和自动层:`{tool, project, shell, installations, skipped, selected, conflicts}`;未授权项目候选不给出待探测 `executable`,已授权且安全校验通过后首次调用把待探测可执行文件列为 `probeFailed`,宿主运行探针后再调用一次 | +| `toolchains.settingsView` | `{tools, query, issueLimit?}` | `view` | 设置页工具列表的投影:按解析原因给每个工具定出 `error`、`warning`、`ok`,按文字和“需要处理 / 已手动指定 / 未应用”筛选,按种类、插件或不分组,返回要显示的行 `rows`、前几项问题 `issues` 和计数 `counts`;最多 20,000 个工具。宿主不自己分类、排序或计数,见[Settings list](../../contract/v1/toolchains/README.md#settings-list) | ### 提供者应答的限制 @@ -153,7 +158,7 @@ Core 的 `plugins.managedRuntimes.plan` 选择准确平台并生成缓存键,` | [Plugin-owned toolchains (Core foundation)](../../contract/v1/README.md#plugin-owned-toolchains-core-foundation) | 契约总入口里的工具链说明和当前宿主状态 | | [Manifest admission and registry](../../contract/v1/toolchains/README.md#manifest-admission-and-registry) | 能力和权限要求、定义字段、提供者字段、ID 规则(短 ID 与限定 ID) | | [Two installation routes](../../contract/v1/toolchains/README.md#two-installation-routes) | 声明式发现和提供者查询 | -| [Commands and envelopes](../../contract/v1/toolchains/README.md#commands-and-envelopes) | 九个 Core 命令、返回格式、注册表限制、`conflicts` | +| [Commands and envelopes](../../contract/v1/toolchains/README.md#commands-and-envelopes) | 十个 Core 命令、返回格式、注册表限制、`conflicts` | | [Launching a tool definition](../../contract/v1/toolchains/README.md#launching-a-tool-definition) | `toolchains.instantiateLaunch`:按定义的 `launch` 模板展开启动参数、`launchMismatch` | | [Tool references](../../contract/v1/README.md#tool-references) | 清单 `requiresTools`、引用位置、启动计划的各部分、`plugin.host.toolUnresolved` | | [Run and debug sessions](../../contract/v1/README.md#run-and-debug-sessions) | `run/start` 的 `process.executable`:`{kind: "tool"}` 或 `{kind: "packaged"}` | @@ -161,6 +166,7 @@ Core 的 `plugins.managedRuntimes.plan` 选择准确平台并生成缓存键,` | [Error replies](../../contract/v1/toolchains/README.md#error-replies) | 错误回复的格式,以及 11 个稳定失败码的数字码对照 | | [Pins and snapshot resolution](../../contract/v1/toolchains/README.md#pins-and-snapshot-resolution) | `local.json`、`resolve`、四层选择、`checkVersion`、`discoveryPlan` | | [Settings candidates](../../contract/v1/toolchains/README.md#settings-candidates) | `candidates` 和两次调用的探测流程 | +| [Settings list](../../contract/v1/toolchains/README.md#settings-list) | `settingsView`:状态分类、筛选、分组、折叠默认值和计数 | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | 可执行文件候选的排序和严格选择 | | [Command installers](../../contract/v1/README.md#command-installers) | `commandInstallers[]` 的字段、两个目标、三个 Core 命令和宿主步骤 | | [Provider backend negotiation](../../contract/v1/toolchains/README.md#provider-backend-negotiation) | `litheToolchains` 协商、`lsp.toolchainRequest`、超时 | @@ -232,6 +238,10 @@ A requirement with no installation stays "unmet", with its reason, even when a l - The registry returns `conflicts: [{tool, pluginIDs}]`: one entry per contested tool, sorted by `tool`, with every defining plugin ID, sorted. A host should tell the user which plugins contest the tool. - A plugin ID repeated within one input still rejects the whole batch, without replacing earlier owners. +### Groups on the settings page + +A tool definition may set `category` to choose its group in the settings page's Toolchains list: `runtime` (runtimes and SDKs), `build` (build tools), `package` (package managers), `debug` (debuggers and profilers), `lint` (checkers and formatters) or `other` (the default). A runtime a plugin only runs for itself, such as the JVM behind a language server, sets `audience: "plugin"`; such tools sit in their own last group, collapsed by default. The default is `user`. Both fields only change where the tool is shown, never resolution, pins or launches. Any other value rejects the whole manifest. They are `toolDefinitions` version 1: a plugin that sets either declares `toolDefinitions: 1`, and a host that supports only 0 does not install it; plugins that do not use them keep `0`. + ### Core commands Every command accepts UTF-8 JSON, has a 4 MiB input budget, and performs no native I/O. Success is `{status: "ok", : value}`; refusal is `{status: "rejected", error: {code, message, field?}}`. @@ -247,6 +257,7 @@ Every command accepts UTF-8 JSON, has a 4 MiB input budget, and performs no nati | `toolchains.instantiateLaunch` | `{registry, tool, executable, home?, entry?, runtimeArguments, arguments}` | `launch` | Expands the definition's `launch` template for the executable the host selected, returning `{executable, arguments, versionArguments}`; see "Launching a process by tool-definition ID" | | `toolchains.discoveryPlan` | `{registry, platform}` | `plan` | Each tool's scan plan, the providers that declare it, login-shell variables, and platform-filtered `projectFiles`. Limits: 256 roots, 4096 entries, 64 ancestors | | `toolchains.candidates` | The settings page's discovery input | `candidates` | Root project candidates, login-shell homes, and the automatic layer shown on a settings page: `{tool, project, shell, installations, skipped, selected, conflicts}`. Untrusted project candidates emit no `executable` to probe; once trusted and checked, the first call lists executables to probe as `probeFailed`, and the host runs the probes and calls again | +| `toolchains.settingsView` | `{tools, query, issueLimit?}` | `view` | Projects the settings page's tool list: classifies each tool as `error`, `warning` or `ok` from its resolver reason, filters by text and by "needs attention / chosen manually / not applied", groups by category, plugin or nothing, and returns the rows to show (`rows`), the first problems (`issues`) and `counts`. At most 20,000 tools. The host does not classify, sort or count by itself; see [Settings list](../../contract/v1/toolchains/README.md#settings-list) | ### Limits on provider replies @@ -334,7 +345,7 @@ Core's `plugins.managedRuntimes.plan` selects the exact platform and generates c | [Plugin-owned toolchains (Core foundation)](../../contract/v1/README.md#plugin-owned-toolchains-core-foundation) | The toolchain overview in the contract entry point and the current host status | | [Manifest admission and registry](../../contract/v1/toolchains/README.md#manifest-admission-and-registry) | Capability and permission requirements, definition and provider fields, ID rules (short and qualified IDs) | | [Two installation routes](../../contract/v1/toolchains/README.md#two-installation-routes) | Declarative discovery and provider query | -| [Commands and envelopes](../../contract/v1/toolchains/README.md#commands-and-envelopes) | The nine Core commands, return shapes, registry limits, `conflicts` | +| [Commands and envelopes](../../contract/v1/toolchains/README.md#commands-and-envelopes) | The ten Core commands, return shapes, registry limits, `conflicts` | | [Launching a tool definition](../../contract/v1/toolchains/README.md#launching-a-tool-definition) | `toolchains.instantiateLaunch`: expanding the launch template, `launchMismatch` | | [Tool references](../../contract/v1/README.md#tool-references) | The manifest's `requiresTools`, reference sites, the parts of a launch plan, `plugin.host.toolUnresolved` | | [Run and debug sessions](../../contract/v1/README.md#run-and-debug-sessions) | `process.executable` of `run/start`: `{kind: "tool"}` or `{kind: "packaged"}` | @@ -342,6 +353,7 @@ Core's `plugins.managedRuntimes.plan` selects the exact platform and generates c | [Error replies](../../contract/v1/toolchains/README.md#error-replies) | The error reply format and the numeric codes of the 11 stable failure codes | | [Pins and snapshot resolution](../../contract/v1/toolchains/README.md#pins-and-snapshot-resolution) | `local.json`, `resolve`, the four layers, `checkVersion`, `discoveryPlan` | | [Settings candidates](../../contract/v1/toolchains/README.md#settings-candidates) | `candidates` and its two-call probe flow | +| [Settings list](../../contract/v1/toolchains/README.md#settings-list) | `settingsView`: status classes, filters, groups, default folding and counts | | [Executable resolution](../../contract/v1/README.md#executable-resolution) | Ordering and strict selection of executable candidates | | [Command installers](../../contract/v1/README.md#command-installers) | The fields of `commandInstallers[]`, the two targets, the three Core commands and the host steps | | [Provider backend negotiation](../../contract/v1/toolchains/README.md#provider-backend-negotiation) | `litheToolchains` negotiation, `lsp.toolchainRequest`, timeouts | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index b8cc6223..f5c430e4 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -16,6 +16,8 @@ - `managedRuntimes` 0(API-23):新增固定 HTTPS 归档与 SHA-256、平台选择、与插件版本无关的缓存身份,以及插件后端对外部/暂存依赖的资格检查契约。新增权限 `runtimes.install`、审查程序 `managedRuntime`、Core 命令 `plugins.managedRuntimes.plan` 与 `plugins.managedRuntimes.decodeResolution`;正常语言服务器启动可接收只读 `runtimes` 映射。原生 `lsp.startServer` 新增可选 `functionRelayEnabled`(默认 true),准备会话设为 false 隔离跨插件调用但保留宿主直接调用。无新增宿主 RPC 或 SDK 版本。实现见 [#96](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/96)(lithe-support[bot]);合入日期在合并后补入下方时间线。宿主须先发布对应能力,插件才可要求它。 +- **`toolDefinitions` 1**(API-23、API-19):工具定义新增只影响显示位置的 `category`(`runtime`、`build`、`package`、`debug`、`lint`、`other`,默认 `other`)和 `audience`(`user` 默认,`plugin` 表示插件自用的运行时);用到任一字段的插件声明 `toolDefinitions: 1`,只支持 0 的宿主不会安装,其他插件继续写 0。新增 Core 命令 `toolchains.settingsView`:按宿主已有的解析原因、固定和未应用状态给设置页工具列表分类(`error`、`warning`、`ok`)、筛选、分组、折叠和计数,最多 20,000 个工具。`plugins.settings.navigation` 支持三级、每项可选 `limit`(超出的子项折叠成一行“全部 N 个”)以及每行的 `matched` 与 `path`。清单 schema 的 `requires.buildProviders` 补上 #89 已支持的版本 1。没有新增宿主方法、通知或 SDK 版本。实现见 [#99](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/99)([@xiaoyumuxi](https://github.com/xiaoyumuxi));合入日期在合并后补入下方时间线。宿主须先声明 `toolDefinitions` 1,插件才可要求它。 + ## 按协议查首次出现 所有版本都从 `0` 开始。以后一个 PR 给某个能力加版本 `1` 时,在对应的表里为它加一行。 @@ -60,6 +62,7 @@ | `sourceSettings` | 1 | 2026-11-17 | [#79](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/79) | | `settings` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `toolDefinitions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `toolDefinitions` | 1 | 2026-11-18 | [#99](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/99) | | `toolchainProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `ui` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `vcsProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) |