diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index e534f272..bc7bbdb2 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -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 = @@ -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, @@ -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, @@ -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 diff --git a/rust/crates/plugin-rpc/src/host_params.rs b/rust/crates/plugin-rpc/src/host_params.rs index 3562bfa4..5c748530 100644 --- a/rust/crates/plugin-rpc/src/host_params.rs +++ b/rust/crates/plugin-rpc/src/host_params.rs @@ -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", @@ -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 => { diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index 53411382..0fece2d6 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -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, @@ -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", diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index 6fded086..d603f69a 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -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", @@ -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; @@ -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| { + 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 = (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. diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d429a6ec..83e95f20 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -6032,6 +6032,7 @@ notifications. | `lithe/host/workspace/getContext` | `{ context: { contextID, generation } }` | `` | `workspace.metadata` | | `lithe/host/workspace/getFolders` | `{ context: { contextID, generation } }` | `{ folders: [] }` | `workspace.metadata` | | `lithe/host/workspace/getHostPaths` | `{ context: { contextID, generation }, rootIDs?: [] }` | `{ folders: [{ rootID, hostPath }] }` | `workspace.metadata`, as a method grant of its own | +| `lithe/host/workspace/recentProjects.importEntries` | `{ entries: [{ path, lastOpenedAt }] }` | `{ added: [], removed: [] }` | `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 @@ -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 diff --git a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json index 7940293f..a3be24c3 100644 --- a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json +++ b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json @@ -573,7 +573,18 @@ {"name": "an empty root ID list is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": []}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a root ID named twice is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": ["r0c1d2e3f4a5b6c7d", "r0c1d2e3f4a5b6c7d"]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a root ID outside the alphabet is invalid", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "rootIDs": ["/home/me/orders"]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, - {"name": "host paths name the option they do not support", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "path": "/home/me/orders"}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "path"}}} + {"name": "host paths name the option they do not support", "version": 0, "hostServices": ["workspace", "lithe/host/workspace/getHostPaths"], "method": "lithe/host/workspace/getHostPaths", "params": {"context": {"contextID": "w-3f2a", "generation": 2}, "path": "/home/me/orders"}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "path"}}}, + {"name": "recent projects import forwards with its own method grant", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1785683892804}, {"path": "/home/me/projects/notebook", "lastOpenedAt": 1785650905947}]}, "expected": {"forward": "workspace"}}, + {"name": "the workspace service alone does not grant recent projects import", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1}]}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "recent projects import without a grant is refused", "version": 0, "hostServices": [], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1}]}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "recent projects import names the option it does not support", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1}], "capacity": 50}, "expected": {"rpcCode": -32018, "code": "plugin.host.unsupportedOption", "details": {"option": "capacity"}}}, + {"name": "an empty recent projects import is invalid", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": []}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects entry has exactly a path and a time", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1, "pinned": true}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects entry needs a time", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas"}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects path is not empty", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "", "lastOpenedAt": 1}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects path has no NUL", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/\u0000projects", "lastOpenedAt": 1}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects time is not negative", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": -1}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a recent projects time is a whole millisecond number", "version": 0, "hostServices": ["lithe/host/workspace/recentProjects.importEntries"], "method": "lithe/host/workspace/recentProjects.importEntries", "params": {"entries": [{"path": "/home/me/projects/atlas", "lastOpenedAt": 1.5}]}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}} ], "invocationCallers": [ { diff --git a/shared/plugins/contract/v1/fixtures/backend/recent-projects-import.plugin.json b/shared/plugins/contract/v1/fixtures/backend/recent-projects-import.plugin.json new file mode 100644 index 00000000..ae15ec70 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/backend/recent-projects-import.plugin.json @@ -0,0 +1,34 @@ +{ + "schemaVersion": 0, + "id": "dev.lithe.fixture.recentprojectsimport", + "displayName": "Recent Projects Import", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { + "backend": 0 + }, + "vendor": { + "id": "org.example", + "displayName": "Example", + "signatureRequirement": "publisherPackage" + }, + "permissions": [ + "backend.launch", + "window.messages", + "workspace.recentProjects.import" + ], + "activationEvents": [ + "onWorkspaceOpen" + ], + "languages": [], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/backend" + }, + "arguments": [ + "--state", + "${stateDir}" + ] + } +} \ No newline at end of file diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 327bed37..645344c3 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -111,7 +111,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", "workspace.directoryMarks", "network.request", "agents.run", "agents.native", "agents.sessions.read", "agents.usage.read", "agents.configuration"] } + "workspace.files.write", "window.input", "views.refresh", "output.write", "window.progress", "statusBar.write", "clipboard.read", "clipboard.write", "workspace.reveal", "workspace.directoryMarks", "workspace.recentProjects.import", "network.request", "agents.run", "agents.native", "agents.sessions.read", "agents.usage.read", "agents.configuration"] } }, "activationEvents": { "type": "array", diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index fd00d60f..9df223ff 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -30,7 +30,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-02 | 命令 | 部分完成 | [`ui` 不打开工具窗口的命令](../contract/v1/README.md#backend-only-commands)和 `commands/didRun` 通知 | 运行期动态注册命令、带返回结果的执行 | [界面](domains/ui.md) | | API-03 | 菜单、快捷键、上下文键、状态栏 | 部分完成 | 已有的命令放置位置(`ui.commands`);`statusBar/setItem`、`removeItem` | 通用菜单、快捷键贡献、上下文键 | [界面](domains/ui.md) | | API-04 | 工作区与文档事件 | 部分完成 | `workspace/didChangeContexts`、`workspace/watch` 的文件事件 | 文档、选区、活动编辑器的变化事件 | [插件后端](domains/backend.md) | -| API-05 | 工作区上下文 | 已公开 | [`workspace/listContexts`、`getContext`、`getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery),带 `contextID`/`generation` 与 `rootID` | — | [插件后端](domains/backend.md) | +| API-05 | 工作区上下文 | 已公开 | [`workspace/listContexts`、`getContext`、`getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery),带 `contextID`/`generation` 与 `rootID`;[`recentProjects.importEntries`](domains/recent-projects.md) 把带时间的项目条目并入最近项目列表 | — | [插件后端](domains/backend.md)、[最近项目导入](domains/recent-projects.md) | | API-06 | 文件读取 | 已公开 | [`workspace/readDirectory`、`stat`、`readFile`](../contract/v1/README.md#public-document-file-and-window-methods);每次最多读 128 KiB;Core 执行有界分页和逐段拒绝链接的磁盘读取 | 远程工作区不支持;桌面端需包含 API-06 Core 与桌面改动的构建,Windows 原生行为待验收 | [插件后端](domains/backend.md) | | API-07 | 文件监听 | 已公开 | `workspace/watch` 加 `subscriptions/notify`、`dispose`;上下文或会话结束时回收,溢出时要求重扫 | 远程工作区不支持;需包含 API-07 Core 与桌面改动的构建,macOS 原生事件已验证,Windows 原生验证未执行 | [插件后端](domains/backend.md) | | API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;需包含 API-08 Core 与桌面改动的构建,仅支持本地工作区 | [插件后端](domains/backend.md) | @@ -98,6 +98,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | 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-05 | `workspace/recentProjects.importEntries` | 把 1–1024 条带时间的项目条目并入宿主最近项目列表;已列出的路径保留较新时间,回答新增与移除的路径,不暴露其余历史 | `workspace.recentProjects.import` | 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 | @@ -253,7 +254,7 @@ Status meanings: | API-02 | Commands | Partial | [`ui` commands without a tool window](../contract/v1/README.md#backend-only-commands) and the `commands/didRun` notification | Registering commands at runtime, result-bearing execution | [UI](domains/ui.md) | | API-03 | Menus, keybindings, context keys, status bar | Partial | Existing command placements (`ui.commands`); `statusBar/setItem`, `removeItem` | General menus, keybinding contributions, context keys | [UI](domains/ui.md) | | API-04 | Workspace and document events | Partial | `workspace/didChangeContexts`, file events from `workspace/watch` | Document, selection, and active editor change events | [Plugin backend](domains/backend.md) | -| API-05 | Workspace contexts | Public | [`workspace/listContexts`, `getContext`, `getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery) with `contextID`/`generation` and `rootID` | — | [Plugin backend](domains/backend.md) | +| API-05 | Workspace contexts | Public | [`workspace/listContexts`, `getContext`, `getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery) with `contextID`/`generation` and `rootID`; [`recentProjects.importEntries`](domains/recent-projects.md) merges dated project entries into the recent projects list | — | [Plugin backend](domains/backend.md), [Recent projects import](domains/recent-projects.md) | | API-06 | File reads | Public | [`workspace/readDirectory`, `stat`, `readFile`](../contract/v1/README.md#public-document-file-and-window-methods); at most 128 KiB per read; Core executes bounded paging and disk reads that refuse link traversal | Remote workspaces are unsupported; the desktop needs both API-06 Core and desktop changes, and native Windows verification is pending | [Plugin backend](domains/backend.md) | | API-07 | File watching | Public | `workspace/watch` with `subscriptions/notify` and `dispose`; reclaimed when the context or session ends, with a rescan request on overflow | Remote workspaces are unsupported; requires both API-07 Core and desktop changes. Native macOS events are verified; native Windows verification was not run | [Plugin backend](domains/backend.md) | | API-08 | Search | Partial | `workspace/findFiles` and `findText`, paged and cancellable | Searches disk content only, not unsaved changes; the exact match range is `null` for now; requires both API-08 Core and desktop changes, for local workspaces only | [Plugin backend](domains/backend.md) | @@ -321,6 +322,7 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | 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-05 | `workspace/recentProjects.importEntries` | Merges 1-1024 dated project entries into the host's recent projects list; a listed path keeps the newer time, the answer names added and removed paths and reveals no other history | `workspace.recentProjects.import` | 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/domains/recent-projects.md b/shared/plugins/reference/domains/recent-projects.md new file mode 100644 index 00000000..f5d2106a --- /dev/null +++ b/shared/plugins/reference/domains/recent-projects.md @@ -0,0 +1,99 @@ +# 最近项目导入 / Recent projects import + +[中文](#中文) · [English](#english) + +## 中文 + +插件可以把其他工具最近打开的项目并入 Lithe 的最近项目列表。插件自己读取并理解来源工具的记录格式,把规范化的条目交给宿主;宿主负责合并、去重、排序、容量和持久化,插件不读写宿主的历史存储。来源格式、目录发现和路径宏展开都是插件的工具知识,Core 与宿主不按工具名加分支。 + +| 项目 | 内容 | +| --- | --- | +| 宿主方法 | `lithe/host/workspace/recentProjects.importEntries`:`{entries: [{path, lastOpenedAt}]}` → `{added, removed}` | +| 能力版本 | 无新版本;方法在现有协议内增加,经 `getCapabilities` 发现 | +| API 编号 | API-05(工作区上下文) | +| 权限 | `workspace.recentProjects.import`(单独的方法授权,不随 `workspace` 服务授予),需要 `backend` 声明 | +| 激活事件 | 没有专用激活;后端按插件自己的声明启动(如 `onWorkspaceOpen`),导入由用户运行插件命令发起 | +| Lithe 桌面端 | 接线中;未注册处理器的宿主在 `getCapabilities` 中不列出该方法 | +| 官方 SDK | Rust、Go、Node、Java 随本扩展的下一次发布提供调用封装 | + +### 请求与合并规则 + +| 部分 | 规则 | +| --- | --- | +| `entries` | 1–1024 个对象,每个恰好两个字段:`path` 与 `lastOpenedAt` | +| `path` | 非空绝对本地路径,最多 4096 UTF-8 字节,不含 NUL;是运行 Lithe 的机器上的路径 | +| `lastOpenedAt` | 非负整数,Unix 毫秒 | +| 合并 | 已列出的路径保留两者中较新的时间;新路径加入;保留列表按宿主容量排序裁剪 | +| 回答 | `added` 为新增保留的路径,`removed` 为合并与裁剪后不再保留的路径;不返回其余历史 | +| 限额 | 整个请求另受 `hostRequestBytes`(1 MiB)约束 | +| 作用域 | 列表是应用全局的,不绑定工作区上下文;请求不带 `context`,合并经宿主自己的发布到达每个窗口 | + +### 错误 + +复用既有稳定码,不新增:未知顶层选项 `plugin.host.unsupportedOption`(`-32018`,`details.option`);条目缺字段、多字段或越界 `plugin.host.invalidParams`(`-32602`);未授权 `plugin.host.permissionDenied`(`-32010`);宿主无处理器 `plugin.host.unavailable`(`-32601`);存储失败 `plugin.host.failed`(`-32603`),原子写入失败保留原列表。旧 Core 在安装时以 `plugin.permission.unknown` 拒绝未知权限。 + +### 第二个使用场景 + +任何迁移类插件都用同一方法:VS Code 的最近工作区、其他 JetBrains 产品的最近项目,各自在插件内解析自己的格式,规范化后调用本方法。宿主与 Core 不需要知道来源是谁。 + +### 契约章节 + +| 章节 | 内容 | +| --- | --- | +| [Workspace contexts and capability discovery](../../contract/v1/README.md#workspace-contexts-and-capability-discovery) | 方法表、参数、合并、授权与错误 | + +### 示例与用例 + +| 文件 | 内容 | +| --- | --- | +| [`backend/recent-projects-import.plugin.json`](../../contract/v1/fixtures/backend/recent-projects-import.plugin.json) | 声明 `workspace.recentProjects.import` 与 `window.messages` 的后端插件 | +| [`backend/function-protocol.json`](../../contract/v1/fixtures/backend/function-protocol.json) | `hostRequests` 中本方法的转发、授权与拒绝用例 | + +--- + +## English + +A plugin can merge the projects another tool recently opened into Lithe's recent projects list. The plugin reads and understands the source tool's record format itself and hands normalized entries to the host; the host owns merging, deduplication, ordering, capacity and persistence, and the plugin never reads or writes the host's history store. The source format, directory discovery and path-macro expansion are the plugin's tool knowledge; Core and the host add no branch per tool name. + +| Item | Value | +| --- | --- | +| Host method | `lithe/host/workspace/recentProjects.importEntries`: `{entries: [{path, lastOpenedAt}]}` → `{added, removed}` | +| Capability versions | No new version; the method is added within the existing protocol and discovered through `getCapabilities` | +| API IDs | API-05 (workspace contexts) | +| Permissions | `workspace.recentProjects.import` (a method grant of its own, not granted with the `workspace` service), requires a `backend` declaration | +| Activation events | None dedicated; the backend starts on the plugin's own declaration (such as `onWorkspaceOpen`), and the import is started by the user running a plugin command | +| Lithe desktop | Integration in progress; a host without a registered handler does not list the method in `getCapabilities` | +| Official SDKs | Rust, Go, Node and Java ship the call wrapper in their next release after this extension | + +### Request and merge rules + +| Part | Rule | +| --- | --- | +| `entries` | 1-1024 objects of exactly two fields each: `path` and `lastOpenedAt` | +| `path` | A non-empty absolute local path of at most 4096 UTF-8 bytes without NUL, on the machine that runs Lithe | +| `lastOpenedAt` | A non-negative integer of Unix milliseconds | +| Merge | A listed path keeps the newer of the two times; a new path is added; the retained list is ordered and capped by the host's capacity | +| Answer | `added` names the newly retained paths, `removed` the paths no longer retained after the merge and the cap; no other history is returned | +| Limits | The whole request also obeys `hostRequestBytes` (1 MiB) | +| Scope | The list is global to the application, not bound to a workspace context; the request names no `context`, and the merge reaches every window through the host's own publication | + +### Errors + +Existing stable codes are reused, none added: an unknown top-level option is `plugin.host.unsupportedOption` (`-32018`, `details.option`); an entry with a missing, extra or out-of-range field is `plugin.host.invalidParams` (`-32602`); no grant is `plugin.host.permissionDenied` (`-32010`); a host without a handler is `plugin.host.unavailable` (`-32601`); a storage failure is `plugin.host.failed` (`-32603`), and the atomic write keeps the previous list on failure. An older Core refuses the unknown permission at install with `plugin.permission.unknown`. + +### A second use case + +Any migration plugin uses the same method: VS Code's recent workspaces, other JetBrains products' recent projects, each parsing its own format inside the plugin and calling this method with normalized entries. The host and Core need not know which tool the entries came from. + +### Contract sections + +| Section | Content | +| --- | --- | +| [Workspace contexts and capability discovery](../../contract/v1/README.md#workspace-contexts-and-capability-discovery) | Method table, params, merge, grant and errors | + +### Examples and cases + +| File | Content | +| --- | --- | +| [`backend/recent-projects-import.plugin.json`](../../contract/v1/fixtures/backend/recent-projects-import.plugin.json) | A backend plugin declaring `workspace.recentProjects.import` and `window.messages` | +| [`backend/function-protocol.json`](../../contract/v1/fixtures/backend/function-protocol.json) | Forward, grant and refusal cases of the method in `hostRequests` | \ No newline at end of file diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 1139c36a..7edd2fae 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -18,6 +18,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#269](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/269)(待合入) | [@David-on-Code](https://github.com/David-on-Code) | API-05 | 现有协议内的补充 | 新增宿主方法 `workspace/recentProjects.importEntries`:后端把 1–1024 条 `{path, lastOpenedAt}`(路径非空、≤4096 UTF-8 字节、无 NUL,时间为非负 Unix 毫秒)并入宿主最近项目列表,已列出的路径保留较新时间,回答 `{added, removed}`,不暴露其余历史;列表是应用全局的,请求不带上下文,经宿主自己的历史存储原子保存并发布到各窗口。新增权限 `workspace.recentProjects.import`,是单独的方法授权,不随 `workspace` 服务授予,需要 `backend` 声明;旧 Core 安装时以 `plugin.permission.unknown` 拒绝,无处理器的宿主在 `getCapabilities` 不列出该方法,调用得 `plugin.host.unavailable`。复用既有错误码(`unsupportedOption`/`invalidParams`/`permissionDenied`/`failed`),不新增码。请求另受 `hostRequestBytes` 约束。迁移插件自己解析来源工具格式(IDEA、VS Code 等),Core 与宿主不按工具名加分支。新增 fixture `backend/recent-projects-import.plugin.json` 与 `function-protocol.json` 的 `hostRequests` 用例、专题页 `reference/domains/recent-projects.md`,四语 SDK 同步调用封装。没有新增能力版本、进程协议版本或通知。 | | [#263](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/263)(待合入) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 内的补充 | 插件可在 `configuration.providers` 的 `read` 快照里列出 Agent 能用的模型 `models`(每项 `{id, name?, provider?, efforts?, defaultEffort?, speeds?, defaultSpeed?, contextWindow?, description?}`,最多 512 个),以及 CLI 提供的推理强度 `efforts`、速度档 `speeds`(各最多 16 个,每项 `{id, name?}`)、正在用的 `effort`、`speed`(`{id, source?}`)、CLI 自己的模型菜单 `modelMenu` 和写它的文件 `targets.modelMenu`;插件不列就没有,宿主和 Core 不内置任何模型名单。`configuration.providers.operations` 新增 `setEffort`、`setSpeed`、`setModelMenu`,`setModel` 可带 `effort`、`speed`(插件也声明了 `setEffort`、`setSpeed` 时);有清单时 Core 在调用插件前检查选择在清单里、组合是模型支持的,换模型时保留的强度和速度也要新模型支持(来源层是 `default` 的不查),新增错误码 `agentProviders.unknownModel`、`agentProviders.unknownEffort`、`agentProviders.unknownSpeed`、`agentProviders.unsupportedCombination`。`setModelMenu` 只由 Core 发给插件,宿主经 `agentProviders.apply` 发它以 `agentProviders.invalidChange` 拒绝。`agentProviders.read` 总是回答 `models`,每项带 `shown`。新增宿主命令 `agentProviders.showModels {agent, show?, hide?}`:用户隐藏的模型按隐藏顺序记在资源库目录的 `models.json`(仅所有者可读写),默认全部显示,插件新加的模型也显示,插件去掉的模型保留记录,每个 Agent 最多 1024 条,超出先丢最早的、已不在清单里的;插件声明 `setModelMenu` 时 Core 经暂存副本让插件把显示的模型写进 CLI 的菜单,写失败把开关放回,不声明时开关只影响 Lithe 的选择器。新增 `agentProviders.readModelSettings {agent}` 和 `agentProviders.applyModelSettings {agent, settings}`,把开关和模型、强度、速度作为一组读出和写回(写回先全部检查,一个被拒就都不改),供以后的模型方案使用。日志 `agent.providers.change_applied`、`agent.providers.change_failed` 的 `change` 新增取值 `showModels`、`applyModelSettings`。样例见 `contract/v1/fixtures/agents/model-catalog.json`。插件函数 `edit` 新增上述操作,`read` 回答新增上述字段;没有新增插件可调用的宿主方法、通知或能力版本,四语 SDK 不改代码,只更新说明。 | ## 按协议查首次出现 @@ -116,6 +117,7 @@ | API-05 | `workspace/setDirectoryTypes` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | | API-05 | `workspace/setDirectoryMarks` | 0 | 2026-11-27 | [#215](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/215) | | API-05 | `workspace/setDirectoryMarks` | 0(接受内建 `package` role) | 2026-12-02 | [#250](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/250) | +| API-05 | `workspace/recentProjects.importEntries` | 0 | 待合入 | [#269](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/269) | | API-06 | `workspace/readDirectory` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-06 | `workspace/readDirectory` | 0(执行/校验补充) | 2026-11-23 | [#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/README.md b/shared/plugins/sdk/go/README.md index cd210919..8771e6d2 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -273,6 +273,7 @@ must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceCo | `Capabilities()`, `Supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `Workspace().ListContexts()`, `.GetContext(context)`, `.GetFolders(context)` | Workspace contexts; only `GetContext` returns, and creates, the context's `stateDirectory`. | | `Workspace().GetHostPaths(context, rootIDs...)`, `.ProcessRoots(context)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | +| `Workspace().ImportRecentProjects(entries)` | Merges dated `RecentProjectEntry` values into the host's recent projects list; answers `RecentProjectsImport` (`Added`, `Removed`). Permission `workspace.recentProjects.import`; see [Recent projects import](../../reference/domains/recent-projects.md). | | `Workspace().ReadDirectory`, `.Stat`, `.ReadFile`, `.FindFiles`, `.FindText`, `.Watch` | Files of a local context, addressed as `{ rootID, path }` from `GetFolders`. | | `Documents().List`, `.GetSnapshot`; `Editor().GetActive`, `.GetSelections`, `.ApplyEdits`, `.ReplaceSelections`, `.InsertText`, `.Open`, `.Reveal`, `.RegisterActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `Documents().Save`, `.SaveAs`, `.Close`; `Workspace().Create`, `.Rename`, `.Copy`, `.Trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 1c8a91bb..8d80ac2c 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -934,6 +934,46 @@ func (w *Workspace) GetHostPaths(context WorkspaceContext, rootIDs ...string) ([ return hostFolders(result) } +// RecentProjectEntry is one dated project entry of +// [Workspace.ImportRecentProjects]: a local path on the machine that runs +// Lithe and when the source tool last opened it, in Unix milliseconds. +type RecentProjectEntry struct { + Path string `json:"path"` + LastOpenedAt int64 `json:"lastOpenedAt"` +} + +// RecentProjectsImport is the answer of [Workspace.ImportRecentProjects]: +// the paths newly retained and the paths no longer retained after the merge +// and the host's capacity. +type RecentProjectsImport struct { + Added []string `json:"added"` + Removed []string `json:"removed"` +} + +// ImportRecentProjects merges 1-1024 dated entries into the host's recent +// projects list, the list the welcome screen shows. A path already listed +// keeps the newer of the two times; the host orders, caps, persists and +// publishes the list. It needs the workspace.recentProjects.import +// permission, a method grant of its own, so check +// Supports("lithe/host/workspace/recentProjects.importEntries") first. The +// plugin normalizes its source tool's records itself; the entries are local +// paths on this machine. +func (w *Workspace) ImportRecentProjects(entries []RecentProjectEntry) (RecentProjectsImport, error) { + if len(entries) == 0 || len(entries) > 1024 { + return RecentProjectsImport{}, newSdkError("sdk.host.invalidParams", "entries is 1-1024 recent project entries.") + } + for _, entry := range entries { + if entry.Path == "" || len(entry.Path) > 4096 || strings.ContainsRune(entry.Path, 0) || entry.LastOpenedAt < 0 { + return RecentProjectsImport{}, newSdkError("sdk.host.invalidParams", "A recent project entry is a 1-4096 byte path without NUL and a non-negative millisecond time.") + } + } + result, err := w.host.request(methodRecentProjectsImport, map[string]any{"entries": entries}) + if err != nil { + return RecentProjectsImport{}, err + } + return recentProjectsImport(result) +} + // ProcessRoot is a root of a context as a process started for it names its // working directory: Path for a local context, HostPath for a remote one. // The other one is empty. @@ -1008,6 +1048,31 @@ func invalidHostPaths() *SdkError { return newSdkError("sdk.host.invalidResult", "The host answered getHostPaths without folders of a root ID and an absolute host path.") } +// recentProjectsImport reads { added, removed } path lists of an import answer. +func recentProjectsImport(result any) (RecentProjectsImport, error) { + paths := func(key string) ([]string, bool) { + items, ok := field(result, key).([]any) + if !ok { + return nil, false + } + list := make([]string, len(items)) + for i, item := range items { + path, ok := item.(string) + if !ok { + return nil, false + } + list[i] = path + } + return list, true + } + added, okAdded := paths("added") + removed, okRemoved := paths("removed") + if !okAdded || !okRemoved { + return RecentProjectsImport{}, newSdkError("sdk.host.invalidResult", "The host answered recentProjects.importEntries without added and removed path lists.") + } + return RecentProjectsImport{Added: added, Removed: removed}, nil +} + // localFolders reads [{ rootID, path }] of a local context's folders. func localFolders(value any) ([]ProcessRoot, error) { items, ok := value.([]any) diff --git a/shared/plugins/sdk/go/lithe/host_services_test.go b/shared/plugins/sdk/go/lithe/host_services_test.go index cf2c5d80..3c8c0626 100644 --- a/shared/plugins/sdk/go/lithe/host_services_test.go +++ b/shared/plugins/sdk/go/lithe/host_services_test.go @@ -914,6 +914,55 @@ func TestHostPathRootIDsCoreRefusesFailLocallyAndTheAnswerHoldsHostPaths(t *test s.close() } +func TestRecentProjectsImportSendsBoundedEntriesAndReadsAddedAndRemoved(t *testing.T) { + backend := lithe.NewBackend("test-backend") + workspace := backend.Handle().Host().Workspace() + s := startSession(t, backend, []any{0}) + + for _, bad := range []lithe.RecentProjectEntry{ + {Path: "", LastOpenedAt: 0}, + {Path: strings.Repeat("p", 4097), LastOpenedAt: 0}, + {Path: "/projects/a\x00b", LastOpenedAt: 0}, + {Path: "/projects/atlas", LastOpenedAt: -1}, + } { + if _, err := workspace.ImportRecentProjects([]lithe.RecentProjectEntry{bad}); code(err) != "sdk.host.invalidParams" { + t.Errorf("%+v: %v", bad, err) + } + } + if _, err := workspace.ImportRecentProjects(nil); code(err) != "sdk.host.invalidParams" { + t.Errorf("empty entries: %v", err) + } + tooMany := make([]lithe.RecentProjectEntry, 1025) + for i := range tooMany { + tooMany[i] = lithe.RecentProjectEntry{Path: fmt.Sprintf("/projects/%d", i), LastOpenedAt: int64(i)} + } + if _, err := workspace.ImportRecentProjects(tooMany); code(err) != "sdk.host.invalidParams" { + t.Errorf("1025 entries: %v", err) + } + s.assertQuiet() + + entries := []lithe.RecentProjectEntry{ + {Path: "/projects/atlas", LastOpenedAt: 1785683892804}, + {Path: "/projects/notebook", LastOpenedAt: 1785650905947}, + } + asking := background(func() (lithe.RecentProjectsImport, error) { return workspace.ImportRecentProjects(entries) }) + request := s.take("lithe/host/workspace/recentProjects.importEntries") + eq(t, request["params"], encode(t, map[string]any{"entries": entries})) + s.reply(request, map[string]any{"added": []any{"/projects/atlas"}, "removed": []any{"/projects/gone"}}) + result := done(t, asking) + must(t, result.err) + eq(t, result.value, `{"added":["/projects/atlas"],"removed":["/projects/gone"]}`) + + for _, answer := range []string{`{}`, `{"added": []}`, `{"added": [1], "removed": []}`} { + asking := background(func() (lithe.RecentProjectsImport, error) { return workspace.ImportRecentProjects(entries) }) + s.reply(s.take("lithe/host/workspace/recentProjects.importEntries"), j(t, answer)) + if err := done(t, asking).err; code(err) != "sdk.host.invalidResult" { + t.Errorf("%s: %v", answer, err) + } + } + s.close() +} + func TestProcessRootsReadsALocalContextAndAsksTheHostOnlyForARemoteOne(t *testing.T) { backend := lithe.NewBackend("test-backend") workspace := backend.Handle().Host().Workspace() diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go index dabbda70..f0dd575a 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -40,6 +40,7 @@ const ( methodGetContext = "lithe/host/workspace/getContext" methodGetFolders = "lithe/host/workspace/getFolders" methodGetHostPaths = "lithe/host/workspace/getHostPaths" + methodRecentProjectsImport = "lithe/host/workspace/recentProjects.importEntries" methodReadDirectory = "lithe/host/workspace/readDirectory" methodStat = "lithe/host/workspace/stat" methodReadFile = "lithe/host/workspace/readFile" diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 6d3b2a71..8352a33f 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -296,6 +296,7 @@ call. See the [build configuration contract](../../contract/v1/README.md#build-c | `workspace().listContexts()`, `.getContext(context)`, `.getFolders(context)` | Workspace contexts; only `getContext` returns, and creates, the context's `stateDirectory`. | | `workspace().readDirectory`, `.stat`, `.readFile`, `.findFiles`, `.findText`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `getFolders`. | | `workspace().getHostPaths(context, rootIds)`, `.processRoots(fullContext)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | +| `workspace().importRecentProjects(entries)` | Merges dated `RecentProjectEntry` values into the host's recent projects list; answers `RecentProjectsImport` (`added()`, `removed()`). Permission `workspace.recentProjects.import`; see [Recent projects import](../../reference/domains/recent-projects.md). | | `documents().list`, `.getSnapshot`; `editor().getActive`, `.getSelections`, `.applyEdits`, `.replaceSelections`, `.insertText`, `.open`, `.reveal`, `.registerActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `documents().save`, `.saveAs`, `.close`; `workspace().create`, `.rename`, `.copy`, `.trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | | `preview().openHtml`, `browser().openExternal`, `window().showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | 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 187fcc09..7f5e8911 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 @@ -165,6 +165,65 @@ public HostPath hostPath() { } } + /** + * One dated project entry of {@link Workspace#importRecentProjects}: a + * local path on the machine that runs Lithe and when the source tool last + * opened it, in Unix milliseconds. + */ + public static final class RecentProjectEntry { + private final String path; + private final long lastOpenedAt; + + /** A non-empty path of at most 4096 UTF-8 bytes without NUL, and a non-negative time. */ + public RecentProjectEntry(String path, long lastOpenedAt) { + if (path == null || path.isEmpty() + || path.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 4096 + || path.indexOf('\0') >= 0 || lastOpenedAt < 0) { + throw new PluginSdkError("sdk.host.invalidParams", + "A recent project entry is a 1-4096 byte path without NUL and a non-negative millisecond time."); + } + this.path = path; + this.lastOpenedAt = lastOpenedAt; + } + + public String path() { + return path; + } + + public long lastOpenedAt() { + return lastOpenedAt; + } + + Map toMap() { + Map value = new LinkedHashMap<>(); + value.put("path", path); + value.put("lastOpenedAt", lastOpenedAt); + return value; + } + } + + /** + * The answer of {@link Workspace#importRecentProjects}: the paths newly + * retained and the paths no longer retained after the merge and the cap. + */ + public static final class RecentProjectsImport { + private final List added; + private final List removed; + + RecentProjectsImport(List added, List removed) { + this.added = added; + this.removed = removed; + } + + public List added() { + return added; + } + + public List removed() { + return removed; + } + } + /** * A root of a context as a process started for it names its working * directory, from {@link Workspace#processRoots}: {@link #path()} for a @@ -476,6 +535,32 @@ public CompletableFuture> getHostPaths(Map context, return channel.request(Protocol.HOST_WORKSPACE_GET_HOST_PATHS, message, scope).thenApply(Host::hostFolders); } + /** + * Merges 1-1024 dated entries into the host's recent projects list, + * the list the welcome screen shows; a listed path keeps the newer of + * the two times, and the host orders, caps, persists and publishes the + * list. It needs the {@code workspace.recentProjects.import} + * permission, a method grant of its own. The plugin normalizes its + * source tool's records itself; the entries are local paths on this + * machine. + */ + public CompletableFuture importRecentProjects(List entries) { + if (entries == null || entries.isEmpty() || entries.size() > 1024) { + return failed(new PluginSdkError("sdk.host.invalidParams", "entries is 1-1024 recent project entries.")); + } + List wire = new ArrayList<>(entries.size()); + for (RecentProjectEntry entry : entries) { + if (entry == null) { + return failed(new PluginSdkError("sdk.host.invalidParams", "entries is 1-1024 recent project entries.")); + } + wire.add(entry.toMap()); + } + Map params = new LinkedHashMap<>(); + params.put("entries", wire); + return channel.request(Protocol.HOST_WORKSPACE_RECENT_PROJECTS_IMPORT, params, scope) + .thenApply(Host::recentProjectsImport); + } + /** * The roots of a full context from {@link #listContexts} or * {@link #getContext} as a process started for it names its working @@ -946,6 +1031,32 @@ private static PluginSdkError invalidHostPaths() { "The host answered getHostPaths without folders of a root ID and an absolute host path."); } + /** {@code { added, removed }} path lists of an import answer. */ + private static RecentProjectsImport recentProjectsImport(Object result) { + Object added = result instanceof Map ? ((Map) result).get("added") : null; + Object removed = result instanceof Map ? ((Map) result).get("removed") : null; + if (!(added instanceof List) || !(removed instanceof List)) { + throw invalidRecentProjectsImport(); + } + return new RecentProjectsImport(stringList((List) added), stringList((List) removed)); + } + + private static List stringList(List items) { + List answer = new ArrayList<>(items.size()); + for (Object item : items) { + if (!(item instanceof String)) { + throw invalidRecentProjectsImport(); + } + answer.add((String) item); + } + return Collections.unmodifiableList(answer); + } + + private static PluginSdkError invalidRecentProjectsImport() { + return new PluginSdkError("sdk.host.invalidResult", + "The host answered recentProjects.importEntries without added and removed path lists."); + } + /** {@code [{ rootID, path }]} of a {@code local} context's folders. */ private static List localFolders(Object folders) { if (!(folders instanceof List)) { 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 3d14e1b2..7d6a65b5 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 @@ -65,6 +65,7 @@ public final class Protocol { public static final String HOST_WORKSPACE_GET_CONTEXT = "lithe/host/workspace/getContext"; public static final String HOST_WORKSPACE_GET_FOLDERS = "lithe/host/workspace/getFolders"; public static final String HOST_WORKSPACE_GET_HOST_PATHS = "lithe/host/workspace/getHostPaths"; + public static final String HOST_WORKSPACE_RECENT_PROJECTS_IMPORT = "lithe/host/workspace/recentProjects.importEntries"; public static final String HOST_WORKSPACE_READ_DIRECTORY = "lithe/host/workspace/readDirectory"; public static final String HOST_WORKSPACE_STAT = "lithe/host/workspace/stat"; public static final String HOST_WORKSPACE_READ_FILE = "lithe/host/workspace/readFile"; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java index de308541..15a7f88b 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/HostTest.java @@ -656,6 +656,53 @@ void hostPathRootIdsCoreRefusesFailLocallyAndTheAnswerHoldsHostPaths() { host.close(); } + @Test + void recentProjectsImportSendsBoundedEntriesAndReadsAddedAndRemoved() { + Backend backend = Backend.create(null, null); + TestHost host = session(backend); + Host.Workspace workspace = backend.host().workspace(); + Set taken = new HashSet<>(); + int before = host.messages().size(); + + for (Object[] bad : new Object[][]{{"", 0L}, {new String(new char[4097]).replace('\0', 'p'), 0L}, {"/projects/a\0b", 0L}, {"/projects/atlas", -1L}}) { + PluginSdkError error = assertThrows(PluginSdkError.class, + () -> new Host.RecentProjectEntry((String) bad[0], (Long) bad[1])); + assertEquals("sdk.host.invalidParams", error.code()); + } + assertEquals("sdk.host.invalidParams", code(workspace.importRecentProjects(Arrays.asList()))); + List tooMany = new ArrayList<>(); + for (int index = 0; index < 1025; index++) { + tooMany.add(new Host.RecentProjectEntry("/projects/" + index, index)); + } + assertEquals("sdk.host.invalidParams", code(workspace.importRecentProjects(tooMany))); + assertEquals(before, host.messages().size()); + + List entries = Arrays.asList( + new Host.RecentProjectEntry("/projects/atlas", 1785683892804L), + new Host.RecentProjectEntry("/projects/notebook", 1785650905947L)); + CompletableFuture asking = workspace.importRecentProjects(entries); + Map request = nextRequest(host, Protocol.HOST_WORKSPACE_RECENT_PROJECTS_IMPORT, taken); + List wire = new ArrayList<>(); + for (Host.RecentProjectEntry entry : entries) { + wire.add(map("path", entry.path(), "lastOpenedAt", entry.lastOpenedAt())); + } + assertEquals(map("entries", wire), request.get("params")); + host.send(map("id", request.get("id"), "result", + map("added", Arrays.asList("/projects/atlas"), "removed", Arrays.asList("/projects/gone")))); + Host.RecentProjectsImport answer = value(asking); + assertEquals(Arrays.asList("/projects/atlas"), answer.added()); + assertEquals(Arrays.asList("/projects/gone"), answer.removed()); + + for (Object result : Arrays.asList(map(), map("added", Arrays.asList()), + map("added", Arrays.asList(1L), "removed", Arrays.asList()))) { + CompletableFuture again = workspace.importRecentProjects(entries); + Map againRequest = nextRequest(host, Protocol.HOST_WORKSPACE_RECENT_PROJECTS_IMPORT, taken); + host.send(map("id", againRequest.get("id"), "result", result)); + assertEquals("sdk.host.invalidResult", code(again), String.valueOf(result)); + } + host.close(); + } + @Test void processRootsReadsALocalContextAndAsksTheHostOnlyForARemoteOne() { Backend backend = Backend.create(null, null); diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 28da19fd..4d17896b 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -289,6 +289,7 @@ backend.onCommand('db.refresh', async ({ workspaceContext }) => { | `capabilities()`, `supports(method)` | What this session may call, from `lithe/host/getCapabilities` (asked once). | | `workspace.listContexts()`, `.getContext(context)`, `.getFolders(context)` | Workspace contexts; only `getContext` returns, and creates, the context's `stateDirectory`. | | `workspace.getHostPaths(context, { rootIDs? })`, `.processRoots(context)` | The root folders of a remote context on the remote host, as `HostPath` values; `processRoots` gives the path a process uses for either authority. See [Remote workspaces](#remote-workspaces). | +| `workspace.importRecentProjects(entries)` | Merges dated `{ path, lastOpenedAt }` entries into the host's recent projects list; answers `{ added, removed }`. Permission `workspace.recentProjects.import`; see [Recent projects import](../../reference/domains/recent-projects.md). | | `workspace.readDirectory`, `.stat`, `.readFile`, `.findFiles`, `.findText`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `getFolders`. | | `documents.list`, `.getSnapshot`; `editor.getActive`, `.getSelections`, `.applyEdits`, `.replaceSelections`, `.insertText`, `.open`, `.reveal`, `.registerActions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `documents.save`, `.saveAs`, `.close`; `workspace.create`, `.rename`, `.copy`, `.trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index 6a58044c..4d0ff3e2 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -289,6 +289,18 @@ export function createHost(channel, callSignal, parentOperationId) { getFolders: async (context, options) => request(HOST_METHODS.workspaceGetFolders, { context: contextReference(context) }, options), getHostPaths, + /** + * Merges 1-1024 dated `{ path, lastOpenedAt }` entries into the host's + * recent projects list; answers `{ added, removed }` path lists. A + * listed path keeps the newer time. Permission + * `workspace.recentProjects.import`, a method grant of its own. + */ + importRecentProjects: async (entries, options) => { + checkRecentProjectEntries(entries); + return recentProjectsImport( + await request(HOST_METHODS.workspaceRecentProjectsImport, { entries }, options), + ); + }, processRoots: async (context, options) => { const kind = context?.authority?.kind; if (kind === 'local') return { folders: localFolders(context.folders) }; @@ -510,6 +522,41 @@ function localFolders(folders) { return folders.map(({ rootID, path }) => ({ rootID, path })); } +/** 1-1024 entries of a 1-4096 byte path without NUL and a non-negative millisecond time. */ +function checkRecentProjectEntries(entries) { + const valid = + Array.isArray(entries) && + entries.length > 0 && + entries.length <= LIMITS.maxRecentProjectImportEntries && + entries.every( + (entry) => + typeof entry?.path === 'string' && + entry.path.length > 0 && + Buffer.byteLength(entry.path) <= LIMITS.maxRecentProjectPathBytes && + !entry.path.includes('\0') && + Number.isInteger(entry?.lastOpenedAt) && + entry.lastOpenedAt >= 0, + ); + if (!valid) { + throw new PluginSdkError( + 'sdk.host.invalidParams', + 'entries is 1-1024 objects of a 1-4096 byte path without NUL and a non-negative millisecond time.', + ); + } +} + +/** `{ added, removed }` path lists of an import answer. */ +function recentProjectsImport(result) { + const paths = (value) => Array.isArray(value) && value.every((path) => typeof path === 'string'); + if (!paths(result?.added) || !paths(result?.removed)) { + throw new PluginSdkError( + 'sdk.host.invalidResult', + 'The host answered recentProjects.importEntries without added and removed path lists.', + ); + } + return { added: [...result.added], removed: [...result.removed] }; +} + function checkCredentialKey(key) { if (!isCredentialKey(key)) { throw new PluginSdkError( diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 4cf18a62..3ed03593 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -99,6 +99,23 @@ export interface LocalFolder { path: string; } +/** + * One dated project entry of `workspace.importRecentProjects`: a local path + * on the machine that runs Lithe and when the source tool last opened it, in + * Unix milliseconds. + */ +export interface RecentProjectEntry { + path: string; + lastOpenedAt: number; +} + +/** The answer of `workspace.importRecentProjects`: paths newly retained and + * paths no longer retained after the merge and the host's capacity. */ +export interface RecentProjectsImport { + added: string[]; + removed: string[]; +} + /** One open workspace in one window. */ export interface WorkspaceContext extends ContextReference { name: string; @@ -290,6 +307,16 @@ export interface Host { params?: { rootIDs?: string[] }, options?: HostRequestOptions, ): Promise<{ folders: HostFolder[] }>; + /** + * Merges 1-1024 dated entries into the host's recent projects list, the + * list the welcome screen shows; a listed path keeps the newer time. + * Permission `workspace.recentProjects.import`, a method grant of its own. + * The plugin normalizes its source tool's records itself. + */ + importRecentProjects( + entries: RecentProjectEntry[], + options?: HostRequestOptions, + ): Promise; /** * The path a process uses for each root of a full context: `path` of a * `local` context, without asking the host, or `hostPath` from @@ -1174,6 +1201,8 @@ export const LIMITS: Readonly<{ maxCredentialSecretBytes: number; maxPendingHostRequests: number; maxHostPathRoots: number; + maxRecentProjectImportEntries: number; + maxRecentProjectPathBytes: number; relayDefaultTimeoutMilliseconds: number; relayMaxTimeoutMilliseconds: number; maxParentOperationIdBytes: number; diff --git a/shared/plugins/sdk/node/src/protocol.mjs b/shared/plugins/sdk/node/src/protocol.mjs index 8abd1048..ebb78d8d 100644 --- a/shared/plugins/sdk/node/src/protocol.mjs +++ b/shared/plugins/sdk/node/src/protocol.mjs @@ -73,6 +73,7 @@ export const HOST_METHODS = Object.freeze({ workspaceGetContext: 'lithe/host/workspace/getContext', workspaceGetFolders: 'lithe/host/workspace/getFolders', workspaceGetHostPaths: 'lithe/host/workspace/getHostPaths', + workspaceRecentProjectsImport: 'lithe/host/workspace/recentProjects.importEntries', workspaceReadDirectory: 'lithe/host/workspace/readDirectory', workspaceStat: 'lithe/host/workspace/stat', workspaceReadFile: 'lithe/host/workspace/readFile', @@ -241,6 +242,8 @@ export const LIMITS = Object.freeze({ maxCredentialSecretBytes: 16 * 1024, maxPendingHostRequests: 16, maxHostPathRoots: 256, + maxRecentProjectImportEntries: 1024, + maxRecentProjectPathBytes: 4096, // The relay's bounds are Core's to enforce; the SDK only names them. relayDefaultTimeoutMilliseconds: 60000, relayMaxTimeoutMilliseconds: 600000, diff --git a/shared/plugins/sdk/node/test/host.test.mjs b/shared/plugins/sdk/node/test/host.test.mjs index 294a1b01..9f9c7ac8 100644 --- a/shared/plugins/sdk/node/test/host.test.mjs +++ b/shared/plugins/sdk/node/test/host.test.mjs @@ -163,6 +163,48 @@ test('host paths: root IDs Core refuses fail locally, and the answer holds HostP await host.close(); }); +test('recent projects import: bounded entries fail locally, and the answer holds added and removed', async () => { + const { backend, host } = await session(); + const taken = new Set(); + const method = 'lithe/host/workspace/recentProjects.importEntries'; + const entries = [ + { path: '/projects/atlas', lastOpenedAt: 1785683892804 }, + { path: '/projects/notebook', lastOpenedAt: 1785650905947 }, + ]; + + for (const bad of [ + [], + [{ path: '', lastOpenedAt: 0 }], + [{ path: 'p'.repeat(LIMITS.maxRecentProjectPathBytes + 1), lastOpenedAt: 0 }], + [{ path: '/projects/a\0b', lastOpenedAt: 0 }], + [{ path: '/projects/atlas', lastOpenedAt: -1 }], + [{ path: '/projects/atlas', lastOpenedAt: 1.5 }], + [{ path: '/projects/atlas' }], + Array.from({ length: LIMITS.maxRecentProjectImportEntries + 1 }, (_, i) => ({ path: `/projects/${i}`, lastOpenedAt: i })), + ]) { + const before = host.messages.length; + await assert.rejects( + backend.host.workspace.importRecentProjects(bad), + (error) => error.code === 'sdk.host.invalidParams', + JSON.stringify(bad).slice(0, 80), + ); + assert.equal(host.messages.length, before); + } + + const asking = backend.host.workspace.importRecentProjects(entries); + const request = await nextRequest(host, method, taken); + assert.deepEqual(request.params, { entries }); + host.send({ id: request.id, result: { added: ['/projects/atlas'], removed: ['/projects/gone'] } }); + assert.deepEqual(await asking, { added: ['/projects/atlas'], removed: ['/projects/gone'] }); + + for (const result of [{}, { added: [] }, { added: [1], removed: [] }]) { + const asking = backend.host.workspace.importRecentProjects(entries); + host.send({ id: (await nextRequest(host, method, taken)).id, result }); + await assert.rejects(asking, (error) => error.code === 'sdk.host.invalidResult', JSON.stringify(result)); + } + await host.close(); +}); + test('processRoots reads a local context and asks the host only for a remote one', async () => { const { backend, host } = await session(); const before = host.messages.length; diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index b9ac12ce..3e56364f 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -471,6 +471,7 @@ backend | `workspace().list_contexts()`, `.get_context(&context)`, `.get_folders(&context)` | Workspace contexts; only `get_context` returns, and creates, the context's `stateDirectory`. | | `workspace().read_directory`, `.stat`, `.read_file`, `.find_files`, `.find_text`, `.watch` | Files of a local context, addressed as `{ rootID, path }` from `get_folders`. | | `workspace().get_host_paths(&context, root_ids)`, `.process_roots(&full_context)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | +| `workspace().import_recent_projects(&entries)` | Merges dated `RecentProjectEntry` values into the host's recent projects list; answers `RecentProjectsImport` (`added`, `removed`). Permission `workspace.recentProjects.import`; see [Recent projects import](../../reference/domains/recent-projects.md). | | `documents().list`, `.get_snapshot`; `editor().get_active`, `.get_selections`, `.apply_edits`, `.replace_selections`, `.insert_text`, `.open`, `.reveal`, `.register_actions` | Live documents and editors. Edits name the `expectedVersion` they were computed against. | | `documents().save`, `.save_as`, `.close`; `workspace().create`, `.rename`, `.copy`, `.trash` | Saves, closes, and file changes, with the `documents.save` and `workspace.files.write` permissions. Nothing is overwritten, discarded, or deleted permanently; see [saving documents and changing files](../../contract/v1/README.md#saving-documents-and-changing-files). | | `preview().open_html`, `browser().open_external`, `window().show_information`, `.show_warning`, `.show_error` | Preview, browser, and messages. | diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index dc7b34e0..81167921 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -940,6 +940,31 @@ impl Workspace { } } + /// Merges dated project entries into the host's recent projects list, + /// the list the welcome screen shows: `{ added, removed }`. Permission + /// `workspace.recentProjects.import`, a method grant of its own. A path + /// already listed keeps the newer of the two times; the host orders and + /// caps the retained list and publishes it to every window. The entries + /// are local paths on the machine that runs Lithe; the plugin normalizes + /// its source tool's records itself. + pub fn import_recent_projects( + &self, + entries: &[RecentProjectEntry], + ) -> Result { + if entries.is_empty() || entries.len() > MAX_RECENT_PROJECT_IMPORT_ENTRIES { + return Err(SdkError::new( + "sdk.host.invalidParams", + "entries is 1-1024 recent project entries.", + )); + } + let entries: Vec = entries.iter().map(RecentProjectEntry::to_value).collect(); + recent_projects_import( + &self + .host + .request(methods::WORKSPACE_RECENT_PROJECTS_IMPORT, json!({ "entries": entries }))?, + ) + } + /// `params`: `resource, cursor?, limit?`. pub fn read_directory( &self, @@ -1124,6 +1149,89 @@ fn host_folders(result: &Value) -> Result, SdkError> { .collect() } +/// Most entries one [`Workspace::import_recent_projects`] call may carry. +const MAX_RECENT_PROJECT_IMPORT_ENTRIES: usize = 1024; + +/// Longest path one imported entry may name, in UTF-8 bytes. +const MAX_RECENT_PROJECT_PATH_BYTES: usize = 4096; + +/// One dated project entry of [`Workspace::import_recent_projects`]: a local +/// path on the machine that runs Lithe and when the source tool last opened +/// it, in Unix milliseconds. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecentProjectEntry { + path: String, + last_opened_at: i64, +} + +impl RecentProjectEntry { + /// A non-empty path of at most 4096 UTF-8 bytes without NUL, and a + /// non-negative millisecond time. + pub fn new(path: impl Into, last_opened_at: i64) -> Result { + let path = path.into(); + if path.is_empty() + || path.len() > MAX_RECENT_PROJECT_PATH_BYTES + || path.contains('\0') + || last_opened_at < 0 + { + return Err(SdkError::new( + "sdk.host.invalidParams", + "A recent project entry is a 1-4096 byte path without NUL and a non-negative millisecond time.", + )); + } + Ok(Self { path, last_opened_at }) + } + + pub fn path(&self) -> &str { + &self.path + } + + pub fn last_opened_at(&self) -> i64 { + self.last_opened_at + } + + fn to_value(&self) -> Value { + json!({ "path": self.path, "lastOpenedAt": self.last_opened_at }) + } +} + +/// The answer of [`Workspace::import_recent_projects`]: the paths newly +/// retained and the paths no longer retained after the merge and the cap. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecentProjectsImport { + added: Vec, + removed: Vec, +} + +impl RecentProjectsImport { + pub fn added(&self) -> &[String] { + &self.added + } + + pub fn removed(&self) -> &[String] { + &self.removed + } +} + +/// `{ added, removed }` of an import answer; both are lists of paths. +fn recent_projects_import(result: &Value) -> Result { + let invalid = || { + SdkError::new( + "sdk.host.invalidResult", + "The host answered recentProjects.importEntries without added and removed path lists.", + ) + }; + let paths = |key: &str| -> Result, SdkError> { + result[key] + .as_array() + .ok_or_else(invalid)? + .iter() + .map(|path| path.as_str().map(str::to_string).ok_or_else(invalid)) + .collect() + }; + Ok(RecentProjectsImport { added: paths("added")?, removed: paths("removed")? }) +} + /// `[{ rootID, path }]` of a `local` context's folders. fn local_folders(folders: &Value) -> Result, SdkError> { let invalid = || { diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 05eb54f9..54fc2aba 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -71,8 +71,9 @@ pub use error::{ }; pub use host::{ Browser, Clipboard, Credentials, Documents, Editor, Event, Functions, Host, HostFolder, - HostPath, Network, Output, Preview, ProcessRoot, Progress, StatusBar, Subscription, - Subscriptions, Terminal, Tests, Views, Window, Workspace, WorkspaceContext, + HostPath, Network, Output, Preview, ProcessRoot, Progress, RecentProjectEntry, + RecentProjectsImport, StatusBar, Subscription, Subscriptions, Terminal, Tests, Views, Window, + Workspace, WorkspaceContext, }; pub use process::{ProcessOutput, RunError, RunOptions}; pub use protocol::{is_command_id, is_credential_key, is_function_id, is_plugin_error_code}; diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index e1a20ed2..abfd8367 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -54,6 +54,8 @@ pub(crate) mod methods { pub const WORKSPACE_GET_CONTEXT: &str = "lithe/host/workspace/getContext"; pub const WORKSPACE_GET_FOLDERS: &str = "lithe/host/workspace/getFolders"; pub const WORKSPACE_GET_HOST_PATHS: &str = "lithe/host/workspace/getHostPaths"; + pub const WORKSPACE_RECENT_PROJECTS_IMPORT: &str = + "lithe/host/workspace/recentProjects.importEntries"; pub const WORKSPACE_READ_DIRECTORY: &str = "lithe/host/workspace/readDirectory"; pub const WORKSPACE_STAT: &str = "lithe/host/workspace/stat"; pub const WORKSPACE_READ_FILE: &str = "lithe/host/workspace/readFile"; diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs index 4b2fd136..01cda77b 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs @@ -925,6 +925,82 @@ fn host_path_root_ids_core_refuses_fail_locally_and_the_answer_holds_host_paths( session.close(); } +#[test] +fn recent_projects_import_sends_bounded_entries_and_reads_added_and_removed() { + use lithe_plugin_sdk::{RecentProjectEntry, RecentProjectsImport}; + let backend = Backend::new("test-backend"); + let host = backend.handle().host(); + let mut session = Session::start(backend); + + // The constructor refuses what Core would refuse, before any request. + for bad in [ + RecentProjectEntry::new("", 0), + RecentProjectEntry::new("p".repeat(4097), 0), + RecentProjectEntry::new("/projects/a\0b", 0), + RecentProjectEntry::new("/projects/atlas", -1), + ] { + assert_eq!(code(bad), "sdk.host.invalidParams"); + } + assert_eq!( + code(host.workspace().import_recent_projects(&[])), + "sdk.host.invalidParams" + ); + let too_many: Vec = (0..1025) + .map(|i| RecentProjectEntry::new(format!("/projects/{i}"), i).unwrap()) + .collect(); + assert_eq!( + code(host.workspace().import_recent_projects(&too_many)), + "sdk.host.invalidParams" + ); + session.host.assert_quiet(); + + // The fixture's forward case round-trips through the typed call. + let case = cases(&fixture(), "hostRequests") + .into_iter() + .find(|case| { + case["method"] == "lithe/host/workspace/recentProjects.importEntries" + && case["expected"]["forward"] == "workspace" + }) + .expect("the fixture has a forward case"); + let entries: Vec = case["params"]["entries"] + .as_array() + .unwrap() + .iter() + .map(|entry| { + RecentProjectEntry::new( + entry["path"].as_str().unwrap(), + entry["lastOpenedAt"].as_i64().unwrap(), + ) + .unwrap() + }) + .collect(); + let asking = { + let (host, entries) = (host.clone(), entries.clone()); + background(move || host.workspace().import_recent_projects(&entries)) + }; + let request = session.take("lithe/host/workspace/recentProjects.importEntries"); + assert_eq!(&request["params"], &case["params"]); + session.reply( + &request, + json!({ "added": ["/projects/atlas"], "removed": ["/projects/gone"] }), + ); + let answer: RecentProjectsImport = done(&asking).unwrap(); + assert_eq!(answer.added(), ["/projects/atlas"]); + assert_eq!(answer.removed(), ["/projects/gone"]); + + // An answer without both path lists is refused. + for answer in [json!({}), json!({ "added": [] }), json!({ "added": [1], "removed": [] })] { + let asking = { + let (host, entries) = (host.clone(), entries.clone()); + background(move || host.workspace().import_recent_projects(&entries)) + }; + let request = session.take("lithe/host/workspace/recentProjects.importEntries"); + session.reply(&request, answer.clone()); + assert_eq!(code(done(&asking)), "sdk.host.invalidResult", "{answer}"); + } + session.close(); +} + #[test] fn process_roots_reads_a_local_context_and_asks_the_host_only_for_a_remote_one() { let backend = Backend::new("test-backend");