diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 72882654..855e5965 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -630,7 +630,7 @@ or removing a command fails until the table changes in the same commit. | `workspace.resolveEntry` | Name one existing entry below a workspace root without following it | | `workspace.reduceDirectoryAction` | Apply role, custom type, color override, exclusion, clear mark or cancel exclusion to a root's persisted directory rules and return the complete state to persist | | `workspace.relocateDirectoryRules` | Move (or drop, after a delete) the directory rule keys of a renamed, moved or deleted subtree, optionally into another workspace root's rules | -| `workspace.resolveDirectoryPresentation` | Resolve deterministic per-path presentation (icon, color, background tint, tag, source, exclusion) and manual indexing exclusions across user rules, shared rules, glob matches and Git ignores | +| `workspace.resolveDirectoryPresentation` | Resolve deterministic per-path presentation (icon, color, background tint, tag, source, exclusion) and manual indexing exclusions across user rules, shared rules, plugin-contributed types and marks, glob matches and Git ignores | | `workspace.repositories` | Discover deterministic Git repository roots for an opened workspace | | `workspace.recentProjects.reduce` | Apply one history mutation or compute a recent project filter projection | | `workspace.searchIndex.warm` | Build or reuses the workspace search index | @@ -7640,7 +7640,8 @@ and releases only the last holder; window destruction also revokes late registra `{ kind: "deleteCustomType", id }`, and `rules` is the root's persisted `{ marks, includedDirectories, previousRoles, customTypes?, colors? }`. Built-in roles are `plain`, `sources`, `tests`, `resources`, `testResources`, `generated`, `excluded`, `module`, -and `package`; `setRole` also accepts any `custom.*` ID defined in `customTypes`. It returns +and `package`; `setRole` also accepts any `custom.*` ID defined in `customTypes` and any +well-formed `plugin.*` ID, which a plugin may contribute later or never. It returns `{ changed, rules }`; hosts persist `rules` verbatim and skip the write when `changed` is false. Excluding remembers the replaced role in `previousRoles` and canceling a manual exclusion restores it. `workspace.relocateDirectoryRules` takes @@ -7648,10 +7649,20 @@ restores it. `workspace.relocateDirectoryRules` takes keys at or below `source` (including `colors`) leave `rules`, reappear under `destination` (in `target` for a move across workspace roots) and are dropped when there is no destination. `workspace.resolveDirectoryPresentation` takes -`{ rules, sharedRules?, gitExcluded?, caseInsensitive?, paths }` and returns -`{ entries, manualExcludedDirectories }`, merging layers in order `user > shared > glob > vcs` -with ancestor background tint and exclusion inheritance. Base request and response pairs are -pinned by `rust/fixtures/workspace/directory-rules-v1.json`. +`{ rules, sharedRules?, pluginTypes?, pluginMarks?, gitExcluded?, caseInsensitive?, paths? }` +and returns `{ entries, manualExcludedDirectories }`, merging layers in order +`user > shared > plugin > glob > vcs` with ancestor background tint and exclusion inheritance. +`pluginTypes` holds at most 256 `{ pluginId, id, name, tag?, icon, color, tintBg?, tintText?, +inheritBg?, excludeIndexing?, readOnlyHint?, matchGlob? }` entries whose `id` starts with +`plugin.`; `pluginMarks` holds `{ pluginId, path, role, color? }` entries whose `role` is a +built-in role or a `plugin.*` ID. Both are what live plugin sessions registered through +`workspace/setDirectoryTypes` and `workspace/setDirectoryMarks`; Core never persists them. +When two plugins contribute the same type ID or path, the plugin ID that sorts first wins. +Each entry carries `pluginId` when its role or type came from a plugin. `paths` may be omitted +or empty, but not `null`: `manualExcludedDirectories` still lists every explicitly marked +directory whose effective role excludes indexing, and adds glob-matched directories only for +the `paths` given. Request and response pairs, including the plugin layers, are pinned by +`rust/fixtures/workspace/directory-rules-v1.json`. `workspace.planDuplicate` takes `{ name, isDirectory, existing?, caseInsensitive? }` and returns `{ name }`; `workspace.planPaste` takes `{ items: [{ name, isDirectory }], existing?, caseInsensitive? }` diff --git a/rust/crates/core/src/tests/directory_actions.rs b/rust/crates/core/src/tests/directory_actions.rs index 7b9c6ae7..94149aaf 100644 --- a/rust/crates/core/src/tests/directory_actions.rs +++ b/rust/crates/core/src/tests/directory_actions.rs @@ -1,4 +1,5 @@ use crate::execute_json; +use lithe_plugin_rpc::workflow::{check_params, DIRECTORY_TYPE_ICONS}; use serde_json::{json, Value}; fn execute(command: &str, payload: Value) -> Value { @@ -61,6 +62,18 @@ fn relocate_matches_the_shared_fixture() { } } +#[test] +fn resolve_matches_the_shared_fixture() { + for case in fixture()["resolve"].as_array().unwrap() { + let response = execute( + "workspace.resolveDirectoryPresentation", + case["request"].clone(), + ); + assert_eq!(response["ok"], true, "{}: {response}", case["id"]); + assert_eq!(response["data"], case["response"], "{}", case["id"]); + } +} + #[test] fn invalid_requests_are_rejected() { for case in fixture()["invalid"].as_array().unwrap() { @@ -333,3 +346,232 @@ fn custom_icons_can_be_added_referenced_and_deleted_with_fallback() { assert!(deleted["data"]["rules"].get("customIcons").is_none()); assert_eq!(deleted["data"]["rules"]["customTypes"][0]["icon"], "folder"); } + +#[test] +fn plugin_directory_types_and_marks_resolve_with_layer_precedence() { + let empty = json!({"marks": {}, "includedDirectories": [], "previousRoles": {}}); + + // User can manually assign a plugin.* role to a folder. + let user_assigned = execute( + "workspace.reduceDirectoryAction", + json!({ + "path": "manual-plugin", + "action": {"kind": "setRole", "role": "plugin.migrations"}, + "rules": empty + }), + ); + assert_eq!(user_assigned["ok"], true, "{user_assigned}"); + let rules = user_assigned["data"]["rules"].clone(); + + // User also overrides a plugin-excluded folder back to sources. + let user_override = execute( + "workspace.reduceDirectoryAction", + json!({ + "path": "generated/api", + "action": {"kind": "setRole", "role": "sources"}, + "rules": rules + }), + ); + assert_eq!(user_override["ok"], true, "{user_override}"); + let rules = user_override["data"]["rules"].clone(); + + let resolved = execute( + "workspace.resolveDirectoryPresentation", + json!({ + "rules": rules, + "pluginTypes": [ + { + "pluginId": "com.example.sql", + "id": "plugin.migrations", + "name": "SQL Migrations", + "tag": "migrations", + "icon": "database", + "color": "#0d9488", + "tintBg": true, + "inheritBg": true + }, + { + "pluginId": "com.example.gen", + "id": "plugin.cache", + "name": "Build Cache", + "tag": "cache", + "icon": "archive", + "color": "#64748b", + "excludeIndexing": true, + "matchGlob": ".cache/**" + } + ], + "pluginMarks": [ + {"pluginId": "com.example.sql", "path": "db/migrations", "role": "plugin.migrations"}, + {"pluginId": "com.example.gen", "path": "generated/api", "role": "plugin.cache"}, + {"pluginId": "com.example.gen", "path": "vendor/out", "role": "excluded"} + ], + "paths": [ + "db/migrations", + "manual-plugin", + "generated/api", + "vendor/out", + ".cache/v1" + ] + }), + ); + assert_eq!(resolved["ok"], true, "{resolved}"); + let entries = &resolved["data"]["entries"]; + + // 1. Plugin mark resolves with plugin source and pluginId. + assert_eq!(entries["db/migrations"]["role"], "plugin.migrations"); + assert_eq!(entries["db/migrations"]["source"], "plugin"); + assert_eq!(entries["db/migrations"]["pluginId"], "com.example.sql"); + assert_eq!(entries["db/migrations"]["tag"], "migrations"); + + // 2. User manually assigning plugin.migrations resolves with user source and plugin styling. + assert_eq!(entries["manual-plugin"]["role"], "plugin.migrations"); + assert_eq!(entries["manual-plugin"]["source"], "user"); + assert_eq!(entries["manual-plugin"]["icon"], "database"); + + // 3. User override beats plugin-excluding mark and removes it from manualExcludedDirectories. + assert_eq!(entries["generated/api"]["role"], "sources"); + assert_eq!(entries["generated/api"]["source"], "user"); + assert_eq!(entries["generated/api"]["excluded"], false); + + // 4. Plugin-marked excluded directory & plugin glob-excluded directory appear in manualExcludedDirectories. + let excluded = resolved["data"]["manualExcludedDirectories"] + .as_array() + .unwrap(); + assert!(excluded.contains(&json!("vendor/out"))); + assert!(excluded.contains(&json!(".cache/v1"))); + assert!(!excluded.contains(&json!("generated/api"))); +} + +/// Whatever `workspace/setDirectoryTypes` and `workspace/setDirectoryMarks` accept from a +/// plugin must also resolve, so one plugin's registration can never make the host's +/// presentation request fail for every other layer. +#[test] +fn plugin_contributions_the_rpc_accepts_always_resolve() { + let context = json!({"contextID": "workspace", "generation": 1}); + let base = + json!({"id": "plugin.sample", "name": "Sample", "icon": "folder", "color": "#0d9488"}); + let long_id = format!("plugin.{}", "a".repeat(57)); + let too_long_id = format!("plugin.{}", "a".repeat(58)); + let mut types = Vec::new(); + let mut vary = |field: &str, values: Vec| { + for value in values { + let mut item = base.clone(); + item[field] = value; + types.push(item); + } + }; + let icons = DIRECTORY_TYPE_ICONS + .iter() + .copied() + .chain(["module", "package", "bogus", ""]); + vary("icon", icons.map(|icon| json!(icon)).collect()); + vary( + "name", + ["Sample", " Padded ", " ", "", "\t"] + .map(|name| json!(name)) + .into_iter() + .chain([json!("n".repeat(64)), json!("n".repeat(65))]) + .collect(), + ); + vary( + "color", + ["#0D9488", "#0d948", "0d9488", " #0d9488", "#0d9488 "] + .map(|color| json!(color)) + .into(), + ); + vary( + "tag", + vec![json!(""), json!("t".repeat(24)), json!("t".repeat(25))], + ); + vary( + "matchGlob", + vec![ + json!("gen/**"), + json!("g".repeat(256)), + json!("g".repeat(257)), + ], + ); + vary( + "id", + vec![ + json!("plugin.a-b_c.d"), + json!("plugin."), + json!("plugin.A"), + json!("custom.a"), + json!(long_id), + json!(too_long_id), + ], + ); + let mut accepted = 0; + for item in types { + let params = json!({"context": context, "types": [item]}); + if check_params("lithe/host/workspace/setDirectoryTypes", ¶ms).is_err() { + continue; + } + accepted += 1; + let mut contributed = item.clone(); + contributed["pluginId"] = json!("com.example.sample"); + let response = execute( + "workspace.resolveDirectoryPresentation", + json!({"rules": {}, "pluginTypes": [contributed], "paths": ["x"]}), + ); + assert_eq!(response["ok"], true, "{item}: {response}"); + } + assert!(accepted > DIRECTORY_TYPE_ICONS.len(), "{accepted}"); + + let mut marks = Vec::new(); + let paths = [ + "src", + "src/main", + "a b", + "目录/子目录", + "a:b", + "a/./b", + ".", + "a//b", + ]; + for path in paths + .map(|path| json!(path)) + .into_iter() + .chain([json!("x".repeat(1024))]) + { + marks.push(json!({"path": path, "role": "sources"})); + } + let roles = [ + "plain", + "sources", + "tests", + "resources", + "testResources", + "generated", + "excluded", + "module", + "package", + "plugin.sample", + "custom.sample", + "bogus", + ]; + for role in roles { + marks.push(json!({"path": "x", "role": role})); + } + for color in ["#ABCDEF", "#abc", "red"] { + marks.push(json!({"path": "x", "role": "sources", "color": color})); + } + let mut accepted = 0; + for mark in marks { + let params = json!({"context": context, "marks": [mark]}); + if check_params("lithe/host/workspace/setDirectoryMarks", ¶ms).is_err() { + continue; + } + accepted += 1; + let mut contributed = mark.clone(); + contributed["pluginId"] = json!("com.example.sample"); + let response = execute( + "workspace.resolveDirectoryPresentation", + json!({"rules": {}, "pluginMarks": [contributed], "paths": ["x"]}), + ); + assert_eq!(response["ok"], true, "{mark}: {response}"); + } + assert!(accepted > 10, "{accepted}"); +} diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index e5e801f2..b2c19ef3 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -222,6 +222,18 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: Some("workspace.reveal"), params: HostParams::Workflow, }, + HostMethod { + method: "lithe/host/workspace/setDirectoryTypes", + service: "workspace", + permission: Some("workspace.directoryMarks"), + params: HostParams::Workflow, + }, + HostMethod { + method: "lithe/host/workspace/setDirectoryMarks", + service: "workspace", + permission: Some("workspace.directoryMarks"), + params: HostParams::Workflow, + }, HostMethod { method: "lithe/host/network/request", service: "network", diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 239abcb3..275d64a0 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -147,6 +147,7 @@ pub const HOST_PERMISSIONS: &[&str] = &[ "clipboard.read", "clipboard.write", "workspace.reveal", + "workspace.directoryMarks", "network.request", "workspace.files.read", "workspace.files.watch", diff --git a/rust/crates/plugin-rpc/src/workflow.rs b/rust/crates/plugin-rpc/src/workflow.rs index fd9e8366..0d61f137 100644 --- a/rust/crates/plugin-rpc/src/workflow.rs +++ b/rust/crates/plugin-rpc/src/workflow.rs @@ -21,6 +21,28 @@ pub const OUTPUT_BYTES: usize = 512 * 1024; pub const OUTPUT_LINE_BYTES: usize = 16 * 1024; /// Maximum channels, progress handles and status items per backend session (shared with other limited host registrations). pub const RESOURCE_LIMIT: usize = 16; +/// Maximum directory types one `workspace/setDirectoryTypes` call may register. +pub const DIRECTORY_TYPES_LIMIT: usize = 32; +/// Maximum directory marks one `workspace/setDirectoryMarks` call may register. +pub const DIRECTORY_MARKS_LIMIT: usize = 500; +/// Maximum UTF-8 bytes of one directory mark path. +pub const DIRECTORY_MARK_PATH_BYTES: usize = 1024; +/// Icon names a plugin directory type may use. They match the icons +/// `workspace.resolveDirectoryPresentation` accepts, so a type the host +/// stores never makes the resolver refuse the whole request. +pub const DIRECTORY_TYPE_ICONS: [&str; 11] = [ + "folder", + "sources", + "tests", + "resources", + "generated", + "excluded", + "star", + "book", + "archive", + "database", + "gear", +]; fn invalid() -> HostRequestRefusal { HostRequestRefusal { @@ -124,6 +146,8 @@ pub fn check_params(method: &str, params: &Value) -> Result<(), HostRequestRefus "clipboard/readText" => &["context"], "clipboard/writeText" => &["context", "text"], "workspace/reveal" => &["context", "resource"], + "workspace/setDirectoryTypes" => &["context", "types"], + "workspace/setDirectoryMarks" => &["context", "marks"], "browser/openExternal" => &["context", "url", "resource", "unsaved"], "network/request" => &[ "context", @@ -252,6 +276,8 @@ pub fn check_params(method: &str, params: &Value) -> Result<(), HostRequestRefus p.contains_key("text") && text(p, "text", TEXT_BYTES, false, false) } "workspace/reveal" => p.get("resource").is_some_and(resource), + "workspace/setDirectoryTypes" => directory_types_valid(p), + "workspace/setDirectoryMarks" => directory_marks_valid(p), "browser/openExternal" => match (p.get("url"), p.get("resource")) { (Some(Value::String(url)), None) => !p.contains_key("unsaved") && http_address(url), (None, Some(value)) => { @@ -272,6 +298,123 @@ pub fn check_params(method: &str, params: &Value) -> Result<(), HostRequestRefus } } +fn directory_types_valid(p: &Map) -> bool { + let Some(items) = p.get("types").and_then(Value::as_array) else { + return false; + }; + if items.len() > DIRECTORY_TYPES_LIMIT { + return false; + } + let mut ids = BTreeSet::new(); + items.iter().all(|item| { + let Ok(obj) = object( + item, + &[ + "id", + "name", + "tag", + "icon", + "color", + "tintBg", + "tintText", + "inheritBg", + "excludeIndexing", + "readOnlyHint", + "matchGlob", + ], + ) else { + return false; + }; + let valid_id = obj + .get("id") + .and_then(Value::as_str) + .is_some_and(|id| is_plugin_directory_type_id(id) && ids.insert(id.to_owned())); + let valid_icon = obj + .get("icon") + .and_then(Value::as_str) + .is_some_and(|icon| DIRECTORY_TYPE_ICONS.contains(&icon)); + let valid_name = obj + .get("name") + .and_then(Value::as_str) + .is_some_and(|name| !name.trim().is_empty()); + let valid_color = obj + .get("color") + .and_then(Value::as_str) + .is_some_and(is_hex_color); + valid_id + && valid_name + && text(obj, "name", 64, true, true) + && text(obj, "tag", 24, false, true) + && valid_icon + && valid_color + && flag(obj, "tintBg") + && flag(obj, "tintText") + && flag(obj, "inheritBg") + && flag(obj, "excludeIndexing") + && flag(obj, "readOnlyHint") + && text(obj, "matchGlob", 256, false, true) + }) +} + +fn directory_marks_valid(p: &Map) -> bool { + let Some(items) = p.get("marks").and_then(Value::as_array) else { + return false; + }; + if items.len() > DIRECTORY_MARKS_LIMIT { + return false; + } + let mut paths = BTreeSet::new(); + items.iter().all(|item| { + let Ok(obj) = object(item, &["path", "role", "color"]) else { + return false; + }; + let valid_path = obj.get("path").and_then(Value::as_str).is_some_and(|raw| { + !raw.is_empty() + && raw.len() <= DIRECTORY_MARK_PATH_BYTES + && !raw.starts_with('/') + && !raw.ends_with('/') + && !raw.contains(['\\', ':']) + && !raw.chars().any(char::is_control) + && raw + .split('/') + .all(|seg| !seg.is_empty() && seg != "." && seg != "..") + && paths.insert(raw.to_owned()) + }); + let valid_role = obj.get("role").and_then(Value::as_str).is_some_and(|role| { + matches!( + role, + "plain" + | "sources" + | "tests" + | "resources" + | "testResources" + | "generated" + | "excluded" + ) || is_plugin_directory_type_id(role) + }); + let valid_color = obj + .get("color") + .is_none_or(|v| v.as_str().is_some_and(is_hex_color)); + valid_path && valid_role && valid_color + }) +} + +fn is_plugin_directory_type_id(id: &str) -> bool { + let Some(rest) = id.strip_prefix("plugin.") else { + return false; + }; + !rest.is_empty() + && id.len() <= 64 + && rest.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'.' | b'_' | b'-') + }) +} + +fn is_hex_color(raw: &str) -> bool { + let bytes = raw.as_bytes(); + bytes.len() == 7 && bytes[0] == b'#' && bytes[1..].iter().all(u8::is_ascii_hexdigit) +} + fn http_address(address: &str) -> bool { address.len() <= 8192 && !address.chars().any(char::is_control) @@ -687,6 +830,74 @@ mod tests { assert!(command(status.clone()).is_err()); status["manifest"]["ui"]["commands"][0]["id"] = json!("run"); assert!(command(status).is_ok()); + + let valid_types = json!({ + "operation": "prepare", + "method": "workspace/setDirectoryTypes", + "params": { + "context": context, + "types": [{ + "id": "plugin.migrations", + "name": "SQL Migrations", + "tag": "migrations", + "icon": "database", + "color": "#0d9488", + "tintBg": true + }] + } + }); + assert!(command(valid_types).is_ok()); + + let invalid_type_id = json!({ + "operation": "prepare", + "method": "workspace/setDirectoryTypes", + "params": { + "context": context, + "types": [{ + "id": "custom.notallowed", + "name": "Bad", + "icon": "folder", + "color": "#0d9488" + }] + } + }); + assert!(command(invalid_type_id).is_err()); + + let valid_marks = json!({ + "operation": "prepare", + "method": "workspace/setDirectoryMarks", + "params": { + "context": context, + "marks": [ + {"path": "db/migrations", "role": "plugin.migrations"}, + {"path": "src/main", "role": "sources", "color": "#3b82f6"} + ] + } + }); + assert!(command(valid_marks).is_ok()); + + let invalid_mark_path = json!({ + "operation": "prepare", + "method": "workspace/setDirectoryMarks", + "params": { + "context": context, + "marks": [{"path": "../escape", "role": "sources"}] + } + }); + assert!(command(invalid_mark_path).is_err()); + + // The resolver draws `module` and `package` as plain folders and refuses blank + // names and Windows drive separators, so the host must never store them. + for (field, value) in [("icon", json!("module")), ("name", json!(" "))] { + let mut item = json!({"id":"plugin.x","name":"X","icon":"folder","color":"#0d9488"}); + item[field] = value; + let request = json!({"operation":"prepare","method":"workspace/setDirectoryTypes", + "params":{"context":context,"types":[item]}}); + assert!(command(request).is_err(), "{field}"); + } + let drive_path = json!({"operation":"prepare","method":"workspace/setDirectoryMarks", + "params":{"context":context,"marks":[{"path":"c:/x","role":"sources"}]}}); + assert!(command(drive_path).is_err()); } #[test] diff --git a/rust/crates/project/src/directory_actions.rs b/rust/crates/project/src/directory_actions.rs index d1fbdd02..3044dbe4 100644 --- a/rust/crates/project/src/directory_actions.rs +++ b/rust/crates/project/src/directory_actions.rs @@ -15,8 +15,14 @@ //! move, drops them after a delete, or hands them to the state of another workspace //! root. //! - `workspace.resolveDirectoryPresentation` merges user rules, optional shared project -//! rules, glob-matched custom types and Git-ignored paths into deterministic per-path -//! tree presentation metadata and manual indexing exclusions. +//! rules, optional plugin-contributed directory types and marks, glob-matched custom +//! types and Git-ignored paths into deterministic per-path tree presentation metadata +//! and manual indexing exclusions. Layers win in the order user > shared > plugin > +//! glob > vcs > plain. +//! +//! Plugin types and marks are never persisted: the host keeps what each plugin session +//! registered through `workspace/setDirectoryTypes` and `workspace/setDirectoryMarks`, drops +//! it when the session ends, and sends the live set with every resolve request. //! //! Directory keys are compared as paths: with `caseInsensitive` set, keys that differ only //! by case name the same directory. Stored keys keep the spelling they were written with. @@ -44,6 +50,9 @@ const MAX_TYPE_NAME_LEN: usize = 64; const MAX_TYPE_TAG_LEN: usize = 24; /// Maximum byte length of a custom type match glob pattern. const MAX_GLOB_LEN: usize = 256; +/// Largest number of plugin-contributed directory types one resolve request may carry, +/// summed over every plugin session the host forwards. +const MAX_PLUGIN_TYPES: usize = 256; /// Built-in directory roles recognized by Core. const BUILTIN_ROLES: [&str; 9] = [ @@ -58,7 +67,8 @@ const BUILTIN_ROLES: [&str; 9] = [ "package", ]; -/// Icon names allowed for custom directory types. +/// Icon names allowed for custom and plugin directory types. `lithe-plugin-rpc` keeps the +/// same list for `workspace/setDirectoryTypes`; `lithe-core` tests that the two agree. const ALLOWED_ICONS: [&str; 11] = [ "folder", "sources", @@ -201,6 +211,60 @@ struct RelocateRequest { target: Option, } +/// A directory type dynamically contributed by a plugin session. The derived order (plugin +/// ID first, then type ID) decides which duplicate contribution wins. +#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginDirectoryType { + /// Contributing plugin identifier. + plugin_id: String, + /// Type identifier starting with `plugin.` (for example `plugin.migrations`). + id: String, + /// Human-readable name displayed in menus and settings; blank names are refused. + name: String, + /// Optional short label shown beside directory names in the project tree. + #[serde(default, skip_serializing_if = "String::is_empty")] + tag: String, + /// Built-in icon identifier from [`ALLOWED_ICONS`]. + icon: String, + /// `#rrggbb` accent color; resolved entries carry it in lowercase. + color: String, + /// Whether rows of this type receive a subtle background tint. + #[serde(default)] + tint_bg: bool, + /// Whether the directory name text is tinted with `color`. + #[serde(default)] + tint_text: bool, + /// Whether descendant rows inherit the background tint. + #[serde(default)] + inherit_bg: bool, + /// Whether directories of this type are excluded from workspace indexing and search. + #[serde(default)] + exclude_indexing: bool, + /// Whether directories of this type carry a generated/read-only hint. + #[serde(default)] + read_only_hint: bool, + /// Optional comma-separated workspace-relative glob patterns for automatic matching. + #[serde(default, skip_serializing_if = "String::is_empty")] + match_glob: String, +} + +/// A directory mark dynamically contributed by a plugin session for one workspace-relative +/// path. The derived order (plugin ID first, then path) decides which duplicate mark wins. +#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginDirectoryMark { + /// Contributing plugin identifier. + plugin_id: String, + /// Workspace-relative directory path. + path: String, + /// Built-in role or `plugin.*` type ID. + role: String, + /// Optional `#rrggbb` color override. + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, +} + #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct ResolvePresentationRequest { @@ -209,12 +273,19 @@ struct ResolvePresentationRequest { /// Optional project-shared rules (e.g. `.lithe/directories.json`, lower than user rules). #[serde(default)] shared_rules: Option, + /// Optional plugin-contributed directory types (lower than user/shared custom types). + #[serde(default)] + plugin_types: Vec, + /// Optional plugin-contributed directory marks (lower than user/shared marks, above glob/VCS). + #[serde(default)] + plugin_marks: Vec, /// Workspace-relative directories currently excluded by `.gitignore`. #[serde(default)] git_excluded: Vec, #[serde(default)] case_insensitive: bool, - /// Workspace-relative paths (directories or files) to resolve presentation for. + /// Workspace-relative paths (directories or files) to resolve presentation for. It may + /// be omitted or empty: `manualExcludedDirectories` still covers every explicit mark. #[serde(default)] paths: Vec, } @@ -223,10 +294,13 @@ struct ResolvePresentationRequest { #[derive(Serialize, Clone, Debug, PartialEq, Eq)] #[serde(rename_all = "camelCase")] struct ResolvedDirectoryEntry { - /// Effective role or custom type ID (`plain` when unmarked). + /// Effective role or custom/plugin type ID (`plain` when unmarked). role: String, - /// Winning layer: `user`, `shared`, `glob`, `vcs`, `inherited`, or `plain`. + /// Winning layer: `user`, `shared`, `plugin`, `glob`, `vcs`, `inherited`, or `plain`. source: String, + /// Contributing plugin ID when `source == "plugin"` or a `plugin.*` type matched. + #[serde(skip_serializing_if = "Option::is_none")] + plugin_id: Option, /// Resolved icon identifier for directories. icon: String, /// Optional `#rrggbb` accent color for the directory icon or text. @@ -493,28 +567,89 @@ pub fn relocate_command(payload: Value) -> Result { } /// Resolves deterministic presentation metadata and effective manual indexing exclusions -/// across local user rules, optional shared project rules, glob-matched custom types and -/// `.gitignore` exclusions (`workspace.resolveDirectoryPresentation`). +/// across local user rules, optional shared project rules, plugin-contributed types and +/// marks, glob-matched custom types and `.gitignore` exclusions +/// (`workspace.resolveDirectoryPresentation`). +/// +/// When two plugins contribute the same `plugin.*` type ID or mark the same path, the entry +/// of the plugin whose ID sorts first wins, so the result does not depend on request order. pub fn resolve_presentation_command(payload: Value) -> Result { let request: ResolvePresentationRequest = parse(payload)?; validate_rules(&request.rules)?; if let Some(shared) = &request.shared_rules { validate_rules(shared)?; } - if request.paths.len() + request.git_excluded.len() > MAX_ENTRIES { + if request.paths.len() + request.git_excluded.len() + request.plugin_marks.len() > MAX_ENTRIES { return Err(CoreError::new( ErrorCode::InvalidRequest, "Too many paths in directory presentation request", )); } + if request.plugin_types.len() > MAX_PLUGIN_TYPES { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Too many plugin directory types in presentation request", + )); + } for path in request.paths.iter().chain(&request.git_excluded) { validate_path(path)?; } let ident = Identity(request.case_insensitive); - // Merge custom types deterministically: local user definitions override shared ones. + // Merge custom and plugin types deterministically: + // plugin types (sorted by pluginId, id) < shared custom types < local user custom types. let mut custom_types: BTreeMap = BTreeMap::new(); + let mut plugin_type_owners: BTreeMap = BTreeMap::new(); + let mut sorted_plugin_types = request.plugin_types; + sorted_plugin_types.sort(); + for pt in sorted_plugin_types { + if pt.plugin_id.trim().is_empty() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Plugin directory type requires pluginId", + )); + } + validate_plugin_type_id(&pt.id)?; + let normalized_color = normalize_hex_color(&pt.color)?; + if pt.name.trim().is_empty() || pt.name.len() > MAX_TYPE_NAME_LEN { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin directory type name", + )); + } + if pt.tag.len() > MAX_TYPE_TAG_LEN || pt.match_glob.len() > MAX_GLOB_LEN { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin directory type tag or matchGlob", + )); + } + if !ALLOWED_ICONS.contains(&pt.icon.as_str()) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Plugin directory type icon must be a built-in icon", + )); + } + if !custom_types.contains_key(&pt.id) { + plugin_type_owners.insert(pt.id.clone(), pt.plugin_id.clone()); + custom_types.insert( + pt.id.clone(), + CustomDirectoryType { + id: pt.id, + name: pt.name.trim().to_owned(), + tag: pt.tag.trim().to_owned(), + icon: pt.icon, + color: normalized_color, + tint_bg: pt.tint_bg, + tint_text: pt.tint_text, + inherit_bg: pt.inherit_bg, + exclude_indexing: pt.exclude_indexing, + read_only_hint: pt.read_only_hint, + match_glob: pt.match_glob.trim().to_owned(), + }, + ); + } + } if let Some(shared) = &request.shared_rules { for item in &shared.custom_types { custom_types.insert(item.id.clone(), item.clone()); @@ -543,26 +678,66 @@ pub fn resolve_presentation_command(payload: Value) -> Result .as_ref() .map(|r| index_map(&r.colors, &ident)) .unwrap_or_default(); + + let mut plugin_marks_map: BTreeMap = BTreeMap::new(); + let mut plugin_colors_map: BTreeMap = BTreeMap::new(); + let mut sorted_plugin_marks = request.plugin_marks; + sorted_plugin_marks.sort(); + for pm in &sorted_plugin_marks { + if pm.plugin_id.trim().is_empty() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Plugin directory mark requires pluginId", + )); + } + validate_path(&pm.path)?; + if !BUILTIN_ROLES.contains(&pm.role.as_str()) && validate_plugin_type_id(&pm.role).is_err() + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Plugin directory mark role must be a built-in role or plugin.* type ID", + )); + } + let key = ident.key(&pm.path); + plugin_marks_map + .entry(key.clone()) + .or_insert_with(|| (pm.role.clone(), pm.plugin_id.clone())); + if let Some(ref raw_color) = pm.color { + let normalized = normalize_hex_color(raw_color)?; + plugin_colors_map + .entry(key) + .or_insert_with(|| (normalized, pm.plugin_id.clone())); + } + } + let git_excluded: BTreeSet = request.git_excluded.iter().map(|p| ident.key(p)).collect(); - // Compute manual exclusions from user + shared marks (including custom types with - // `excludeIndexing: true`) so indexing stays aligned with presentation. + // Compute manual exclusions from user + shared + plugin marks (including custom/plugin + // types with `excludeIndexing: true`) so indexing stays aligned with presentation. let mut manual_excluded = BTreeSet::new(); - for (raw_path, role) in request - .shared_rules + for raw_path in sorted_plugin_marks .iter() - .flat_map(|r| r.marks.iter()) - .chain(request.rules.marks.iter()) + .map(|m| m.path.as_str()) + .chain( + request + .shared_rules + .iter() + .flat_map(|r| r.marks.keys().map(String::as_str)), + ) + .chain(request.rules.marks.keys().map(String::as_str)) { let key = ident.key(raw_path); - let effective_role = user_marks.get(&key).or_else(|| shared_marks.get(&key)); + let effective_role = user_marks + .get(&key) + .map(String::as_str) + .or_else(|| shared_marks.get(&key).map(String::as_str)) + .or_else(|| plugin_marks_map.get(&key).map(|(r, _)| r.as_str())); if let Some(effective) = effective_role { if role_excludes_indexing(effective, &custom_types) && !user_included.contains(&key) { - manual_excluded.insert(raw_path.clone()); + manual_excluded.insert(raw_path.to_owned()); } } - let _ = role; } let mut entries = BTreeMap::new(); @@ -571,15 +746,21 @@ pub fn resolve_presentation_command(payload: Value) -> Result raw_path, &ident, &custom_types, + &plugin_type_owners, &user_marks, &user_colors, &user_included, &shared_marks, &shared_colors, + &plugin_marks_map, + &plugin_colors_map, &git_excluded, ); if resolved.excluded - && matches!(resolved.source.as_str(), "user" | "shared" | "glob") + && matches!( + resolved.source.as_str(), + "user" | "shared" | "plugin" | "glob" + ) && !user_included.contains(&ident.key(raw_path)) { manual_excluded.insert(raw_path.clone()); @@ -598,11 +779,14 @@ fn resolve_one( raw_path: &str, ident: &Identity, custom_types: &BTreeMap, + plugin_type_owners: &BTreeMap, user_marks: &BTreeMap, user_colors: &BTreeMap, user_included: &BTreeSet, shared_marks: &BTreeMap, shared_colors: &BTreeMap, + plugin_marks: &BTreeMap, + plugin_colors: &BTreeMap, git_excluded: &BTreeSet, ) -> ResolvedDirectoryEntry { let key = ident.key(raw_path); @@ -610,12 +794,16 @@ fn resolve_one( let user_color = user_colors.get(&key); let shared_role = shared_marks.get(&key); let shared_color = shared_colors.get(&key); + let plugin_mark = plugin_marks.get(&key); + let plugin_color = plugin_colors.get(&key); let glob_type = find_glob_match(raw_path, custom_types, ident.0); let is_vcs_excluded = git_excluded.contains(&key) && !user_included.contains(&key); // Determine fallback role (what would apply if the user clears their local override). let auto_fallback_role = if let Some(role) = shared_role { Some(role.clone()) + } else if let Some((role, _)) = plugin_mark { + Some(role.clone()) } else if let Some(ct) = glob_type { Some(ct.id.clone()) } else if is_vcs_excluded { @@ -624,21 +812,37 @@ fn resolve_one( None }; - // Determine direct role and winning source. - let (role, mut source) = if let Some(role) = user_role { - (role.clone(), "user".to_owned()) + // Determine direct role, winning source, and optional contributing plugin ID. + let (role, mut source, plugin_id) = if let Some(role) = user_role { + ( + role.clone(), + "user".to_owned(), + plugin_type_owners.get(role).cloned(), + ) } else if user_color.is_some() { - ("plain".to_owned(), "user".to_owned()) + ("plain".to_owned(), "user".to_owned(), None) } else if let Some(role) = shared_role { - (role.clone(), "shared".to_owned()) + ( + role.clone(), + "shared".to_owned(), + plugin_type_owners.get(role).cloned(), + ) } else if shared_color.is_some() { - ("plain".to_owned(), "shared".to_owned()) + ("plain".to_owned(), "shared".to_owned(), None) + } else if let Some((role, pid)) = plugin_mark { + (role.clone(), "plugin".to_owned(), Some(pid.clone())) + } else if let Some((_, pid)) = plugin_color { + ("plain".to_owned(), "plugin".to_owned(), Some(pid.clone())) } else if let Some(ct) = glob_type { - (ct.id.clone(), "glob".to_owned()) + ( + ct.id.clone(), + "glob".to_owned(), + plugin_type_owners.get(&ct.id).cloned(), + ) } else if is_vcs_excluded { - ("excluded".to_owned(), "vcs".to_owned()) + ("excluded".to_owned(), "vcs".to_owned(), None) } else { - ("plain".to_owned(), "plain".to_owned()) + ("plain".to_owned(), "plain".to_owned(), None) }; let (icon, base_color, base_tint_bg, tint_text, tag, mut excluded, read_only_hint) = @@ -647,13 +851,16 @@ fn resolve_one( let effective_color = user_color .cloned() .or_else(|| shared_color.cloned()) + .or_else(|| plugin_color.map(|(c, _)| c.clone())) .or(base_color); - let direct_bg = if user_color.is_some() || shared_color.is_some() || base_tint_bg { - effective_color.clone() - } else { - None - }; + let direct_bg = + if user_color.is_some() || shared_color.is_some() || plugin_color.is_some() || base_tint_bg + { + effective_color.clone() + } else { + None + }; // Walk ancestors (nearest first) for inherited background tint and exclusion state. let mut bg_color = direct_bg; @@ -663,6 +870,7 @@ fn resolve_one( .get(&anc_key) .or_else(|| shared_marks.get(&anc_key)) .cloned() + .or_else(|| plugin_marks.get(&anc_key).map(|(r, _)| r.clone())) .or_else(|| find_glob_match(&ancestor, custom_types, ident.0).map(|ct| ct.id.clone())) .or_else(|| { if git_excluded.contains(&anc_key) && !user_included.contains(&anc_key) { @@ -673,7 +881,8 @@ fn resolve_one( }); let anc_color_override = user_colors .get(&anc_key) - .or_else(|| shared_colors.get(&anc_key)); + .or_else(|| shared_colors.get(&anc_key)) + .or_else(|| plugin_colors.get(&anc_key).map(|(c, _)| c)); if let Some(ref ar) = anc_role { if role_excludes_indexing(ar, custom_types) { @@ -702,6 +911,7 @@ fn resolve_one( ResolvedDirectoryEntry { role, source, + plugin_id, icon, color: effective_color, bg_color, @@ -976,7 +1186,30 @@ fn validate_path(path: &str) -> Result<(), CoreError> { } fn is_known_role(role: &str, custom_types: &[CustomDirectoryType]) -> bool { - BUILTIN_ROLES.contains(&role) || custom_types.iter().any(|ct| ct.id == role) + BUILTIN_ROLES.contains(&role) + || custom_types.iter().any(|ct| ct.id == role) + || validate_plugin_type_id(role).is_ok() +} + +fn validate_plugin_type_id(id: &str) -> Result<(), CoreError> { + let Some(rest) = id.strip_prefix("plugin.") else { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Plugin directory type ID must start with 'plugin.'", + )); + }; + if rest.is_empty() + || id.len() > MAX_TYPE_ID_LEN + || !rest.bytes().all(|b| { + b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-' | b'.') + }) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid plugin directory type ID", + )); + } + Ok(()) } fn validate_custom_type_id(id: &str) -> Result<(), CoreError> { diff --git a/rust/fixtures/workspace/directory-rules-v1.json b/rust/fixtures/workspace/directory-rules-v1.json index a8e377c2..c8655bd4 100644 --- a/rust/fixtures/workspace/directory-rules-v1.json +++ b/rust/fixtures/workspace/directory-rules-v1.json @@ -109,10 +109,67 @@ "target": {"marks": {"vendor": "plain", "vendor/pkg": "package"}, "includedDirectories": ["vendor/pkg/gen"], "previousRoles": {"vendor/pkg": "sources"}}} } ], + "resolve": [ + { + "id": "plugin-layers-sit-between-shared-and-glob", + "request": { + "rules": {"marks": {"manual": "sources"}, "includedDirectories": [], "previousRoles": {}}, + "sharedRules": {"marks": {"db/override": "generated"}, "includedDirectories": [], "previousRoles": {}}, + "pluginTypes": [ + {"pluginId": "com.example.b", "id": "plugin.migrations", "name": "Other", "icon": "folder", "color": "#111111"}, + {"pluginId": "com.example.a", "id": "plugin.migrations", "name": "Migrations", "tag": "migrations", "icon": "database", "color": "#0D9488", "tintBg": true, "inheritBg": true}, + {"pluginId": "com.example.a", "id": "plugin.cache", "name": "Cache", "icon": "archive", "color": "#64748b", "excludeIndexing": true, "matchGlob": ".cache"} + ], + "pluginMarks": [ + {"pluginId": "com.example.b", "path": "db/migrations", "role": "sources"}, + {"pluginId": "com.example.a", "path": "db/migrations", "role": "plugin.migrations"}, + {"pluginId": "com.example.a", "path": "db/override", "role": "plugin.migrations"}, + {"pluginId": "com.example.a", "path": "manual", "role": "excluded"}, + {"pluginId": "com.example.a", "path": "out", "role": "excluded", "color": "#ff0000"} + ], + "paths": ["db/migrations", "db/migrations/V1", "db/override", "manual", "out", "pkg/.cache"] + }, + "response": { + "entries": { + "db/migrations": {"role": "plugin.migrations", "source": "plugin", "pluginId": "com.example.a", "icon": "database", "color": "#0d9488", "bgColor": "#0d9488", "tintText": false, "tag": "migrations", "excluded": false, "readOnlyHint": false}, + "db/migrations/V1": {"role": "plain", "source": "inherited", "icon": "folder", "bgColor": "#0d9488", "tintText": false, "excluded": false, "readOnlyHint": false}, + "db/override": {"role": "generated", "source": "shared", "icon": "generated", "color": "#9f7aea", "bgColor": "#9f7aea", "tintText": false, "tag": "generated", "excluded": false, "readOnlyHint": true}, + "manual": {"role": "sources", "source": "user", "icon": "sources", "color": "#4e8df5", "bgColor": "#4e8df5", "tintText": false, "tag": "sources", "excluded": false, "readOnlyHint": false, "autoFallbackRole": "excluded"}, + "out": {"role": "excluded", "source": "plugin", "pluginId": "com.example.a", "icon": "excluded", "color": "#ff0000", "bgColor": "#ff0000", "tintText": false, "tag": "excluded", "excluded": true, "readOnlyHint": false}, + "pkg/.cache": {"role": "plugin.cache", "source": "glob", "pluginId": "com.example.a", "icon": "archive", "color": "#64748b", "tintText": false, "excluded": true, "readOnlyHint": false} + }, + "manualExcludedDirectories": ["out", "pkg/.cache"] + } + }, + { + "id": "explicit-plugin-exclusions-need-no-paths", + "request": { + "rules": {}, + "pluginTypes": [ + {"pluginId": "com.example.a", "id": "plugin.cache", "name": "Cache", "icon": "archive", "color": "#64748b", "excludeIndexing": true} + ], + "pluginMarks": [ + {"pluginId": "com.example.a", "path": "vendor", "role": "excluded"}, + {"pluginId": "com.example.a", "path": "gen", "role": "plugin.cache"}, + {"pluginId": "com.example.a", "path": "src", "role": "sources"} + ] + }, + "response": { + "entries": {}, + "manualExcludedDirectories": ["gen", "vendor"] + } + } + ], "invalid": [ {"command": "workspace.reduceDirectoryAction", "request": {"path": "../x", "action": {"kind": "exclude"}, "rules": {}}}, {"command": "workspace.reduceDirectoryAction", "request": {"path": "x", "action": {"kind": "setRole", "role": "excluded"}, "rules": {}}}, {"command": "workspace.reduceDirectoryAction", "request": {"path": "x", "action": {"kind": "exclude"}, "rules": {"marks": {"y": "bogus"}}}}, - {"command": "workspace.relocateDirectoryRules", "request": {"source": "x", "rules": {}, "target": {}}} + {"command": "workspace.relocateDirectoryRules", "request": {"source": "x", "rules": {}, "target": {}}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "paths": null}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "pluginTypes": [{"pluginId": "p", "id": "custom.x", "name": "X", "icon": "folder", "color": "#000000"}]}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "pluginTypes": [{"pluginId": "p", "id": "plugin.x", "name": " ", "icon": "folder", "color": "#000000"}]}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "pluginTypes": [{"pluginId": "p", "id": "plugin.x", "name": "X", "icon": "module", "color": "#000000"}]}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "pluginMarks": [{"pluginId": "p", "path": "x", "role": "custom.x"}]}}, + {"command": "workspace.resolveDirectoryPresentation", "request": {"rules": {}, "pluginMarks": [{"pluginId": "", "path": "x", "role": "sources"}]}} ] } diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 5b8a7db1..67245f3d 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4535,6 +4535,8 @@ and frequency limits. Native hosts must own all tasks and release their leases. | `clipboard/readText` | `clipboard.read` | none | `{text}` | | `clipboard/writeText` | `clipboard.write` | `text` | `null` | | `workspace/reveal` | `workspace.reveal` | `resource` | `null` | +| `workspace/setDirectoryTypes` | `workspace.directoryMarks` | `types` (`[{id,name,tag?,icon,color,tintBg?,tintText?,inheritBg?,excludeIndexing?,readOnlyHint?,matchGlob?}]`, max 32; `id` starts with `plugin.`) | `{count}` | +| `workspace/setDirectoryMarks` | `workspace.directoryMarks` | `marks` (`[{path,role,color?}]`, max 500; `role` is a built-in role or `plugin.*` type ID) | `{count}` | | `network/request` | `network.request` | `url,method?,headers?,body?,timeoutMilliseconds?,maximumResponseBytes?` | `{status,headers,body,encoding}` | Quick-pick `items` contains at most 1000 objects `{id,label,description?,detail?,picked?}`. @@ -4583,6 +4585,36 @@ text is nonempty and at most 256 bytes, tooltip 1024, priority an integer in -1000–1000 (default 0). Higher priority displays first, ties use host-stable IDs. A `commandID`, if present, names a command declared by the same plugin. +`workspace/setDirectoryTypes` and `workspace/setDirectoryMarks` each replace +the whole list this session registered in this context: a new call overwrites +the previous list and an empty list removes it. Each method holds one of the +16 limited registrations from its first call; context closure, disable, update +and backend end remove what it registered. Nothing is persisted or written to +project files. `count` is the number of entries in the call. A type has a +unique `id`: `plugin.` followed by lowercase ASCII letters, digits, `.`, `_` or +`-`, at most 64 bytes in total. `name` is nonempty after trimming, single-line, +at most 64 bytes; `tag` is at most 24 bytes; `icon` is one of `folder`, +`sources`, `tests`, `resources`, `generated`, `excluded`, `star`, `book`, +`archive`, `database` or `gear`; `color` is `#rrggbb`. `matchGlob` is at most +256 bytes of comma-separated patterns with `*`, `?` and `**`; a pattern with a +`/` matches the workspace-relative path, one without matches the directory name. +A mark has a unique workspace-relative `path`: nonempty, at most 1024 bytes, +`/`-separated, without a leading or trailing `/`, an empty, `.` or `..` +segment, `\`, `:` or a control character. Its `role` is `plain`, `sources`, +`tests`, `resources`, `testResources`, `generated`, `excluded` or a `plugin.*` +ID, which may name a type another plugin registers; a mark whose type no live +session registered displays as a plain folder. `color` is optional `#rrggbb`. + +The host merges every live registration below the user's own marks, colors and +cancelled exclusions and the project's shared directory rules, and above +glob-matched types and `.gitignore`. When two plugins register the same type ID +or mark the same path, the registration of the plugin whose ID sorts first wins. +A directory marked `excluded`, or with a type whose `excludeIndexing` is true, +leaves indexing and project search; so does a directory such a type's +`matchGlob` matches. The permission prompt states this. Users may also assign a +plugin type from the project tree; that assignment is the user's own mark and +remains after the plugin stops. + `views/refresh` only invalidates that plugin/session/context's visible instance; unknown or closed instances return `notFound`. Refreshes coalesce with in-flight calls and retain the old view until a valid result arrives. Tree items may set diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 679257d1..770a22df 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -102,7 +102,7 @@ "languageServer.request", "documents.contentProvider", "documents.save", - "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "network.request"] } + "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "workspace.directoryMarks", "network.request"] } }, "activationEvents": { "type": "array", diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 5a63e271..7e84c369 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -95,6 +95,8 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-05 | `workspace/listContexts` | 列出当前的工作区上下文,带变化序号 `revision` | `workspace.metadata` | 0 | | API-05 | `workspace/getContext` | 读取一个工作区上下文 | `workspace.metadata` | 0 | | API-05 | `workspace/getFolders` | 列出上下文的根目录,每个根目录带 `rootID` | `workspace.metadata` | 0 | +| API-05 | `workspace/setDirectoryTypes` | 注册或替换本插件会话在当前上下文提供的自定义目录类型(最多 32 个,`id` 以 `plugin.` 开头) | `workspace.directoryMarks` | 0 | +| API-05 | `workspace/setDirectoryMarks` | 注册或替换本插件会话在当前上下文的动态目录标记与可选配色(最多 500 条),优先级低于用户与项目共享规则、高于 Glob 与 `.gitignore` | `workspace.directoryMarks` | 0 | | API-06 | `workspace/readDirectory` | 分页列出目录项;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | | API-06 | `workspace/stat` | 读取文件或目录的类型、大小和修改时间;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | | API-06 | `workspace/readFile` | 读取磁盘上的文件,返回文本或 base64,超过上限时截断;执行/校验补充见 [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | @@ -297,6 +299,8 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-05 | `workspace/listContexts` | Lists the current workspace contexts with the change counter `revision` | `workspace.metadata` | 0 | | API-05 | `workspace/getContext` | Reads one workspace context | `workspace.metadata` | 0 | | API-05 | `workspace/getFolders` | Lists the context's root folders, each with a `rootID` | `workspace.metadata` | 0 | +| API-05 | `workspace/setDirectoryTypes` | Registers or replaces this plugin session's contributed directory types for the context (up to 32; `id` starts with `plugin.`) | `workspace.directoryMarks` | 0 | +| API-05 | `workspace/setDirectoryMarks` | Registers or replaces this plugin session's dynamic directory marks and optional colors for the context (up to 500); precedence sits below user/shared rules and above glob/VCS | `workspace.directoryMarks` | 0 | | API-06 | `workspace/readDirectory` | Lists directory entries page by page; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | | API-06 | `workspace/stat` | Reads the kind, size, and modification time of a file or directory; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | | API-06 | `workspace/readFile` | Reads a file from disk as text or base64, truncated past the limit; execution/validation details in [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | `workspace.files.read` | 0 | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 8dd915f5..85ce9567 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,8 @@ ## 待合入 +- [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 / `litheFunctions` 0 内补充(API-05):新增宿主方法 `workspace/setDirectoryTypes` 与 `workspace/setDirectoryMarks`(新权限 `workspace.directoryMarks`),允许插件后端在当前工作区上下文注册自定义目录类型(最多 32 个,`id` 以 `plugin.` 开头)与动态目录标记(最多 500 条);`workspace.resolveDirectoryPresentation` 新增可选 `pluginTypes` 与 `pluginMarks` 字段及输出可选 `pluginId`,按 `user > shared > plugin > glob > vcs > plain` 确定性合并呈现与索引排除,并允许用户手动分配 `plugin.*` 角色;插件提交时的校验与解析器一致,宿主保存下来的登记不会让整次解析失败;清单 schema 与四种官方 SDK(Rust、Go、Node、Java)同步补齐。无新增能力版本、协议版本或 SDK 版本。 + - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 - [#198](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/198)(2026-11-24),[@1lck](https://github.com/1lck),`pluginAPIVersion` 0 / `litheFunctions` 0 内补充(API-27):`editor/registerActions` 的 `services.editor.options.actionIcons` 新增四个通用行首导航图标 token:`navigate-implemented`(接口/契约有子实现,向下)、`navigate-implementing`(实现接口/契约,向上)、`navigate-overridden`(父类/方法被覆写,向下)、`navigate-overriding`(覆写父类声明,向上),保留已有 `navigate-super` 与 `navigate-implementations` 向后兼容。`plugins.editorActions.decode` 仍由宿主声明的 `actionIcons` 列表动态校验,插件通过 `getCapabilities` 发现是否支持新 token,在旧宿主上回退到原有图标;契约 README、领域参考与 `fixtures/editor/editor-actions.json` 同步更新。没有新增能力版本、协议版本、宿主方法、通知或 SDK 版本。 @@ -132,6 +134,8 @@ | API-05 | `workspace/listContexts` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/getContext` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-05 | `workspace/getFolders` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-05 | `workspace/setDirectoryTypes` | 0 | 待合入 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | +| API-05 | `workspace/setDirectoryMarks` | 0 | 待合入 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | | API-06 | `workspace/readDirectory` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-06 | `workspace/readDirectory` | 0(执行/校验补充) | 待合入 | [#190](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/190) | | API-06 | `workspace/stat` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 56cf43bf..36f48777 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -1484,6 +1484,16 @@ func (w *Workspace) Reveal(context WorkspaceContext, params any) (json.RawMessag return w.host.scoped(methodWorkspaceReveal, context, params) } +// SetDirectoryTypes registers or replaces this plugin session's contributed directory types for context. +func (w *Workspace) SetDirectoryTypes(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodWorkspaceSetDirectoryTypes, context, params) +} + +// SetDirectoryMarks registers or replaces this plugin session's dynamic directory marks for context. +func (w *Workspace) SetDirectoryMarks(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodWorkspaceSetDirectoryMarks, context, params) +} + // Network provides context-scoped network services. type Network struct{ host *Host } diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go index b0626736..7f0e6f62 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -19,86 +19,88 @@ const ( // JSON-RPC methods of the backend protocol. const ( - methodInitialize = "initialize" - methodShutdown = "shutdown" - methodExit = "exit" - methodCancelRequest = "$/cancelRequest" - methodLog = "lithe/log" - methodInvoke = "lithe/function/invoke" - methodRegister = "lithe/function/register" - methodUnregister = "lithe/function/unregister" - methodProgress = "lithe/function/progress" - methodKeymapImport = "lithe/keymap/import" - methodKeymapInputs = "lithe/host/keymapImport/listInputs" - methodKeymapChunk = "lithe/host/keymapImport/readChunk" - methodCredentialsGet = "lithe/host/credentials/get" - methodCredentialsSet = "lithe/host/credentials/set" - methodCredentialsDel = "lithe/host/credentials/delete" - methodCapabilities = "lithe/host/getCapabilities" - methodDispose = "lithe/host/subscriptions/dispose" - methodListContexts = "lithe/host/workspace/listContexts" - methodGetContext = "lithe/host/workspace/getContext" - methodGetFolders = "lithe/host/workspace/getFolders" - methodGetHostPaths = "lithe/host/workspace/getHostPaths" - methodReadDirectory = "lithe/host/workspace/readDirectory" - methodStat = "lithe/host/workspace/stat" - methodReadFile = "lithe/host/workspace/readFile" - methodWatch = "lithe/host/workspace/watch" - methodFindFiles = "lithe/host/workspace/findFiles" - methodFindText = "lithe/host/workspace/findText" - methodCreate = "lithe/host/workspace/create" - methodRename = "lithe/host/workspace/rename" - methodCopy = "lithe/host/workspace/copy" - methodTrash = "lithe/host/workspace/trash" - methodDocumentsList = "lithe/host/documents/list" - methodDocumentsSnap = "lithe/host/documents/getSnapshot" - methodDocumentsSave = "lithe/host/documents/save" - methodDocumentsAs = "lithe/host/documents/saveAs" - methodDocumentsClose = "lithe/host/documents/close" - methodEditorActions = "lithe/host/editor/registerActions" - methodEditorActive = "lithe/host/editor/getActive" - methodEditorSelect = "lithe/host/editor/getSelections" - methodEditorApply = "lithe/host/editor/applyEdits" - methodEditorReplace = "lithe/host/editor/replaceSelections" - methodEditorInsert = "lithe/host/editor/insertText" - methodEditorOpen = "lithe/host/editor/open" - methodEditorReveal = "lithe/host/editor/reveal" - methodWindowShowQuickPick = "lithe/host/window/showQuickPick" - methodWindowShowInputBox = "lithe/host/window/showInputBox" - methodPreviewOpenMarkdown = "lithe/host/preview/openMarkdown" - methodEditorShowDiff = "lithe/host/editor/showDiff" - methodViewsRefresh = "lithe/host/views/refresh" - methodOutputCreate = "lithe/host/output/create" - methodOutputAppend = "lithe/host/output/append" - methodOutputClear = "lithe/host/output/clear" - methodOutputShow = "lithe/host/output/show" - methodOutputDispose = "lithe/host/output/dispose" - methodProgressCreate = "lithe/host/progress/create" - methodProgressReport = "lithe/host/progress/report" - methodProgressEnd = "lithe/host/progress/end" - methodStatusBarSetItem = "lithe/host/statusBar/setItem" - methodStatusBarRemoveItem = "lithe/host/statusBar/removeItem" - methodClipboardReadText = "lithe/host/clipboard/readText" - methodClipboardWriteText = "lithe/host/clipboard/writeText" - methodWorkspaceReveal = "lithe/host/workspace/reveal" - methodNetworkRequest = "lithe/host/network/request" - methodPreviewHTML = "lithe/host/preview/openHTML" - methodBrowserOpen = "lithe/host/browser/openExternal" - methodShowInfo = "lithe/host/window/showInformation" - methodShowWarning = "lithe/host/window/showWarning" - methodShowError = "lithe/host/window/showError" - methodTerminalCreate = "lithe/host/terminal/create" - methodTerminalShow = "lithe/host/terminal/show" - methodTerminalClose = "lithe/host/terminal/close" - methodTerminalReopen = "lithe/host/terminal/reopen" - methodTerminalDrop = "lithe/host/terminal/dispose" - methodTerminalExit = "lithe/host/terminal/onExit" - methodProviders = "lithe/host/functions/providers" - methodRelayInvoke = "lithe/host/functions/invoke" - methodContexts = "lithe/host/workspace/didChangeContexts" - methodNotify = "lithe/host/subscriptions/notify" - methodCommandRan = "lithe/host/commands/didRun" - hostPrefix = "lithe/host/" + methodInitialize = "initialize" + methodShutdown = "shutdown" + methodExit = "exit" + methodCancelRequest = "$/cancelRequest" + methodLog = "lithe/log" + methodInvoke = "lithe/function/invoke" + methodRegister = "lithe/function/register" + methodUnregister = "lithe/function/unregister" + methodProgress = "lithe/function/progress" + methodKeymapImport = "lithe/keymap/import" + methodKeymapInputs = "lithe/host/keymapImport/listInputs" + methodKeymapChunk = "lithe/host/keymapImport/readChunk" + methodCredentialsGet = "lithe/host/credentials/get" + methodCredentialsSet = "lithe/host/credentials/set" + methodCredentialsDel = "lithe/host/credentials/delete" + methodCapabilities = "lithe/host/getCapabilities" + methodDispose = "lithe/host/subscriptions/dispose" + methodListContexts = "lithe/host/workspace/listContexts" + methodGetContext = "lithe/host/workspace/getContext" + methodGetFolders = "lithe/host/workspace/getFolders" + methodGetHostPaths = "lithe/host/workspace/getHostPaths" + methodReadDirectory = "lithe/host/workspace/readDirectory" + methodStat = "lithe/host/workspace/stat" + methodReadFile = "lithe/host/workspace/readFile" + methodWatch = "lithe/host/workspace/watch" + methodFindFiles = "lithe/host/workspace/findFiles" + methodFindText = "lithe/host/workspace/findText" + methodCreate = "lithe/host/workspace/create" + methodRename = "lithe/host/workspace/rename" + methodCopy = "lithe/host/workspace/copy" + methodTrash = "lithe/host/workspace/trash" + methodDocumentsList = "lithe/host/documents/list" + methodDocumentsSnap = "lithe/host/documents/getSnapshot" + methodDocumentsSave = "lithe/host/documents/save" + methodDocumentsAs = "lithe/host/documents/saveAs" + methodDocumentsClose = "lithe/host/documents/close" + methodEditorActions = "lithe/host/editor/registerActions" + methodEditorActive = "lithe/host/editor/getActive" + methodEditorSelect = "lithe/host/editor/getSelections" + methodEditorApply = "lithe/host/editor/applyEdits" + methodEditorReplace = "lithe/host/editor/replaceSelections" + methodEditorInsert = "lithe/host/editor/insertText" + methodEditorOpen = "lithe/host/editor/open" + methodEditorReveal = "lithe/host/editor/reveal" + methodWindowShowQuickPick = "lithe/host/window/showQuickPick" + methodWindowShowInputBox = "lithe/host/window/showInputBox" + methodPreviewOpenMarkdown = "lithe/host/preview/openMarkdown" + methodEditorShowDiff = "lithe/host/editor/showDiff" + methodViewsRefresh = "lithe/host/views/refresh" + methodOutputCreate = "lithe/host/output/create" + methodOutputAppend = "lithe/host/output/append" + methodOutputClear = "lithe/host/output/clear" + methodOutputShow = "lithe/host/output/show" + methodOutputDispose = "lithe/host/output/dispose" + methodProgressCreate = "lithe/host/progress/create" + methodProgressReport = "lithe/host/progress/report" + methodProgressEnd = "lithe/host/progress/end" + methodStatusBarSetItem = "lithe/host/statusBar/setItem" + methodStatusBarRemoveItem = "lithe/host/statusBar/removeItem" + methodClipboardReadText = "lithe/host/clipboard/readText" + methodClipboardWriteText = "lithe/host/clipboard/writeText" + methodWorkspaceReveal = "lithe/host/workspace/reveal" + methodWorkspaceSetDirectoryTypes = "lithe/host/workspace/setDirectoryTypes" + methodWorkspaceSetDirectoryMarks = "lithe/host/workspace/setDirectoryMarks" + methodNetworkRequest = "lithe/host/network/request" + methodPreviewHTML = "lithe/host/preview/openHTML" + methodBrowserOpen = "lithe/host/browser/openExternal" + methodShowInfo = "lithe/host/window/showInformation" + methodShowWarning = "lithe/host/window/showWarning" + methodShowError = "lithe/host/window/showError" + methodTerminalCreate = "lithe/host/terminal/create" + methodTerminalShow = "lithe/host/terminal/show" + methodTerminalClose = "lithe/host/terminal/close" + methodTerminalReopen = "lithe/host/terminal/reopen" + methodTerminalDrop = "lithe/host/terminal/dispose" + methodTerminalExit = "lithe/host/terminal/onExit" + methodProviders = "lithe/host/functions/providers" + methodRelayInvoke = "lithe/host/functions/invoke" + methodContexts = "lithe/host/workspace/didChangeContexts" + methodNotify = "lithe/host/subscriptions/notify" + methodCommandRan = "lithe/host/commands/didRun" + hostPrefix = "lithe/host/" ) // JSON-RPC error numbers. diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java index 1e8ce7f7..0ea4805d 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Host.java @@ -420,6 +420,8 @@ public CompletableFuture watchConfiguration( public final class Workspace { /** Reveal a saved resource in the file manager. Permission workspace.reveal. */ public CompletableFuture> reveal(Map context,Map params) {return scoped(Protocol.HOST_WORKSPACE_REVEAL,context,params);} + public CompletableFuture> setDirectoryTypes(Map context,Map params) {return scoped(Protocol.HOST_WORKSPACE_SET_DIRECTORY_TYPES,context,params);} + public CompletableFuture> setDirectoryMarks(Map context,Map params) {return scoped(Protocol.HOST_WORKSPACE_SET_DIRECTORY_MARKS,context,params);} private Workspace() {} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index 0e76f3b6..7016898a 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -106,6 +106,8 @@ public final class Protocol { public static final String HOST_CLIPBOARD_READ_TEXT = "lithe/host/clipboard/readText"; public static final String HOST_CLIPBOARD_WRITE_TEXT = "lithe/host/clipboard/writeText"; public static final String HOST_WORKSPACE_REVEAL = "lithe/host/workspace/reveal"; + public static final String HOST_WORKSPACE_SET_DIRECTORY_TYPES = "lithe/host/workspace/setDirectoryTypes"; + public static final String HOST_WORKSPACE_SET_DIRECTORY_MARKS = "lithe/host/workspace/setDirectoryMarks"; public static final String HOST_NETWORK_REQUEST = "lithe/host/network/request"; public static final String HOST_PREVIEW_OPEN_HTML = "lithe/host/preview/openHTML"; public static final String HOST_BROWSER_OPEN_EXTERNAL = "lithe/host/browser/openExternal"; diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index 1116e6c5..2bb45dd9 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -280,6 +280,8 @@ export function createHost(channel, callSignal, parentOperationId) { }), workspace: Object.freeze({ reveal: scoped(HOST_METHODS.workspaceReveal), + setDirectoryTypes: scoped(HOST_METHODS.workspaceSetDirectoryTypes), + setDirectoryMarks: scoped(HOST_METHODS.workspaceSetDirectoryMarks), listContexts: async (options) => request(HOST_METHODS.workspaceListContexts, {}, options), getContext: async (context, options) => diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 428b07f2..1747aac5 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -273,6 +273,8 @@ export interface Host { }; readonly workspace: { reveal: Scoped<{resource:WorkspaceResource},null>; + setDirectoryTypes: Scoped<{types:JsonObject[]},{count:number}>; + setDirectoryMarks: Scoped<{marks:JsonObject[]},{count:number}>; /** Permission `workspace.metadata`. Entries carry no `stateDirectory`. */ listContexts(options?: HostRequestOptions): Promise<{ revision: number; contexts: WorkspaceContext[] }>; diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index 373b508e..42125b5f 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -58,6 +58,8 @@ export const HOST_METHODS = Object.freeze({ clipboardReadText: 'lithe/host/clipboard/readText', clipboardWriteText: 'lithe/host/clipboard/writeText', workspaceReveal: 'lithe/host/workspace/reveal', + workspaceSetDirectoryTypes: 'lithe/host/workspace/setDirectoryTypes', + workspaceSetDirectoryMarks: 'lithe/host/workspace/setDirectoryMarks', networkRequest: 'lithe/host/network/request', credentialsGet: 'lithe/host/credentials/get', diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 5b19ebab..70ce7cd3 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -841,6 +841,26 @@ impl Workspace { self.host.scoped(methods::WORKSPACE_REVEAL, context, params) } + /// Registers or replaces this plugin session's contributed directory types for `context`. + pub fn set_directory_types( + &self, + context: &WorkspaceContext, + params: Value, + ) -> Result { + self.host + .scoped(methods::WORKSPACE_SET_DIRECTORY_TYPES, context, params) + } + + /// Registers or replaces this plugin session's dynamic directory marks for `context`. + pub fn set_directory_marks( + &self, + context: &WorkspaceContext, + params: Value, + ) -> Result { + self.host + .scoped(methods::WORKSPACE_SET_DIRECTORY_MARKS, context, params) + } + /// `{ revision, contexts }`. pub fn list_contexts(&self) -> Result { self.host diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index 902b2a2a..d5e437d2 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -93,6 +93,8 @@ pub(crate) mod methods { pub const CLIPBOARD_READ_TEXT: &str = "lithe/host/clipboard/readText"; pub const CLIPBOARD_WRITE_TEXT: &str = "lithe/host/clipboard/writeText"; pub const WORKSPACE_REVEAL: &str = "lithe/host/workspace/reveal"; + pub const WORKSPACE_SET_DIRECTORY_TYPES: &str = "lithe/host/workspace/setDirectoryTypes"; + pub const WORKSPACE_SET_DIRECTORY_MARKS: &str = "lithe/host/workspace/setDirectoryMarks"; pub const NETWORK_REQUEST: &str = "lithe/host/network/request"; pub const PREVIEW_OPEN_HTML: &str = "lithe/host/preview/openHTML"; pub const BROWSER_OPEN_EXTERNAL: &str = "lithe/host/browser/openExternal";