From 88f995bd1fc1435ab73d4a8601d4285f1c967e2a Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 07:39:41 -0800 Subject: [PATCH 1/3] feat(settings): add source-backed compiler and library forms --- rust/contracts/application-boundary.md | 14 + rust/contracts/rust-core-api.md | 14 + rust/crates/build/src/invocation.rs | 3 + rust/crates/core/src/protocol/command.rs | 15 + .../core/src/runtime/dispatcher/plugins.rs | 15 + .../core/src/tests/build_runtime_versions.rs | 12 +- rust/crates/core/src/tests/mod.rs | 1 + .../core/src/tests/plugin_source_settings.rs | 57 ++ rust/crates/plugin-manifest/src/settings.rs | 29 + .../plugin-manifest/src/settings_surfaces.rs | 2 +- rust/crates/plugin-manifest/src/validation.rs | 12 +- rust/crates/plugin-model/src/capabilities.rs | 4 + rust/crates/plugin-model/src/settings.rs | 49 ++ .../crates/plugin-model/src/settings/pages.rs | 1 + .../plugin-model/src/settings/sources.rs | 537 ++++++++++++++++++ .../src/settings/sources/tests.rs | 154 +++++ rust/fixtures/plugins/settings-sources.json | 95 ++++ shared/plugins/contract/v1/README.md | 78 +++ .../settings/source-editor.plugin.json | 16 + .../contract/v1/plugin-manifest.schema.json | 7 +- .../reference/capabilities-and-versions.md | 10 +- shared/plugins/reference/domains/settings.md | 10 + 22 files changed, 1126 insertions(+), 9 deletions(-) create mode 100644 rust/crates/core/src/tests/plugin_source_settings.rs create mode 100644 rust/crates/plugin-model/src/settings/sources.rs create mode 100644 rust/crates/plugin-model/src/settings/sources/tests.rs create mode 100644 rust/fixtures/plugins/settings-sources.json create mode 100644 shared/plugins/contract/v1/fixtures/settings/source-editor.plugin.json diff --git a/rust/contracts/application-boundary.md b/rust/contracts/application-boundary.md index 2c2082f6..0018e46d 100644 --- a/rust/contracts/application-boundary.md +++ b/rust/contracts/application-boundary.md @@ -18,6 +18,20 @@ verification scripts are the executable source of boundary checks. - Every asynchronous operation exposes `idle`, `loading`, `ready`, and `failed` outcomes. - Failures contain a stable `code` and user-facing `message`; platform details belong in `details`. +## Source-backed plugin settings + +Source-backed plugin settings use `sourceSettings: 0` and the three +`plugins.settings.source*` commands. Plugins supply only allowlisted non-sensitive +fields from their upstream configuration; Core validates and projects the form, +inheritance and confirmed edits. Native adapters capture workspace identity, +reject installation roots and source aliases, verify exact revisions, create +private existing staging files and publish with guarded atomic replacement. +Opening or cancelling a page never writes sources. A failed read-back retains +drafts and cannot announce that settings took effect. Closing or replacing the +workspace or plugin revokes pending publication and cleans staging files. +See [source-editor protocol](../../shared/plugins/contract/v1/README.md#source-backed-settings-editors) +and [the inert fixture](../fixtures/plugins/settings-sources.json). + ## Shared built-in translations [Shared i18n](https://github.com/1lck/Lithe-IDEA/blob/preview/shared/i18n/README.md) owns migrated semantic keys, typed named parameters, diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 983f4cde..a767f102 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -462,6 +462,9 @@ or removing a command fails until the table changes in the same commit. | `plugins.settings.catalog` | Project enabled plugin settings pages from installed manifests | | `plugins.settings.navigation` | Project searched settings navigation without platform policy | | `plugins.settings.delivery` | Route committed preference effects using native ownership facts | +| `plugins.settings.sourceState` | Validate a source-editor function result and project inherited native control inputs | +| `plugins.settings.sourceEdit` | Validate explicit confirmation and derive changed source-bound values without file I/O | +| `plugins.settings.sourceReceipt` | Bind a private staged-file receipt to a confirmed source and exact byte revision | | `plugins.declarative.settingsState` | Read complete plugin preference documents and packaged translations into Core-normalized rows, sources, and bounded native read plans | | `plugins.declarative.settingsActionPlan` | Resolve an installed settings action and its native confirmation requirement | | `plugins.installed.select` | Select numeric installed versions from native facts without reading paths | @@ -6495,3 +6498,14 @@ state or diagnostic payload. executes through the rule dispatcher, the Core JSON envelope and the desktop bridge. It covers repeats, either history entry point, clearing, visible arrivals, non-prefix display order, read/unread eviction and invalid inputs. + +### Build runtime resolution + +`build.invocation` includes declared `runtimeDependencies` before its primary +executable candidates. Each requirement supplies its candidate plans, minimum +version and `pathVariable` (`LITHE__PATH`). The native adapter +resolves and validates these runtimes first, applies Core-selected environment +and executable exports, then resolves/probes the main build tool in that same +environment. User-configured invocation environment retains its existing +precedence. Host-managed runtime candidates are explicit `runtime` plans; hosts +must not infer executable names from opaque runtime IDs. diff --git a/rust/crates/build/src/invocation.rs b/rust/crates/build/src/invocation.rs index 0de23fa6..f17814d2 100644 --- a/rust/crates/build/src/invocation.rs +++ b/rust/crates/build/src/invocation.rs @@ -100,6 +100,8 @@ fn runtime( // definition with the same ID; resolving it checks `minimumVersion`. let executables = if runtime.names_tool_definition() { vec![json!({ "kind": "toolchain", "toolchainID": runtime.id, "root": root })] + } else if runtime.is_host_managed() { + vec![json!({"kind":"runtime","runtime":runtime.id})] } else { candidates(&runtime.executables, root, platform, manifest, settings)? }; @@ -107,6 +109,7 @@ fn runtime( "id": runtime.id, "displayName": runtime.display_name, "hostManaged": runtime.is_host_managed(), + "pathVariable":format!("LITHE_{}_PATH",runtime.id.to_ascii_uppercase().replace('-',"_")), "minimumVersion": runtime.minimum_version, "executables": executables, "version": version, diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 4d8b49ac..eb5bbc2a 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -256,6 +256,12 @@ pub enum PluginsCommand { SettingsNavigation, /// Routes committed preference effects using native ownership facts. SettingsDelivery, + /// Validates a plugin's native workspace settings projection. + SettingsSourceState, + /// Plans confirmed changes without copying source documents into RPC. + SettingsSourceEdit, + /// Binds a plugin's private staging receipt to its confirmed source. + SettingsSourceReceipt, /// Resolves an installed settings action and its native confirmation requirement. DeclarativeSettingsActionPlan, /// Selects numeric installed versions and reports malformed native facts. @@ -1038,6 +1044,15 @@ impl CoreCommand { Some(Self::Plugins(PluginsCommand::SettingsNavigation)) } "plugins.settings.delivery" => Some(Self::Plugins(PluginsCommand::SettingsDelivery)), + "plugins.settings.sourceState" => { + Some(Self::Plugins(PluginsCommand::SettingsSourceState)) + } + "plugins.settings.sourceEdit" => { + Some(Self::Plugins(PluginsCommand::SettingsSourceEdit)) + } + "plugins.settings.sourceReceipt" => { + Some(Self::Plugins(PluginsCommand::SettingsSourceReceipt)) + } "plugins.declarative.settingsState" => { Some(Self::Plugins(PluginsCommand::DeclarativeSettingsState)) } diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 65348442..abbcbe62 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -95,6 +95,21 @@ pub(super) fn dispatch( PluginsCommand::SettingsCatalog => { plugin_response(id, payload, lithe_plugin_manifest::settings_catalog_command) } + PluginsCommand::SettingsSourceState => plugin_response( + id, + payload, + lithe_plugin_model::settings::sources::state_command, + ), + PluginsCommand::SettingsSourceEdit => plugin_response( + id, + payload, + lithe_plugin_model::settings::sources::edit_command, + ), + PluginsCommand::SettingsSourceReceipt => plugin_response( + id, + payload, + lithe_plugin_model::settings::sources::receipt_command, + ), PluginsCommand::SettingsNavigation => plugin_response( id, payload, diff --git a/rust/crates/core/src/tests/build_runtime_versions.rs b/rust/crates/core/src/tests/build_runtime_versions.rs index bad2afdf..42f2953f 100644 --- a/rust/crates/core/src/tests/build_runtime_versions.rs +++ b/rust/crates/core/src/tests/build_runtime_versions.rs @@ -47,7 +47,16 @@ fn host_runtime_probe_arguments_are_portable_across_platforms() { .enumerate() { assert_eq!(runtimes[index]["hostManaged"], true, "{platform}"); - assert_eq!(runtimes[index]["executables"], json!([]), "{platform}"); + let id = if index == 0 { "node" } else { "go" }; + assert_eq!( + runtimes[index]["executables"], + json!([{"kind":"runtime","runtime":id}]), + "{platform}" + ); + assert_eq!( + runtimes[index]["pathVariable"], + format!("LITHE_{}_PATH", id.to_ascii_uppercase()) + ); assert_eq!( runtimes[index]["version"]["arguments"], arguments, "{platform}" @@ -77,6 +86,7 @@ fn runtime_without_executables_becomes_a_toolchain_candidate() { "id": "vm", "displayName": null, "hostManaged": false, + "pathVariable":"LITHE_VM_PATH", "executables": [ { "kind": "toolchain", "toolchainID": "vm", "root": "." } ], diff --git a/rust/crates/core/src/tests/mod.rs b/rust/crates/core/src/tests/mod.rs index 57da99c3..89405728 100644 --- a/rust/crates/core/src/tests/mod.rs +++ b/rust/crates/core/src/tests/mod.rs @@ -46,6 +46,7 @@ mod notification_read; mod plugin_editor_resources; mod plugin_run_debug; mod plugin_settings_documents; +mod plugin_source_settings; mod process_memory; mod project; mod project_generators; diff --git a/rust/crates/core/src/tests/plugin_source_settings.rs b/rust/crates/core/src/tests/plugin_source_settings.rs new file mode 100644 index 00000000..e6a026aa --- /dev/null +++ b/rust/crates/core/src/tests/plugin_source_settings.rs @@ -0,0 +1,57 @@ +//! Public-dispatch coverage for the shared source-backed settings fixture. + +use serde_json::{json, Value}; + +#[test] +fn native_source_settings_fixture_is_available_through_the_public_boundary() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/plugins/settings-sources.json" + ))) + .unwrap(); + let response: Value = serde_json::from_str(&crate::execute_json( + &json!({"command":"plugins.settings.sourceState","payload":{"result":fixture["snapshot"]}}) + .to_string(), + )) + .unwrap(); + assert_eq!(response["ok"], true, "{response}"); + assert_eq!(response["data"]["status"], "ok", "{response}"); + assert_eq!( + response["data"]["state"]["inputs"]["root"]["target"]["inherit"], + true + ); +} + +#[test] +fn source_editor_actions_require_explicit_host_capability_and_keep_their_binding() { + let manifest: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/settings/source-editor.plugin.json" + ))) + .unwrap(); + let run = |command: &str, payload: Value| -> Value { + serde_json::from_str(&crate::execute_json( + &json!({"command":command,"payload":payload}).to_string(), + )) + .unwrap() + }; + let old_host = json!({"backend":[0],"languages":[0],"settings":[0]}); + let refused = run( + "plugins.declarative.validate", + json!({"manifest":manifest,"hostCapabilities":old_host}), + ); + assert_eq!( + refused["data"]["error"]["code"], "plugin.api.unsupported", + "{refused}" + ); + let plan = run( + "plugins.declarative.settingsActionPlan", + json!({ + "manifest":manifest,"owner":{"pluginID":"dev.lithe.test.source-settings","version":"1.0.0"}, + "actionID":"compiler","enabled":true,"confirmed":false,"workspaceAvailable":true + }), + ); + assert_eq!(plan["data"]["plan"]["sourceEditor"], true, "{plan}"); + assert_eq!(plan["data"]["plan"]["function"], "compiler.settings"); + assert_eq!(plan["data"]["plan"]["params"], json!({})); +} diff --git a/rust/crates/plugin-manifest/src/settings.rs b/rust/crates/plugin-manifest/src/settings.rs index 28c815fb..b8f20258 100644 --- a/rust/crates/plugin-manifest/src/settings.rs +++ b/rust/crates/plugin-manifest/src/settings.rs @@ -48,6 +48,35 @@ impl DeclarativePluginManifest { for (index, action) in self.setting_actions.iter().enumerate() { let field = format!("settingActions[{index}]"); action.validate(&field)?; + if let Some(editor) = &action.source_editor { + if self.backend.is_none() { + return Err(invalid( + &field, + "A source editor requires the plugin's own backend.", + )); + } + if editor + .build_system_id + .as_ref() + .is_some_and(|id| !self.build_systems.iter().any(|system| &system.id == id)) + { + return Err(invalid( + &field, + "A source editor may reference only a declared build system.", + )); + } + if editor.language_id.as_ref().is_some_and(|id| { + !self + .language_servers + .iter() + .any(|server| &server.language_id == id) + }) { + return Err(invalid( + &field, + "A source editor may reference only a declared language server.", + )); + } + } if !ids.insert(action.id.clone()) { return Err(invalid( format!("{field}.id"), diff --git a/rust/crates/plugin-manifest/src/settings_surfaces.rs b/rust/crates/plugin-manifest/src/settings_surfaces.rs index 7b5f2da9..01597d60 100644 --- a/rust/crates/plugin-manifest/src/settings_surfaces.rs +++ b/rust/crates/plugin-manifest/src/settings_surfaces.rs @@ -89,7 +89,7 @@ pub fn settings_catalog_command(payload: Value) -> Result { let key = page["key"].as_str().unwrap_or_default().to_owned(); let target = pages.entry(key.clone()).or_insert_with(|| json!({ "key":key,"kind":page["kind"],"id":page["id"], - "title":titles.get(&key).cloned().unwrap_or_else(|| page["id"].as_str().unwrap_or_default().to_owned()),"contributors":[] + "title":titles.get(&key).or_else(|| titles.get(&format!("language:{}",page["id"].as_str().unwrap_or_default()))).or_else(|| titles.get(&format!("buildSystem:{}",page["id"].as_str().unwrap_or_default()))).cloned().unwrap_or_else(|| page["id"].as_str().unwrap_or_default().to_owned()),"contributors":[] })); target["contributors"].as_array_mut().expect("catalog array").push(json!({ "pluginID":id,"version":manifest.version,"title":manifest.display_name,"sections":page["sections"] diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 9fe3f976..ea0d5ee8 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -259,7 +259,11 @@ impl DeclarativePluginManifest { // when the host asks it for the server's command line; an // exported function starts it when another plugin calls it. // Neither needs a page, command or workspace event. - provider_query_trigger: !self.toolchain_providers.is_empty() + provider_query_trigger: self + .setting_actions + .iter() + .any(|action| action.source_editor.is_some()) + || !self.toolchain_providers.is_empty() || !self.keymap_import_providers.is_empty() || self .language_servers @@ -301,6 +305,12 @@ impl DeclarativePluginManifest { capabilities::SETTINGS, !self.settings.is_empty() || !self.setting_actions.is_empty(), ), + ( + capabilities::SOURCE_SETTINGS, + self.setting_actions + .iter() + .any(|action| action.source_editor.is_some()), + ), (capabilities::UI, self.ui.is_some()), (capabilities::BUILD_SYSTEMS, !self.build_systems.is_empty()), ( diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index 1a60c652..e3a428db 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -56,6 +56,9 @@ pub const EXECUTION_PROVIDERS: &str = "executionProviders"; /// `settings[]`: scopes, effects, settings pages, and the multiSelect, text, /// file, and directory types; see [`crate::settings`]. pub const SETTINGS: &str = "settings"; +/// Source-backed workspace editors returned by settings actions, including +/// compiler pages and guarded native staging receipts. +pub const SOURCE_SETTINGS: &str = "sourceSettings"; /// `ui`: tool windows with text, web, or host-rendered native content, and /// commands. pub const UI: &str = "ui"; @@ -121,6 +124,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (PLUGIN_FUNCTIONS, &[0]), (PROJECT_GENERATORS, &[0]), (SETTINGS, &[0]), + (SOURCE_SETTINGS, &[0]), (TOOL_DEFINITIONS, &[0]), (TOOLCHAIN_PROVIDERS, &[0]), (UI, &[0]), diff --git a/rust/crates/plugin-model/src/settings.rs b/rust/crates/plugin-model/src/settings.rs index 8e06892f..8fc66ed8 100644 --- a/rust/crates/plugin-model/src/settings.rs +++ b/rust/crates/plugin-model/src/settings.rs @@ -22,6 +22,7 @@ pub use localization::{ }; mod pages; pub use pages::page_sections; +pub mod sources; use crate::rejection::{invalid, PluginRejection, Validation}; use regex::Regex; @@ -97,6 +98,9 @@ pub enum SettingPage { /// Build Tools › *build system*. #[serde(rename = "buildSystemID")] BuildSystem(String), + /// Build, Execution, Deployment › Compilers › *compiler*. + #[serde(rename = "compilerID")] + Compiler(String), } /// A button the host draws on a settings page that invokes one of the same @@ -126,6 +130,25 @@ pub struct SettingAction { /// Ask before invoking, for actions that discard state. #[serde(default, skip_serializing_if = "std::ops::Not::not")] confirm: bool, + /// The read result is a typed native-source form; saves invoke its distinct + /// staging function only after native confirmation. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_editor: Option, +} + +/// Explicit read/edit roles allow frequent read successes to be suppressed +/// while SDKs record confirmed edit outcomes at their ordinary boundary. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceEditorDeclaration { + /// Same-plugin function that writes only the host's private staging file. + pub edit_function: String, + /// Optional declared build system whose native tool and stored options accompany reads. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub build_system_id: Option, + /// Optional declared language server made ready before a source query. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub language_id: Option, } /// Resolves one declared action without native I/O or runtime admission. Only @@ -161,6 +184,12 @@ pub fn plan_action( plan["kind"] = json!("invoke"); plan["function"] = json!(action.function); plan["params"] = json!({}); + if let Some(editor) = &action.source_editor { + plan["sourceEditor"] = json!(true); + plan["editFunction"] = json!(editor.edit_function); + plan["buildSystemID"] = json!(editor.build_system_id); + plan["languageID"] = json!(editor.language_id); + } } Ok(plan) } @@ -171,6 +200,22 @@ pub const MAX_SETTING_ACTIONS: usize = 16; impl SettingAction { /// Checks the action as the manifest entry at `field`. pub fn validate(&self, field: &str) -> Validation<()> { + if matches!(self.page, Some(SettingPage::Compiler(_))) && self.source_editor.is_none() { + return Err(invalid( + field, + "Compiler pages require a native source-editor action.", + )); + } + if let Some(editor) = &self.source_editor { + if !crate::is_function_id(&editor.edit_function) + || editor.edit_function == self.function + { + return Err(invalid( + format!("{field}.sourceEditor.editFunction"), + "A source editor names a distinct same-plugin staging function.", + )); + } + } if !is_setting_identifier(&self.id) { return Err(invalid( format!("{field}.id"), @@ -216,6 +261,7 @@ fn check_page(page: &SettingPage, field: &str) -> Validation<()> { let (key, id) = match page { SettingPage::Language(id) => ("languageID", id), SettingPage::BuildSystem(id) => ("buildSystemID", id), + SettingPage::Compiler(id) => ("compilerID", id), }; if !is_setting_option_value(id) { return Err(invalid( @@ -470,6 +516,9 @@ impl SettingDeclaration { /// Checks the declaration against the `settings` capability contract. pub fn validate(&self, field: &str) -> Validation<()> { + if matches!(self.page, Some(SettingPage::Compiler(_))) { + return Err(invalid(field,"Compiler pages contain native source-editor actions, not stored plugin preferences.")); + } if !is_setting_identifier(&self.id) { return Err(invalid( format!("{field}.id"), diff --git a/rust/crates/plugin-model/src/settings/pages.rs b/rust/crates/plugin-model/src/settings/pages.rs index a8cd4a7c..7be150d7 100644 --- a/rust/crates/plugin-model/src/settings/pages.rs +++ b/rust/crates/plugin-model/src/settings/pages.rs @@ -43,6 +43,7 @@ pub fn page_sections( let (kind, id) = match &page { SettingPage::Language(id) => ("language", id), SettingPage::BuildSystem(id) => ("buildSystem", id), + SettingPage::Compiler(id) => ("compiler", id), }; let sections: Vec<_> = sections.into_iter().map(|(title, (rows, actions))| { json!({"title":super::localization::shown_section(localization, title),"rows":rows,"actions":actions}) diff --git a/rust/crates/plugin-model/src/settings/sources.rs b/rust/crates/plugin-model/src/settings/sources.rs new file mode 100644 index 00000000..9dc51210 --- /dev/null +++ b/rust/crates/plugin-model/src/settings/sources.rs @@ -0,0 +1,537 @@ +//! Bounded native settings forms and confirmed edits of workspace-owned sources. +//! Plugins interpret their tools; native adapters own files, staging, conditional +//! publication and read-back. Full source documents never cross this boundary. + +use crate::{decode_payload, is_identifier, outcome, PluginRejection, Validation}; +use lithe_protocol::CoreError; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +const MAX_SOURCES: usize = 1024; +const MAX_FIELDS: usize = 32; +const MAX_TEXT: usize = 8192; +const MAX_BYTES: usize = 2 * 1024 * 1024; + +#[cfg(test)] +mod tests; + +/// Read-only projection supplied by the function of a `sourceEditor` action. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceSettings { + /// Discriminator `litheSettingsSources`; not an arbitrary function result. + pub format: String, + /// Source-editor protocol version, currently zero. + pub version: u32, + /// Plugin-localized editor window title. + pub title: String, + /// Ordered sections use shared form or table controls, never plugin styles. + pub groups: Vec, + /// File bindings owned by this read snapshot. + pub sources: Vec, +} + +/// A presentation section; its identifier binds sources without interpreting them. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceGroup { + /// Stable section identity within this editor. + pub id: String, + /// Plugin-localized section heading. + pub title: String, + /// `form` presents labeled controls; `table` presents source labels as rows. + pub layout: String, + /// Localized heading of the first table column; empty uses the host default. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub row_title: String, +} + +/// One source file inside the captured workspace. Revisions cover exact bytes. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SettingsSource { + /// Opaque binding reused by edits and staging receipts. + pub id: String, + /// Identity of an existing presentation section. + pub group: String, + /// Localized source or module name displayed in the first table column. + pub title: String, + /// Normalized workspace-relative path, interpreted only by native I/O. + pub path: String, + /// `missing`, or `sha256:` followed by 64 lowercase hexadecimal digits. + pub revision: String, + /// Whether the plugin permits explicit edits of this source. + pub writable: bool, + /// Allowlisted non-sensitive fields; unrelated source content stays private. + pub fields: Vec, +} + +/// One explicitly non-sensitive raw value and its upstream effective value. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceField { + /// Opaque field binding interpreted only by the source's plugin. + pub id: String, + /// Localized label or table column heading. + pub title: String, + /// Explanation displayed by the host's information control. + #[serde(default)] + pub description: String, + /// `text`, `enum`, `boolean`, `stringList`, or `fileList`. + pub kind: String, + /// Null means the source has no explicit override. + pub value: Value, + /// Current value selected by the upstream tool, including inheritance. + pub effective_value: Value, + /// Upstream value after removing this override; null means not determined. + #[serde(default)] + pub inherited_value: Value, + /// Localized upstream origin, suitable for a compact source indicator. + pub effective_source: String, + /// Upstream-supported choices; empty for non-enumeration controls. + #[serde(default)] + pub options: Vec, +} + +/// An upstream-supported choice; its opaque value never becomes a command line. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SourceOption { + /// Opaque native value written only after confirmation. + pub value: String, + /// Localized choice label. + pub title: String, +} + +/// Native controls retain these unparsed drafts until an explicit Save. +#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceInput { + /// Unparsed text or newline-separated list draft. + #[serde(default)] + pub text: String, + /// Selected enumeration value; it must occur in the snapshot's options. + #[serde(default)] + pub choice: String, + /// Boolean control draft, ignored by other control kinds. + #[serde(default)] + pub on: bool, + /// Explicitly retain or restore absence of a native override. + #[serde(default)] + pub inherit: bool, +} + +/// A source-bound collection of changed controls, not a source document. +#[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceEdits { + /// Existing source binding from the captured snapshot. + #[serde(rename = "sourceID")] + pub source_id: String, + /// Explicitly edited controls; omitted fields remain untouched. + pub values: BTreeMap, +} + +/// One confirmed write. The adapter stages it with the action's own function. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SourceWrite { + /// Existing source binding to which the staging receipt must refer. + #[serde(rename = "sourceID")] + pub source_id: String, + /// Workspace-relative publication target copied from the snapshot. + pub path: String, + /// Exact native source revision that publication must still observe. + pub revision: String, + /// Changed native values only; null removes the corresponding override. + pub values: BTreeMap, +} + +fn rejected(field: &str) -> PluginRejection { + PluginRejection::at( + "plugin.settings.invalidSourceEditor", + field, + "Expected bounded, source-bound non-sensitive workspace settings.", + ) +} + +fn text(value: &str, limit: usize, empty: bool) -> bool { + (empty || !value.trim().is_empty()) + && value.len() <= limit + && !value.chars().any(char::is_control) +} + +fn identifier(value: &str) -> bool { + value.len() <= 128 && is_identifier(value) +} + +fn relative_path(value: &str) -> bool { + text(value, 4096, false) + && !value.contains(['\\', ':']) + && value + .split('/') + .all(|part| !part.is_empty() && part != "." && part != "..") +} + +/// Whether a revision identifies exact native bytes or an absent source. +pub fn valid_source_revision(value: &str) -> bool { + value == "missing" + || value.strip_prefix("sha256:").is_some_and(|hash| { + hash.len() == 64 + && hash + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + }) +} + +fn value_valid(field: &SourceField, value: &Value) -> bool { + if value.is_null() { + return true; + } + match field.kind.as_str() { + "boolean" => value.is_boolean(), + "enum" => value + .as_str() + .is_some_and(|value| field.options.iter().any(|option| option.value == value)), + "text" => value + .as_str() + .is_some_and(|value| text(value, MAX_TEXT, true)), + "stringList" | "fileList" => value.as_array().is_some_and(|items| { + items.len() <= 256 + && items + .iter() + .all(|item| item.as_str().is_some_and(|item| text(item, 4096, false))) + }), + _ => false, + } +} + +impl SourceSettings { + /// Rejects malformed files, aliases, controls, values and section references. + pub fn validate(&self) -> Validation<()> { + if serde_json::to_vec(self).map_or(true, |bytes| bytes.len() > MAX_BYTES) { + return Err(rejected("snapshot")); + } + if self.format != "litheSettingsSources" + || self.version != 0 + || !text(&self.title, 256, false) + || self.groups.is_empty() + || self.groups.len() > 32 + || self.sources.len() > MAX_SOURCES + { + return Err(rejected("snapshot")); + } + let mut groups = BTreeSet::new(); + for group in &self.groups { + if !identifier(&group.id) + || !groups.insert(&group.id) + || !text(&group.title, 256, false) + || !matches!(group.layout.as_str(), "form" | "table") + || !text(&group.row_title, 256, true) + { + return Err(rejected("groups")); + } + } + let mut ids = BTreeSet::new(); + let mut paths = BTreeSet::new(); + for source in &self.sources { + if !identifier(&source.id) + || !ids.insert(&source.id) + || !paths.insert(&source.path) + || !groups.contains(&source.group) + || !text(&source.title, 256, false) + || !relative_path(&source.path) + || !valid_source_revision(&source.revision) + || source.fields.is_empty() + || source.fields.len() > MAX_FIELDS + { + return Err(rejected("sources")); + } + let mut fields = BTreeSet::new(); + for field in &source.fields { + if !identifier(&field.id) + || !fields.insert(&field.id) + || !text(&field.title, 256, false) + || !text(&field.description, 2048, true) + || !text(&field.effective_source, 1024, true) + || !matches!( + field.kind.as_str(), + "text" | "enum" | "boolean" | "stringList" | "fileList" + ) + || !value_valid(field, &field.value) + || !value_valid(field, &field.effective_value) + || !value_valid(field, &field.inherited_value) + { + return Err(rejected("fields")); + } + if field.kind == "enum" { + let mut choices = BTreeSet::new(); + if field.options.is_empty() || field.options.len() > 64 { + return Err(rejected("options")); + } + for option in &field.options { + if !text(&option.value, 128, false) + || !choices.insert(&option.value) + || !text(&option.title, 256, false) + { + return Err(rejected("options")); + } + } + } else if !field.options.is_empty() { + return Err(rejected("options")); + } + } + } + Ok(()) + } +} + +impl SourceField { + /// Projects an inherited value without making it an explicit override. + pub fn input(&self) -> SourceInput { + let mut input = SourceInput { + inherit: self.value.is_null(), + ..SourceInput::default() + }; + let value = if input.inherit { + &self.effective_value + } else { + &self.value + }; + match self.kind.as_str() { + "enum" => input.choice = value.as_str().unwrap_or_default().to_owned(), + "boolean" => input.on = value.as_bool().unwrap_or_default(), + "stringList" | "fileList" => { + input.text = value + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect::>() + .join("\n"); + } + _ => input.text = value.as_str().unwrap_or_default().to_owned(), + } + input + } + + fn edited_value(&self, input: &SourceInput) -> Validation { + if input.inherit { + return Ok(Value::Null); + } + let value = match self.kind.as_str() { + "enum" => json!(input.choice), + "boolean" => json!(input.on), + "text" => json!(input.text), + "stringList" | "fileList" => { + if input.text.len() > 256 * 4096 { + return Err(rejected("input")); + } + json!(input + .text + .lines() + .filter(|line| !line.trim().is_empty()) + .collect::>()) + } + _ => return Err(rejected("input")), + }; + if !value_valid(self, &value) { + return Err(rejected("input")); + } + Ok(value) + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct StateRequest { + result: Value, +} + +/// Validates a source-editor read before any native control sees its contents. +pub fn state_command(payload: Value) -> Result { + let request: StateRequest = decode_payload(payload, "plugins.settings.sourceState")?; + Ok(outcome((|| { + if request.result.to_string().len() > MAX_BYTES { + return Err(rejected("result")); + } + let snapshot: SourceSettings = + serde_json::from_value(request.result).map_err(|_| rejected("result"))?; + snapshot.validate()?; + let inputs: BTreeMap<_, BTreeMap<_, _>> = snapshot + .sources + .iter() + .map(|source| { + ( + source.id.clone(), + source + .fields + .iter() + .map(|field| (field.id.clone(), field.input())) + .collect(), + ) + }) + .collect(); + let inherited_inputs: BTreeMap<_, BTreeMap<_, _>> = snapshot + .sources + .iter() + .map(|source| { + ( + source.id.clone(), + source + .fields + .iter() + .map(|field| { + let mut inherited = field.clone(); + inherited.effective_value = if field.value.is_null() { + field.effective_value.clone() + } else { + field.inherited_value.clone() + }; + inherited.value = Value::Null; + (field.id.clone(), inherited.input()) + }) + .collect(), + ) + }) + .collect(); + let effective_displays:BTreeMap<_,BTreeMap<_,Value>>=snapshot.sources.iter().map(|source|{ + (source.id.clone(),source.fields.iter().filter(|field|!field.value.is_null()&&field.value!=field.effective_value).map(|field|{ + let value=&field.effective_value; + let display=if value.is_null(){json!({"kind":"unknown"})}else{match field.kind.as_str(){ + "enum"=>json!({"kind":"text","text":field.options.iter().find(|option|Some(option.value.as_str())==value.as_str()).map(|option|option.title.as_str()).unwrap_or_default()}), + "boolean"=>json!({"kind":"boolean","on":value.as_bool().unwrap_or_default()}), + "fileList"|"stringList"=>json!({"kind":"list","count":value.as_array().map_or(0,Vec::len)}), + _=>json!({"kind":"text","text":value.as_str().unwrap_or_default()}), + }}; + (field.id.clone(),display) + }).collect()) + }).collect(); + let layout: Vec<_> = snapshot + .groups + .iter() + .enumerate() + .map(|(index, group)| { + let sources: Vec<_> = snapshot + .sources + .iter() + .enumerate() + .filter_map(|(index, source)| (source.group == group.id).then_some(index)) + .collect(); + json!({"group":index,"sources":sources}) + }) + .collect(); + Ok(( + "state", + json!({"snapshot":snapshot,"inputs":inputs,"inheritedInputs":inherited_inputs,"effectiveDisplays":effective_displays,"layout":layout,"limits":{ + "maximumSourceBytes":MAX_BYTES,"maximumTotalBytes":4*MAX_BYTES + }}), + )) + })())) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct EditRequest { + snapshot: SourceSettings, + edits: Vec, + confirmed: bool, +} + +/// Derives only changed raw values; native file access and publication are absent. +pub fn edit_command(payload: Value) -> Result { + let request: EditRequest = decode_payload(payload, "plugins.settings.sourceEdit")?; + Ok(outcome((|| { + request.snapshot.validate()?; + if !request.confirmed || request.edits.len() > MAX_SOURCES { + return Err(rejected("confirmed")); + } + let mut ids = BTreeSet::new(); + let mut writes = Vec::new(); + for edit in request.edits { + if !ids.insert(edit.source_id.clone()) || edit.values.len() > MAX_FIELDS { + return Err(rejected("edits")); + } + let source = request + .snapshot + .sources + .iter() + .find(|source| source.id == edit.source_id) + .ok_or_else(|| rejected("sourceID"))?; + let mut values = BTreeMap::new(); + for (id, input) in edit.values { + let field = source + .fields + .iter() + .find(|field| field.id == id) + .ok_or_else(|| rejected("fieldID"))?; + let value = field.edited_value(&input)?; + if value != field.value { + values.insert(id, value); + } + } + if values.is_empty() { + continue; + } + if !source.writable { + return Err(rejected("writable")); + } + writes.push(SourceWrite { + source_id: source.id.clone(), + path: source.path.clone(), + revision: source.revision.clone(), + values, + }); + } + let order: BTreeMap<_, _> = request + .snapshot + .sources + .iter() + .enumerate() + .map(|(index, source)| (&source.id, index)) + .collect(); + writes.sort_by_key(|write| order.get(&write.source_id).copied()); + Ok(("writes", json!(writes))) + })())) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Receipt { + format: String, + version: u32, + #[serde(rename = "sourceID")] + source_id: String, + revision: String, + changed: bool, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct ReceiptRequest { + write: SourceWrite, + result: Value, +} + +/// Binds a private staged-file receipt to the confirmed source and exact digest. +pub fn receipt_command(payload: Value) -> Result { + let request: ReceiptRequest = decode_payload(payload, "plugins.settings.sourceReceipt")?; + Ok(outcome((|| { + let receipt: Receipt = + serde_json::from_value(request.result).map_err(|_| rejected("result"))?; + if receipt.format != "litheSettingsSourceEdit" + || receipt.version != 0 + || receipt.source_id != request.write.source_id + || !valid_source_revision(&receipt.revision) + || receipt.revision == "missing" + || !receipt.changed && receipt.revision != request.write.revision + { + return Err(rejected("receipt")); + } + Ok(( + "receipt", + json!({"sourceID":receipt.source_id,"revision":receipt.revision,"changed":receipt.changed}), + )) + })())) +} diff --git a/rust/crates/plugin-model/src/settings/sources/tests.rs b/rust/crates/plugin-model/src/settings/sources/tests.rs new file mode 100644 index 00000000..335b5f7e --- /dev/null +++ b/rust/crates/plugin-model/src/settings/sources/tests.rs @@ -0,0 +1,154 @@ +//! Source projection and confirmed-edit regressions use inert synthetic facts. + +use super::*; + +fn snapshot() -> Value { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/plugins/settings-sources.json" + ))) + .unwrap(); + fixture["snapshot"].clone() +} + +#[test] +fn inheritance_is_visible_without_manufacturing_an_override() { + let state = state_command(json!({"result":snapshot()})).unwrap(); + assert_eq!(state["status"], "ok", "{state}"); + let inputs = &state["state"]["inputs"]; + assert_eq!(inputs["root"]["target"]["choice"], "one"); + assert_eq!(inputs["root"]["target"]["inherit"], true); + assert_eq!(inputs["root"]["checks"]["on"], true); + let edits: Vec<_> = inputs + .as_object() + .unwrap() + .iter() + .map(|(id, values)| json!({"sourceID":id,"values":values})) + .collect(); + let result = + edit_command(json!({"snapshot":snapshot(),"edits":edits,"confirmed":true})).unwrap(); + assert_eq!(result["writes"], json!([]), "{result}"); +} + +#[test] +fn a_module_edit_does_not_touch_project_defaults_or_sibling_sources() { + let result = edit_command(json!({"snapshot":snapshot(),"confirmed":true,"edits":[ + {"sourceID":"child","values":{"target":{"choice":"one"}}} + ]})) + .unwrap(); + assert_eq!(result["status"], "ok", "{result}"); + assert_eq!(result["writes"].as_array().unwrap().len(), 1); + assert_eq!(result["writes"][0]["path"], "child/tool.json"); + assert_eq!(result["writes"][0]["values"], json!({"target":"one"})); +} + +#[test] +fn resetting_one_override_emits_null_for_that_field_only() { + let result = edit_command(json!({"snapshot":snapshot(),"confirmed":true,"edits":[ + {"sourceID":"child","values":{"target":{"inherit":true}}} + ]})) + .unwrap(); + assert_eq!(result["writes"][0]["values"], json!({"target":null})); +} + +#[test] +fn file_list_editing_preserves_spaces_and_windows_path_spelling() { + let result = edit_command(json!({"snapshot":snapshot(),"confirmed":true,"edits":[ + {"sourceID":"root","values":{"files":{"text":"C:\\Example Files\\one.jar\n\nlib/two.jar\n"}}} + ]})).unwrap(); + assert_eq!( + result["writes"][0]["values"]["files"], + json!(["C:\\Example Files\\one.jar", "lib/two.jar"]) + ); +} + +#[test] +fn unconfirmed_invalid_read_only_and_unbound_edits_are_rejected_atomically() { + for (confirmed, source, field, value, read_only) in [ + (false, "child", "target", "one", false), + (true, "unknown", "target", "one", false), + (true, "child", "unknown", "one", false), + (true, "child", "target", "unknown", false), + (true, "child", "target", "one", true), + ] { + let mut snapshot = snapshot(); + if read_only { + snapshot["sources"][1]["writable"] = json!(false); + } + let result = edit_command(json!({"snapshot":snapshot,"confirmed":confirmed,"edits":[ + {"sourceID":source,"values":{(field):{"choice":value}}} + ]})) + .unwrap(); + assert_eq!(result["status"], "rejected", "{result}"); + assert!(result.get("writes").is_none()); + } +} + +#[test] +fn unsafe_source_names_duplicate_bindings_and_invalid_values_never_reach_ui() { + for path in [ + "../outside", + "/outside", + "C:/outside", + "a/../outside", + "a//b", + "a\\b", + ] { + let mut snapshot = snapshot(); + snapshot["sources"][0]["path"] = json!(path); + let result = state_command(json!({"result":snapshot})).unwrap(); + assert_eq!(result["status"], "rejected", "{path}: {result}"); + } + for kind in ["duplicateID", "duplicatePath", "wrongValue", "unknownGroup"] { + let mut bad = snapshot(); + match kind { + "duplicateID" => bad["sources"][1]["id"] = json!("root"), + "duplicatePath" => bad["sources"][1]["path"] = json!("tool.json"), + "wrongValue" => bad["sources"][0]["fields"][0]["value"] = json!(17), + _ => bad["sources"][0]["group"] = json!("unknown"), + } + assert_eq!( + state_command(json!({"result":bad})).unwrap()["status"], + "rejected", + "{kind}" + ); + } +} + +#[test] +fn staging_receipts_are_bound_to_the_confirmed_source_and_revision() { + let write = json!({"sourceID":"child","path":"child/tool.json","revision":"missing","values":{"target":"one"}}); + let receipt = json!({"format":"litheSettingsSourceEdit","version":0,"sourceID":"child", + "revision":"sha256:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","changed":true}); + assert_eq!( + receipt_command(json!({"write":write,"result":receipt})).unwrap()["status"], + "ok" + ); + for field in ["sourceID", "revision", "format"] { + let mut bad = receipt.clone(); + bad[field] = json!("different"); + assert_eq!( + receipt_command(json!({"write":write,"result":bad})).unwrap()["status"], + "rejected" + ); + } +} + +#[test] +fn inheritance_and_current_effective_values_remain_distinct_from_an_override() { + let mut fixture = snapshot(); + fixture["sources"][1]["fields"][0]["effectiveValue"] = json!("one"); + let result = state_command(json!({"result":fixture})).unwrap(); + assert_eq!( + result["state"]["inputs"]["child"]["target"]["choice"], + "two" + ); + assert_eq!( + result["state"]["inheritedInputs"]["child"]["target"]["choice"], + "one" + ); + assert_eq!( + result["state"]["effectiveDisplays"]["child"]["target"], + json!({"kind":"text","text":"Version 1"}) + ); +} diff --git a/rust/fixtures/plugins/settings-sources.json b/rust/fixtures/plugins/settings-sources.json new file mode 100644 index 00000000..fd94432b --- /dev/null +++ b/rust/fixtures/plugins/settings-sources.json @@ -0,0 +1,95 @@ +{ + "snapshot": { + "format": "litheSettingsSources", + "version": 0, + "title": "Fictional compiler", + "groups": [ + { + "id": "project", + "title": "Project defaults", + "layout": "form" + }, + { + "id": "modules", + "title": "Module overrides", + "layout": "table" + } + ], + "sources": [ + { + "id": "root", + "group": "project", + "title": "Workspace", + "path": "tool.json", + "revision": "missing", + "writable": true, + "fields": [ + { + "id": "target", + "title": "Target", + "kind": "enum", + "value": null, + "effectiveValue": "one", + "effectiveSource": "Tool default", + "description": "Select the format written by the compiler.", + "options": [ + { + "value": "one", + "title": "Version 1" + }, + { + "value": "two", + "title": "Version 2" + } + ] + }, + { + "id": "checks", + "title": "Checks", + "kind": "boolean", + "value": null, + "effectiveValue": true, + "effectiveSource": "Tool default" + }, + { + "id": "files", + "title": "Referenced files", + "kind": "fileList", + "value": [], + "effectiveValue": [], + "effectiveSource": "Workspace" + } + ] + }, + { + "id": "child", + "group": "modules", + "title": "Child module", + "path": "child/tool.json", + "revision": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "writable": true, + "fields": [ + { + "id": "target", + "title": "Target", + "kind": "enum", + "value": "two", + "effectiveValue": "two", + "effectiveSource": "Child module", + "options": [ + { + "value": "one", + "title": "Version 1" + }, + { + "value": "two", + "title": "Version 2" + } + ], + "inheritedValue": "one" + } + ] + } + ] + } +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 700d6f99..e3335653 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -612,6 +612,84 @@ skipping a stored value the declaration no longer accepts. `plugins.declarative.resolveSettings` returns each effective value with its `source` (`project`, `global`, or `default`). +#### Source-backed settings editors + +An action may declare `sourceEditor: {"editFunction":"compiler.prepareSettings"}` and require `sourceSettings: 0` +alongside `settings: 0`. The host invokes the read function only after an +explicit user action; opening its page must not run project wrappers or tools. +The function must **only read** and return the +non-sensitive `litheSettingsSources` snapshot described below. It never returns +source documents. Source-editor actions may use `page: {"compilerID":""}` +to appear under Build, Execution, Deployment; other placements +retain their existing behavior. The editor, tables, pickers, theme, cancellation +and explicit Save/Cancel actions belong to the host. The plugin owns formats, +upstream discovery, module identity, supported choices and effective values. + +A source editor requires the plugin's own backend. Its optional `languageID` +names a declared language server: the host makes it ready before querying. +Its optional `buildSystemID` names a declared build system: each detected instance +contributes `{root,options,tool,model}` from the same resolved native executable, +stored options and upstream model used for Build. Reads receive +`{context:{language,builds:[...]}}`; each `model` contains only the upstream +`projects` projection, without task/run lists or document contents. `language` +is the host interface language. No build selection is inferred from a tool's name. +The read function receives `operation:"readAfterSave"` after publication and +must refresh the upstream tool's native configuration before projecting it. + +Snapshot fields (unknown fields are rejected): + +| Field | Contract | +| --- | --- | +| `format`, `version`, `title` | `litheSettingsSources`, `0`, and a localized nonblank title of at most 256 UTF-8 bytes. The complete snapshot is at most 2 MiB. | +| `groups` | 1–32 ordered `{id,title,layout,rowTitle?}` sections. `layout` is `form` or `table`; table rows use source titles in the first column and their fields as value columns. | +| `sources` | At most 1024 `{id,group,title,path,revision,writable,fields}` bindings. `path` is normalized, workspace-relative, slash-separated, at most 4096 bytes and contains no empty/dot/parent components, drive letters or backslashes. Duplicate IDs or paths are rejected. Native adapters must additionally reject native file aliases and any installation resource. | +| `revision` | `missing`, or `sha256:` followed by 64 lowercase hexadecimal digits covering the exact source bytes. Reading a missing source does not create it. | +| `fields` | 1–32 `{id,title,description?,kind,value,effectiveValue,inheritedValue?,effectiveSource,options?}` records per source. IDs are opaque ASCII identifiers of at most 128 bytes; labels are nonblank and at most 256 bytes, descriptions at most 2048 bytes. Only explicitly non-sensitive fields may be projected. | +| Field values | `value:null` means absent/inherited. `effectiveValue` comes from the upstream tool and may also be null if there is no value. `inheritedValue` is the upstream value after removing a local override; omit it or use null when unknown. `effectiveSource` is a localized origin label of at most 1024 bytes. | +| Field kinds | `enum` with 1–64 distinct `{value,title}` options; `boolean`; `text` up to 8192 bytes; `stringList` or `fileList` with at most 256 nonblank strings, each at most 4096 bytes. Non-enumeration fields omit options. `fileList` adds the host's file picker; list editing uses one item per line, preserving spaces and platform path spelling. | + +No secret/password field, arbitrary script, CSS or host action is accepted. +All plugin-provided labels and choices use the current interface language. +Raw source content, credentials and unrelated configuration stay private to +the plugin and native adapter; they must not appear in RPC, normal controls, +model inputs or logs. The host presents inherited values without creating an +override, maintains drafts and displays each confirmed target path. Core +`plugins.settings.sourceState` supplies `inputs`, `inheritedInputs`, ordered +`layout`, native I/O `limits`, and `effectiveDisplays`. The latter describes +actual values differing from explicit raw values as `unknown`, `text`, +`boolean`, or list `count`; the host localizes these presentation hints. + +On explicit Save the host uses `plugins.settings.sourceEdit` to derive only +changed raw fields. It captures each target with a bounded native reader, +verifies the snapshot revision and current workspace/package ownership, and +creates a private **already existing empty** staging file. It invokes the +distinct `sourceEditor.editFunction` with +`{operation:"editSource",sourceID,revision,values,outputFile}`. `values` maps +opaque field IDs to raw JSON values; null removes just that override. +The function rechecks the source revision, uses its upstream/mature reader +and writer, preserves unrelated fields/comments/secrets, and writes only to +the supplied existing staging file without CREATE or following symlinks. +It does not write the original source. Cancellation cannot recreate staging. + +The reply is exactly +`{format:"litheSettingsSourceEdit",version:0,sourceID,revision,changed}`. +`plugins.settings.sourceReceipt` binds it to the confirmed source. The native +adapter checks the staged bytes' SHA-256 and uses conditional atomic +publication preserving permissions and native metadata. A no-op never creates +a source. Multiple source changes are all prepared and verified before the +first publication; failures retain drafts and report any partial publication. +Publication must still own the workspace, enabled package version and editor +read baseline. After saving, invalidate affected tool facts and invoke the +read function again; report success only after each published digest appears +in the new snapshot. Missing sources and cancel are normal outcomes; all +other failures use the existing action/SDK logging path. Staging is private, +bounded, never reusable across worktrees, and removed on every terminal path. + +Invalid forms, edits or receipts return `plugin.settings.invalidSourceEditor`; +unknown or revoked actions retain their existing errors. These editors are +local-workspace operations; remote workspaces are not supported in version 0. +Fixture: [`settings-sources.json`](../../../../rust/fixtures/plugins/settings-sources.json). + #### Translations A package may translate its setting text with `l10n/.json` files diff --git a/shared/plugins/contract/v1/fixtures/settings/source-editor.plugin.json b/shared/plugins/contract/v1/fixtures/settings/source-editor.plugin.json new file mode 100644 index 00000000..ef199015 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/settings/source-editor.plugin.json @@ -0,0 +1,16 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.test.source-settings", + "displayName": "Fictional compiler settings", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { "backend": 0, "languages": 0, "settings": 0, "sourceSettings": 0 }, + "vendor": { "id": "org.example", "displayName": "Fixture publisher", "signatureRequirement": "publisherPackage" }, + "permissions": ["backend.launch", "workspace.metadata"], + "languages": [{ "id": "fictional", "displayName": "Fictional", "fileExtensions": ["fictional"] }], + "backend": { "launch": { "kind": "packaged", "path": "bin/fixture" } }, + "settingActions": [{ + "id": "compiler", "title": "Compiler settings", "description": "Read and edit the tool's native workspace files.", + "function": "compiler.settings", "sourceEditor": {"editFunction":"compiler.prepareSettings"}, "page": { "compilerID": "fictional" } + }] +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 4b00c597..84a15dd0 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -40,6 +40,7 @@ "packageTrust": { "description": "Required exactly when vendor.bundledSignatureRequirement is present.", "enum": [0] }, "projectGenerators": { "description": "Entries of the New Project window: fields, requirements, and steps, with tool fields that pick tool installations.", "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.", "enum": [0] }, "toolDefinitions": { "enum": [0] }, "toolchainProviders": { "enum": [0] }, "keymapImportProviders": { "enum": [0] }, @@ -1408,7 +1409,8 @@ "maxProperties": 1, "properties": { "languageID": { "$ref": "#/$defs/settingToken" }, - "buildSystemID": { "$ref": "#/$defs/settingToken" } + "buildSystemID": { "$ref": "#/$defs/settingToken" }, + "compilerID": { "$ref": "#/$defs/settingToken" } } }, "settingAction": { @@ -1423,7 +1425,8 @@ "page": { "$ref": "#/$defs/settingPage" }, "section": { "type": "string", "minLength": 1, "maxLength": 120 }, "function": { "description": "Plugin function ID: dot-separated lowerCamelCase segments.", "type": "string", "maxLength": 128, "pattern": "^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])" }, - "confirm": { "description": "Ask before invoking, for actions that discard state.", "type": "boolean" } + "confirm": { "description": "Ask before invoking, for actions that discard state.", "type": "boolean" }, + "sourceEditor": { "description": "Read a non-sensitive native-source editor; requires sourceSettings 0. Only explicit Save invokes editFunction for private staging.", "type": "object", "additionalProperties": false, "required": ["editFunction"], "properties": { "editFunction": { "type":"string", "pattern":"^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])", "maxLength":128 }, "buildSystemID": {"type":"string","minLength":1,"maxLength":128}, "languageID": {"type":"string","minLength":1,"maxLength":128} } } } }, "fileNameList": { diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 9c185431..cda71248 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -4,9 +4,9 @@ ## 中文 -本页把插件会碰到的所有版本号放在一起:`pluginAPIVersion`、清单格式、18 个能力、进程协议和文档格式。**它们现在的版本全部是 `0`。** 规范以 [`contract/v1/README.md`](../contract/v1/README.md) 的 [Versioning](../contract/v1/README.md#versioning)、[Capabilities](../contract/v1/README.md#capabilities)、[Host capabilities](../contract/v1/README.md#host-capabilities) 和 [Publishing](../contract/v1/README.md#publishing) 为准;本页与契约不一致时以契约为准,并请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 +本页把插件会碰到的所有版本号放在一起:`pluginAPIVersion`、清单格式、各项能力、进程协议和文档格式。**它们现在的版本全部是 `0`。** 规范以 [`contract/v1/README.md`](../contract/v1/README.md) 的 [Versioning](../contract/v1/README.md#versioning)、[Capabilities](../contract/v1/README.md#capabilities)、[Host capabilities](../contract/v1/README.md#host-capabilities) 和 [Publishing](../contract/v1/README.md#publishing) 为准;本页与契约不一致时以契约为准,并请到 [Lithe-core-rust 的 Issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues) 反馈。 -Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs) 的 `SUPPORTED_CAPABILITIES`,[`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs) 的 `SUPPORTED_PLUGIN_API_VERSIONS`);Lithe 桌面端列以桌面端的[声明与说明](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go)为准。Core 能校验不等于宿主能运行:桌面端声明了 12 个能力,另外 6 个没有声明,需要它们的插件不会被提供安装。 +Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs) 的 `SUPPORTED_CAPABILITIES`,[`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs) 的 `SUPPORTED_PLUGIN_API_VERSIONS`);Lithe 桌面端列以桌面端的[声明与说明](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go)为准。Core 能校验不等于宿主能运行:宿主未声明的能力不会提供给插件,市场按实际声明筛选版本。 ### 四类版本号 @@ -45,6 +45,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `languageServers` `0` | `languageServers[]`(启动字段按[启动进程](../contract/v1/README.md#process-start)),包括[`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration)和[插件自有服务器的会话字段](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [语言](domains/languages.md)、[Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`:用声明的命令运行和发现测试 | ✅ | 未声明 | [语言](domains/languages.md)、[Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` 与 `settingActions[]`,含[放置位置、作用域、生效方式、页面按钮](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [插件设置](domains/settings.md)、[Plugin settings](../contract/v1/README.md#plugin-settings) | +| `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui):文本、[包内网页](../contract/v1/README.md#web-content)和[原生控件](../contract/v1/README.md#host-rendered-native-content)的工具窗口、命令,以及[不打开工具窗口的后端命令](../contract/v1/README.md#backend-only-commands) | ✅ | ✅¹ | [界面](domains/ui.md) | | `buildSystems` `0` | 不带 `provider` 的 [`buildSystems[]`](../contract/v1/README.md#build-systems):检测、选项、项目模型、任务、运行入口、测试、诊断、依赖、同步和[声明式项目准备](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [声明式构建系统](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | @@ -108,9 +109,9 @@ Node.js SDK 0.5.0、Java SDK 0.5.0 和 Rust SDK 0.4.0 说的是版本 `0` 的协 ## English -This page puts every version number a plugin meets in one place: `pluginAPIVersion`, the manifest format, the 18 capabilities, the process protocols, and the document formats. **Every one of them is `0`.** The normative text is [Versioning](../contract/v1/README.md#versioning), [Capabilities](../contract/v1/README.md#capabilities), [Host capabilities](../contract/v1/README.md#host-capabilities), and [Publishing](../contract/v1/README.md#publishing) in [`contract/v1/README.md`](../contract/v1/README.md). Where this page disagrees with the contract, the contract wins; please report it in the [Lithe-core-rust issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). +This page puts every version number a plugin meets in one place: `pluginAPIVersion`, the manifest format, the capabilities, the process protocols, and the document formats. **Every one of them is `0`.** The normative text is [Versioning](../contract/v1/README.md#versioning), [Capabilities](../contract/v1/README.md#capabilities), [Host capabilities](../contract/v1/README.md#host-capabilities), and [Publishing](../contract/v1/README.md#publishing) in [`contract/v1/README.md`](../contract/v1/README.md). Where this page disagrees with the contract, the contract wins; please report it in the [Lithe-core-rust issues](https://github.com/Lithe-IDEA/Lithe-core-rust/issues). -The Core column follows the Core source on this repository's `main` (`SUPPORTED_CAPABILITIES` in [`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs), `SUPPORTED_PLUGIN_API_VERSIONS` in [`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs)); the Lithe desktop column follows the desktop client's [declarations and notes](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go). Validating a capability is not running it: the desktop client declares 12 capabilities and does not declare the other 6, so a plugin that needs one of those is not offered for installation. +The Core column follows the Core source on this repository's `main` (`SUPPORTED_CAPABILITIES` in [`capabilities.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-model/src/capabilities.rs), `SUPPORTED_PLUGIN_API_VERSIONS` in [`plugin-manifest/src/lib.rs`](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/main/rust/crates/plugin-manifest/src/lib.rs)); the Lithe desktop column follows the desktop client's [declarations and notes](https://github.com/1lck/Lithe-IDEA/blob/preview/desktop/internal/pluginhost/pluginhost.go). Validating a capability is not running it: the marketplace offers only versions whose requirements the host declares. ### Four kinds of version @@ -149,6 +150,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `languageServers` `0` | `languageServers[]` (launch fields as in [Process start](../contract/v1/README.md#process-start)), including [`workspaceConfiguration`](../contract/v1/README.md#workspace-configuration) and the [session fields for a plugin's own server](../contract/v1/README.md#plugin-owned-sessions) | ✅ | ✅¹ | [Languages](domains/languages.md), [Language servers](../contract/v1/README.md#language-servers) | | `executionProviders` `0` | `executionProviders[]`: run and discover tests through the declared commands | ✅ | Not declared | [Languages](domains/languages.md), [Execution providers](../contract/v1/README.md#execution-providers) | | `settings` `0` | `settings[]` and `settingActions[]`, with [placement, scope, effect, and page buttons](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅ | [Plugin settings](domains/settings.md), [Plugin settings](../contract/v1/README.md#plugin-settings) | +| `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | 待宿主接入 / Pending host integration | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui): text, [web](../contract/v1/README.md#web-content), and [native](../contract/v1/README.md#host-rendered-native-content) tool windows, commands, and [backend-only commands](../contract/v1/README.md#backend-only-commands) without a tool window | ✅ | ✅¹ | [UI](domains/ui.md) | | `buildSystems` `0` | [`buildSystems[]`](../contract/v1/README.md#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [Declarative build systems](domains/build-systems.md) | | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | diff --git a/shared/plugins/reference/domains/settings.md b/shared/plugins/reference/domains/settings.md index 06414749..949576bc 100644 --- a/shared/plugins/reference/domains/settings.md +++ b/shared/plugins/reference/domains/settings.md @@ -267,3 +267,13 @@ Settings rejections are in [`manifest/invalid-manifests.json`](../../contract/v1 - [Building an LSP plugin end to end](../../guides/lsp-plugin-lifecycle.md) - [Build, run, and test for language plugins](../../guides/build-tool-integration.md) + +## Native source editors / 真实配置来源 + +`sourceSettings: 0` adds native forms and per-module tables backed by actual +tool configuration. See the normative [source editor contract](../../contract/v1/README.md#source-backed-settings-editors) +for `sourceEditor`, compiler placement, upstream context, inheritance, limits, +staging and conflict handling. The plugin must translate its labels itself. +Read actions explain that they may execute the project tool or wrapper; opening +a page does not authorize that execution. Only explicit Save stages changes, +and the host publishes them conditionally before refreshing upstream facts. From 337ec2a371666eac823fe20fd7ca163868643edf Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 07:50:12 -0800 Subject: [PATCH 2/3] docs(settings): register protocol and update runtime plan goldens --- .../v1/fixtures/build-systems/build-plans.json | 16 ++++++++++++---- shared/plugins/reference/protocol-changelog.md | 6 +++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json b/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json index 1eedda79..5a39ff65 100644 --- a/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json +++ b/shared/plugins/contract/v1/fixtures/build-systems/build-plans.json @@ -488,12 +488,18 @@ "displayName": null, "hostManaged": true, "minimumVersion": "1.21", - "executables": [], + "executables": [ + { + "kind": "runtime", + "runtime": "go" + } + ], "version": { "arguments": [ "version" ] - } + }, + "pathVariable": "LITHE_GO_PATH" } ], "version": null, @@ -862,7 +868,8 @@ "root": "build-logic" } ], - "version": null + "version": null, + "pathVariable": "LITHE_JAVA_PATH" } ], "version": { @@ -923,7 +930,8 @@ "root": "." } ], - "version": null + "version": null, + "pathVariable": "LITHE_JAVA_PATH" } ], "version": { diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 0d20e4d7..6fe8d7e1 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -28,9 +28,11 @@ | `plugins.editorActions.decode` 请求的 `version` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | 插件网页桥 `window.lithe.version` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `litheSettingsSources`、`litheSettingsSourceEdit` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | + ### 能力版本(`requires`) -18 个能力都从版本 `0` 开始。 +各项能力都从版本 `0` 开始。 | 能力 | 版本 | 日期 | PR | | --- | --- | --- | --- | @@ -48,6 +50,7 @@ | `packageTrust` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `pluginFunctions` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | `projectGenerators` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| `sourceSettings` | 0 | 2026-11-15 | [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | | `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) | | `toolchainProviders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | @@ -134,6 +137,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | +| [#57](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/57) | [@1lck](https://github.com/1lck) | API-19、API-29 | **`sourceSettings` 0**;`buildSystems` 0 内补充 | 原生配置来源编辑:同插件独立读取/暂存函数、编译器页、上游语言/构建上下文、实际值与移除覆盖后的继承值、严格限额、显式保存及 SHA-256 收据。Core 新增 sourceState/sourceEdit/sourceReceipt 命令,原文不跨协议。构建运行时计划返回明确候选与 pathVariable,由原生宿主先验证运行时再启动构建工具;未新增宿主 RPC 方法或通知。 | | [#56](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/56) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.cwd` 除了 `target.workingDirectory`,也可以绑到 `target.directory`(源文件所在目录)。调试引擎在 launch 参数缺 `cwd` 时会填工作区根目录;Go 插件绑定 `cwd` ← `target.directory` 后,被调程序在包目录运行,按包目录写的相对路径能读到。其他值以 `plugin.manifest.invalid`(字段 `targetBindings.cwd`)拒绝;目标路径是裸文件名、取不出目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。只是可选取值,不需要新能力版本。 | | [#55](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/55) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings` 新增 `adapterArguments`:最多 8 个只有这个适配器才有的 DAP 参数,`{"<参数路径>": "<事实>"}`,路径和 `connection` 的目标一样用点分隔、最多 4 段,事实只能是 `target.path`、`target.directory` 或 `target.workingDirectory`,和其他绑定一样只在没有值时填入。`env.<变量名>` 往环境里加一个变量,`arguments` 和 `env` 绑定给的变量都保留。例如 Delve 在 `dlvCwd` 里编译程序,不在宿主给它的工作目录(工作区根目录)里编译,`go build` 又从 `PWD` 读当前目录;Go 插件绑定 `dlvCwd` 和 `env.PWD` ← `target.directory` 后,工作区根目录没有 `go.mod`、一个工作区放了多个模块、路径经过符号链接时都能调试。路径不能从 `program`、`processId`、`cwd`、`args`、`env` 本身、`noDebug`、`__` 开头的名字开始,路径之间、路径和 `connection` 的目标之间不能重叠,也不能落在 `arguments` 已有的值上或它的下面,违反时以 `plugin.manifest.invalid`(字段 `targetBindings.adapterArguments[.<参数路径>]`)拒绝;目标缺少事实时以 `debug.target.invalid`(字段 `target.path` 或 `target.workingDirectory`)拒绝。只是可选字段,不需要新能力版本。 | | [#53](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/53) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-23 | **`commandInstallers` 0** | 新能力 `commandInstallers` 和权限 `commands.install`:清单顶层 `commandInstallers[]` 声明怎样用插件已依赖的工具(`requiresTools`)安装 `systemCommand` 启动缺的裸命令,例如用 `go install` 装 `dlv`。每个安装声明 `commands`、`tool`、`minimumVersion?`、字面量 `arguments`、`mayUseNetwork`、`timeoutSeconds?`(1–3600,默认 600)和至少一个目标:`managed` 装进宿主为插件管理的目录,参数或环境变量必须用唯一的模板变量 `${installDirectory}`,`commandDirectory` 指命令所在的子目录;`toolDefault` 装到工具默认位置,`directory` 最多 4 个探针,按顺序运行同一工具,从输出读目录(`pathList`、`append`)。新增宿主命令 `plugins.commandInstallers.requirements`、`plan`、`defaultDirectory` 和错误码 `plugin.commandInstaller.unknown`、`targetUndeclared`、`directoryInvalid`、`probeOutputsInvalid`(Core),以及宿主报告的 `plugin.command.missing`、`plugin.commandInstaller.failed`、`timedOut`、`commandsMissing`。安装声明进入安装审查(`kind: "commandInstaller"`)。宿主只在用户确认命令行、网络和目标后安装,每次安装用 `diagnostics.recordPluginOperation` 记一条 `commandInstaller/install`(命令执行生命周期,安装后命令仍缺记 `decode`)。 | From 3d1e0819d0531bde70aa86014f39bc9edaec327d Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Sun, 15 Nov 2026 07:56:10 -0800 Subject: [PATCH 3/3] fix(settings): expose inherited boolean and list values explicitly --- .../plugin-model/src/settings/sources.rs | 40 +++++++++++++------ .../src/settings/sources/tests.rs | 14 ++++++- shared/plugins/contract/v1/README.md | 4 +- 3 files changed, 43 insertions(+), 15 deletions(-) diff --git a/rust/crates/plugin-model/src/settings/sources.rs b/rust/crates/plugin-model/src/settings/sources.rs index 9dc51210..2e5be805 100644 --- a/rust/crates/plugin-model/src/settings/sources.rs +++ b/rust/crates/plugin-model/src/settings/sources.rs @@ -396,18 +396,34 @@ pub fn state_command(payload: Value) -> Result { ) }) .collect(); - let effective_displays:BTreeMap<_,BTreeMap<_,Value>>=snapshot.sources.iter().map(|source|{ - (source.id.clone(),source.fields.iter().filter(|field|!field.value.is_null()&&field.value!=field.effective_value).map(|field|{ - let value=&field.effective_value; - let display=if value.is_null(){json!({"kind":"unknown"})}else{match field.kind.as_str(){ - "enum"=>json!({"kind":"text","text":field.options.iter().find(|option|Some(option.value.as_str())==value.as_str()).map(|option|option.title.as_str()).unwrap_or_default()}), - "boolean"=>json!({"kind":"boolean","on":value.as_bool().unwrap_or_default()}), - "fileList"|"stringList"=>json!({"kind":"list","count":value.as_array().map_or(0,Vec::len)}), - _=>json!({"kind":"text","text":value.as_str().unwrap_or_default()}), - }}; - (field.id.clone(),display) - }).collect()) - }).collect(); + let effective_displays: BTreeMap<_, BTreeMap<_, Value>> = snapshot + .sources + .iter() + .map(|source| { + let displays = source.fields.iter().filter(|field| { + (field.value.is_null() && field.kind != "enum") + || (!field.value.is_null() && field.value != field.effective_value) + }).map(|field| { + let value = &field.effective_value; + let mut display = if value.is_null() { + json!({"kind":"unknown"}) + } else { + match field.kind.as_str() { + "enum" => { + let title = field.options.iter().find(|option| Some(option.value.as_str()) == value.as_str()) + .map(|option| option.title.as_str()).unwrap_or_default(); + json!({"kind":"text","text":title}) + } + "boolean" => json!({"kind":"boolean","on":value.as_bool().unwrap_or_default()}), + "fileList" | "stringList" => json!({"kind":"list","count":value.as_array().map_or(0, Vec::len)}), + _ => json!({"kind":"text","text":value.as_str().unwrap_or_default()}), + } + }; + display["inherited"] = json!(field.value.is_null()); + (field.id.clone(), display) + }).collect(); + (source.id.clone(), displays) + }).collect(); let layout: Vec<_> = snapshot .groups .iter() diff --git a/rust/crates/plugin-model/src/settings/sources/tests.rs b/rust/crates/plugin-model/src/settings/sources/tests.rs index 335b5f7e..e9e67790 100644 --- a/rust/crates/plugin-model/src/settings/sources/tests.rs +++ b/rust/crates/plugin-model/src/settings/sources/tests.rs @@ -149,6 +149,18 @@ fn inheritance_and_current_effective_values_remain_distinct_from_an_override() { ); assert_eq!( result["state"]["effectiveDisplays"]["child"]["target"], - json!({"kind":"text","text":"Version 1"}) + json!({"kind":"text","text":"Version 1","inherited":false}) + ); +} + +#[test] +fn absent_boolean_values_expose_inheritance_and_unknown_effective_values() { + let mut fixture = snapshot(); + fixture["sources"][0]["fields"][1]["value"] = Value::Null; + fixture["sources"][0]["fields"][1]["effectiveValue"] = Value::Null; + let result = state_command(json!({"result":fixture})).unwrap(); + assert_eq!( + result["state"]["effectiveDisplays"]["root"]["checks"], + json!({"kind":"unknown","inherited":true}) ); } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index e3335653..e2546e2d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -656,8 +656,8 @@ model inputs or logs. The host presents inherited values without creating an override, maintains drafts and displays each confirmed target path. Core `plugins.settings.sourceState` supplies `inputs`, `inheritedInputs`, ordered `layout`, native I/O `limits`, and `effectiveDisplays`. The latter describes -actual values differing from explicit raw values as `unknown`, `text`, -`boolean`, or list `count`; the host localizes these presentation hints. +inherited non-enum values and actual values differing from explicit raw values as `unknown`, `text`, +`boolean`, or list `count`, with an `inherited` flag; the host localizes these presentation hints. On explicit Save the host uses `plugins.settings.sourceEdit` to derive only changed raw fields. It captures each target with a bounded native reader,