Skip to content
Draft
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
39 changes: 39 additions & 0 deletions rust/crates/core/src/tests/declarative_plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const SETTINGS_FIXTURE: &str = contract_file!("fixtures/settings/settings.plugin
const BACKEND_FIXTURE: &str = contract_file!("fixtures/backend/backend.plugin.json");
const WORKSPACE_BACKEND_FIXTURE: &str =
contract_file!("fixtures/backend/backend-workspace.plugin.json");
const RECENT_PROJECTS_IMPORT_FIXTURE: &str =
contract_file!("fixtures/backend/recent-projects-import.plugin.json");
const FUNCTION_EXPORTER_FIXTURE: &str =
contract_file!("fixtures/backend/plugin-functions-exporter.plugin.json");
const FUNCTION_CALLER_FIXTURE: &str =
Expand Down Expand Up @@ -102,6 +104,7 @@ fn fixture(name: &str) -> Value {
"settings.plugin.json" => SETTINGS_FIXTURE,
"backend.plugin.json" => BACKEND_FIXTURE,
"backend-workspace.plugin.json" => WORKSPACE_BACKEND_FIXTURE,
"recent-projects-import.plugin.json" => RECENT_PROJECTS_IMPORT_FIXTURE,
"plugin-functions-exporter.plugin.json" => FUNCTION_EXPORTER_FIXTURE,
"plugin-functions-caller.plugin.json" => FUNCTION_CALLER_FIXTURE,
"debug-adapter.plugin.json" => DEBUG_ADAPTER_FIXTURE,
Expand Down Expand Up @@ -142,6 +145,7 @@ fn contract_fixtures_and_official_plugins_validate() {
PUBLISHER_BUNDLED_FIXTURE,
BACKEND_FIXTURE,
WORKSPACE_BACKEND_FIXTURE,
RECENT_PROJECTS_IMPORT_FIXTURE,
FUNCTION_EXPORTER_FIXTURE,
FUNCTION_CALLER_FIXTURE,
DEBUG_ADAPTER_FIXTURE,
Expand Down Expand Up @@ -1021,6 +1025,41 @@ fn workspace_backend_is_planned_with_its_version_and_workspace_service() {
assert_eq!(hosted(json!({ "backend": [0] }))["status"], "ok");
}

/// `workspace.recentProjects.import` is a host-method permission of the
/// backend (plan API-05): the launch plan grants the import method and the
/// message methods the confirmation flow uses, and the permission without a
/// backend is refused because no process would ever exercise it.
#[test]
fn recent_projects_import_permission_grants_the_method_to_the_backend() {
let outcome = validate(fixture("recent-projects-import.plugin.json"));
assert_eq!(outcome["status"], "ok", "{outcome}");
let launch = language_server_launch_plan_command(json!({
"manifest": fixture("recent-projects-import.plugin.json"),
"backend": true,
"request": {
"pluginDirectory": "/plugins/recent-projects-import",
"stateDirectory": "/state/recent-projects-import",
"architecture": "arm64"
},
}))
.expect("payload is well formed");
assert_eq!(launch["status"], "ok", "{launch}");
let services = launch["plan"]["backend"]["hostServices"]
.as_array()
.unwrap();
assert!(services.contains(&json!("lithe/host/workspace/recentProjects.importEntries")));
assert!(services.contains(&json!("lithe/host/window/showInformation")));

// Without a backend process the manifest is refused: `requires.backend`
// no longer matches a declaration, and the host-method permission check
// in permissions.rs is the second line of the same rule.
let mut without_backend = fixture("recent-projects-import.plugin.json");
without_backend.as_object_mut().unwrap().remove("backend");
let outcome = validate(without_backend);
assert_eq!(outcome["status"], "rejected", "{outcome}");
assert_eq!(outcome["error"]["field"], "requires.backend");
}

/// An exporting plugin is sorted by function ID and starts for a call without
/// a page or an event. Only a plugin that declares calls is granted the host
/// service that finds providers: exporting grants nothing, and a call needs
Expand Down
39 changes: 39 additions & 0 deletions rust/crates/plugin-rpc/src/host_params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub(crate) fn check_host_params(
"parentOperationID",
],
HostParams::KeymapSnapshot { chunk: false } => &["snapshotID", "providerID"],
HostParams::RecentProjectsImport => &["entries"],
HostParams::KeymapSnapshot { chunk: true } => &[
"snapshotID",
"providerID",
Expand Down Expand Up @@ -329,6 +330,44 @@ pub(crate) fn check_host_params(
));
}
}
HostParams::RecentProjectsImport => {
let entries = params
.get("entries")
.and_then(Value::as_array)
.filter(|entries| {
!entries.is_empty() && entries.len() <= MAX_RECENT_PROJECT_IMPORT_ENTRIES
});
let valid_entry = |entry: &Value| {
let object = entry.as_object()?;
// Exactly the two fields the reducer records; an unknown field
// is a malformed entry, not a silently ignored option.
if object.len() != 2
|| !object.contains_key("path")
|| !object.contains_key("lastOpenedAt")
{
return None;
}
let path = object.get("path")?.as_str()?;
if path.is_empty()
|| path.len() > MAX_RECENT_PROJECT_PATH_BYTES
|| path.contains('\0')
{
return None;
}
let time = object.get("lastOpenedAt")?.as_i64()?;
if time < 0 {
return None;
}
Some(())
};
if !entries
.is_some_and(|entries| entries.iter().all(|entry| valid_entry(entry).is_some()))
{
return Err(invalid(
"`entries` is 1-1024 objects of a 1-4096 byte path without NUL and a non-negative millisecond time.",
));
}
}
HostParams::LanguageServerRequest
| HostParams::LanguageServerNotify
| HostParams::LanguageServerStatus => {
Expand Down
9 changes: 9 additions & 0 deletions rust/crates/plugin-rpc/src/host_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub(crate) enum HostParams {
BuildConfiguration { watch: bool },
/// Snapshot source listing or one bounded chunk from a selected source.
KeymapSnapshot { chunk: bool },
/// `{ entries }`: 1-1024 dated recent-project entries to merge into the
/// host's recent projects list (plan API-05).
RecentProjectsImport,
/// `{ context, serverID, method, params?, timeoutMilliseconds? }`: one
/// request to the plugin's own language server (plan API-25).
LanguageServerRequest,
Expand Down Expand Up @@ -240,6 +243,12 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[
permission: Some("workspace.directoryMarks"),
params: HostParams::Workflow,
},
HostMethod {
method: WORKSPACE_RECENT_PROJECTS_IMPORT,
service: "workspace",
permission: Some("workspace.recentProjects.import"),
params: HostParams::RecentProjectsImport,
},
HostMethod {
method: "lithe/host/network/request",
service: "network",
Expand Down
69 changes: 69 additions & 0 deletions rust/crates/plugin-rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ pub const HOST_PERMISSIONS: &[&str] = &[
"clipboard.write",
"workspace.reveal",
"workspace.directoryMarks",
"workspace.recentProjects.import",
"network.request",
"workspace.files.read",
"workspace.files.watch",
Expand Down Expand Up @@ -231,6 +232,21 @@ const WORKSPACE_GET_FOLDERS: &str = "lithe/host/workspace/getFolders";
/// it out of the session and adding it widened no existing grant.
const WORKSPACE_GET_HOST_PATHS: &str = "lithe/host/workspace/getHostPaths";

/// Dated recent-project entries a backend merges into the host's recent
/// projects list (plan API-05). `workspace.recentProjects.import` admits it
/// as a grant of its own, so a host that does not serve it leaves it out of
/// the session and adding it widened no existing grant.
pub const WORKSPACE_RECENT_PROJECTS_IMPORT: &str =
"lithe/host/workspace/recentProjects.importEntries";

/// Most entries one `recentProjects.importEntries` request may carry, the
/// same bound the recent-projects reducer enforces.
pub(crate) const MAX_RECENT_PROJECT_IMPORT_ENTRIES: usize = 1024;

/// Longest project path one imported entry may name, in UTF-8 bytes, the
/// same bound the recent-projects reducer enforces.
pub(crate) const MAX_RECENT_PROJECT_PATH_BYTES: usize = 4096;

/// Most root IDs one `getHostPaths` request may name.
const MAX_HOST_PATH_ROOTS: usize = 256;

Expand Down Expand Up @@ -914,6 +930,59 @@ mod tests {
.contains(&json!(WORKSPACE_GET_HOST_PATHS)));
}

/// Recent projects import is a method grant of its own (plan API-05):
/// the aggregate workspace grant never admits it, and the entries keep
/// the reducer's bounds.
#[test]
fn recent_projects_import_is_a_method_grant_with_bounded_entries() {
assert_eq!(
methods_for_permission("workspace.recentProjects.import"),
[WORKSPACE_RECENT_PROJECTS_IMPORT]
);
assert!(is_host_grant(WORKSPACE_RECENT_PROJECTS_IMPORT));
let granted = BTreeSet::from([WORKSPACE_RECENT_PROJECTS_IMPORT.to_string()]);
let entry = |path: String, time: i64| json!({ "path": path, "lastOpenedAt": time });
let request = |entries: Vec<Value>| {
host_request(
WORKSPACE_RECENT_PROJECTS_IMPORT,
Some(&json!({ "entries": entries })),
Some(0),
&granted,
)
};
assert_eq!(
request(vec![entry("/projects/atlas".into(), 0)]),
Ok(HostRoute::Forward(HOST_SERVICE_WORKSPACE))
);
// The bounds are inclusive: 1024 entries, and a 4096-byte path. The
// 1 MiB host-request byte limit applies on top of both.
let longest = "p".repeat(MAX_RECENT_PROJECT_PATH_BYTES);
let full: Vec<Value> = (0..MAX_RECENT_PROJECT_IMPORT_ENTRIES)
.map(|i| entry(format!("/projects/{i}"), i as i64))
.collect();
assert!(request(full.clone()).is_ok());
let mut over = full;
over.push(entry("/projects/one-more".into(), 0));
assert_eq!(over.len(), MAX_RECENT_PROJECT_IMPORT_ENTRIES + 1);
assert_eq!(request(over).unwrap_err().code, codes::HOST_INVALID_PARAMS);
assert!(request(vec![entry(longest.clone(), 0)]).is_ok());
assert_eq!(
request(vec![entry(longest + "x", 0)]).unwrap_err().code,
codes::HOST_INVALID_PARAMS
);
// A session granted only the workspace service never learns the method.
let capabilities =
capabilities_answer(0, &BTreeSet::from([HOST_SERVICE_WORKSPACE.to_string()]));
assert!(!capabilities
.to_string()
.contains(WORKSPACE_RECENT_PROJECTS_IMPORT));
let capabilities = capabilities_answer(0, &granted);
assert!(capabilities["services"][HOST_SERVICE_WORKSPACE]["methods"]
.as_array()
.unwrap()
.contains(&json!(WORKSPACE_RECENT_PROJECTS_IMPORT)));
}

/// Saving and file changes are method grants of their own (plan
/// API-11): a session granted the `workspace` service, or only reading,
/// never writes, and each new failure code has a number of its own.
Expand Down
38 changes: 38 additions & 0 deletions shared/plugins/contract/v1/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6032,6 +6032,7 @@ notifications.
| `lithe/host/workspace/getContext` | `{ context: { contextID, generation } }` | `<context>` | `workspace.metadata` |
| `lithe/host/workspace/getFolders` | `{ context: { contextID, generation } }` | `{ folders: [<folder>] }` | `workspace.metadata` |
| `lithe/host/workspace/getHostPaths` | `{ context: { contextID, generation }, rootIDs?: [<rootID>] }` | `{ folders: [{ rootID, hostPath }] }` | `workspace.metadata`, as a method grant of its own |
| `lithe/host/workspace/recentProjects.importEntries` | `{ entries: [{ path, lastOpenedAt }] }` | `{ added: [<path>], removed: [<path>] }` | `workspace.recentProjects.import`, as a method grant of its own |

- Core answers `getCapabilities` itself; `protocolVersion` is the negotiated `litheFunctions` version. `services` maps each service the
session may use (the implicit `host`, `subscriptions`, and `commands`, and
Expand Down Expand Up @@ -6125,6 +6126,43 @@ notifications.
create nothing, so listing many windows leaves no directories behind.
`${stateDir}` is the plugin-wide state. Both survive disabling and
updating the plugin and are deleted when it is uninstalled.
- `recentProjects.importEntries` merges dated project entries into the
host's recent projects list, the list the welcome screen shows. A
migration plugin reads another tool's recent projects itself and hands
the normalized entries here; the host owns the list, its ordering,
deduplication and capacity, and the plugin never reads or writes the
host's history store.
- It is granted by `workspace.recentProjects.import` as a method grant of
its own, not with the `workspace` service: a host that does not serve it
leaves it out of `getCapabilities`, and the service grant alone is
`plugin.host.permissionDenied`. The permission requires a `backend`
declaration, like every host-method permission.
- `entries` is 1 to 1024 objects of exactly two fields: `path`, a
non-empty absolute local path of at most 4096 UTF-8 bytes without NUL,
and `lastOpenedAt`, a non-negative integer of Unix milliseconds. An
unknown top-level option is `plugin.host.unsupportedOption` naming the
option; an entry with a missing, extra or malformed field is
`plugin.host.invalidParams`. The whole request also obeys
`hostRequestBytes`.
- The host merges with the rules of its own history: a path already
listed keeps the newer of the two times, a new path is added, and the
retained list is ordered and capped by the host's capacity. `added`
names the paths newly retained and `removed` the paths no longer
retained after the merge and the cap. The answer carries no other
entries, so an import never reveals the rest of the user's history.
- The list is global to the application, not per workspace: the request
names no context, and the merge reaches every window through the
host's own history publication. A storage failure is
`plugin.host.failed`; the host writes atomically, so a failure leaves
the previous list.
- The paths are local paths on the machine that runs Lithe. A plugin
importing a remote tool's history maps what it can to local paths and
skips the rest itself; the method does not accept the host's opaque
remote identities.
- No version changes: the method is discovered through `getCapabilities`.
A host without a handler answers `plugin.host.unavailable`, and a Core
that does not know the permission refuses the manifest at install with
`plugin.permission.unknown`.
- A page call may name its context: `lsp.functionRequest.context`
(`{ contextID, generation }`) reaches the backend as
`params.context` of `lithe/function/invoke`. A malformed reference is
Expand Down
Loading