Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 17 additions & 6 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -7640,18 +7640,29 @@ 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
`{ source, destination?, caseInsensitive?, rules, target? }` and returns `{ rules, target }`:
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? }`
Expand Down
242 changes: 242 additions & 0 deletions rust/crates/core/src/tests/directory_actions.rs
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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<Value>| {
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", &params).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", &params).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}");
}
12 changes: 12 additions & 0 deletions rust/crates/plugin-rpc/src/host_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions rust/crates/plugin-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Loading
Loading