From 2e413f65415a0b2af6972c73d4b1b24c1da6406a Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Mon, 23 Nov 2026 16:57:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(plugins):=20=E6=8F=92=E4=BB=B6=E5=90=8E?= =?UTF-8?q?=E7=AB=AF=E5=8F=AF=E4=BF=9D=E5=AD=98=E3=80=81=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E6=96=87=E6=A1=A3=E5=92=8C=E6=96=B0=E5=BB=BA=E3=80=81=E9=87=8D?= =?UTF-8?q?=E5=91=BD=E5=90=8D=E3=80=81=E5=A4=8D=E5=88=B6=E3=80=81=E7=A7=BB?= =?UTF-8?q?=E5=88=B0=E5=BA=9F=E7=BA=B8=E7=AF=93=EF=BC=88API-11=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增宿主方法 documents/save、saveAs、close(新权限 documents.save)和 workspace/create、rename、copy、trash(新权限 workspace.files.write)。每个权限只授予 自己的方法,聚合的 workspace 授权和 documents.read 都不授予它们。 - 宿主经文档所有者保存;close 先保存再关闭,从不丢弃修改;目标已存在时失败、从不覆盖; trash 只移到系统废纸篓;需要用户选择的情形直接拒绝,不弹询问。 - 新增失败码 plugin.host.alreadyExists(-32080)和 plugin.host.diskChanged(-32081), 中转与宿主错误表保持一码一义。 - 契约 README 新增“保存文档与改动文件”一节,清单 schema、fixture、API 总表、领域页、 后端指南和协议更新记录同步;四个官方 SDK 新增 7 个方法的封装和两个失败码。 --- rust/crates/plugin-rpc/src/failures.rs | 4 + rust/crates/plugin-rpc/src/host_requests.rs | 50 +++++++- rust/crates/plugin-rpc/src/lib.rs | 113 ++++++++++++++++++ rust/fixtures/plugins/host-api-v1.json | 20 ++++ shared/plugins/contract/v1/README.md | 72 +++++++++++ .../fixtures/backend/function-protocol.json | 8 +- .../contract/v1/plugin-manifest.schema.json | 4 +- .../guides/plugin-backend-workspace.md | 10 ++ shared/plugins/reference/api-catalog.md | 18 ++- shared/plugins/reference/domains/backend.md | 14 ++- shared/plugins/reference/domains/editor.md | 10 +- .../plugins/reference/protocol-changelog.md | 8 ++ shared/plugins/sdk/go/README.md | 3 +- shared/plugins/sdk/go/lithe/errors.go | 2 + shared/plugins/sdk/go/lithe/errors_test.go | 2 +- shared/plugins/sdk/go/lithe/host.go | 45 +++++++ .../sdk/go/lithe/host_services_test.go | 41 +++++++ shared/plugins/sdk/go/lithe/protocol.go | 7 ++ shared/plugins/sdk/java/README.md | 3 +- .../io/github/litheidea/plugin/sdk/Host.java | 56 +++++++++ .../litheidea/plugin/sdk/HostError.java | 2 + .../github/litheidea/plugin/sdk/Protocol.java | 7 ++ .../github/litheidea/plugin/sdk/HostTest.java | 42 +++++++ shared/plugins/sdk/node/README.md | 3 +- shared/plugins/sdk/node/src/host.mjs | 7 ++ shared/plugins/sdk/node/src/index.d.ts | 34 +++++- shared/plugins/sdk/node/src/protocol.mjs | 9 ++ shared/plugins/sdk/node/test/host.test.mjs | 24 ++++ shared/plugins/sdk/node/test/types/host.mts | 23 ++++ shared/plugins/sdk/rust/README.md | 3 +- .../plugins/sdk/rust/plugin-sdk/src/error.rs | 6 +- .../plugins/sdk/rust/plugin-sdk/src/host.rs | 46 +++++++ .../sdk/rust/plugin-sdk/src/protocol.rs | 7 ++ .../rust/plugin-sdk/tests/host_services.rs | 54 +++++++++ 34 files changed, 731 insertions(+), 26 deletions(-) diff --git a/rust/crates/plugin-rpc/src/failures.rs b/rust/crates/plugin-rpc/src/failures.rs index 4d53cf40..d43251a9 100644 --- a/rust/crates/plugin-rpc/src/failures.rs +++ b/rust/crates/plugin-rpc/src/failures.rs @@ -45,6 +45,8 @@ pub fn host_rpc_code(code: &str) -> i64 { // -32072 to -32077 are the toolchain provider protocol's. codes::HOST_REMOTE_DISCONNECTED => -32078, codes::HOST_PLATFORM_UNAVAILABLE => -32079, + codes::HOST_ALREADY_EXISTS => -32080, + codes::HOST_DISK_CHANGED => -32081, _ => -32603, } } @@ -91,6 +93,8 @@ pub fn host_failure(code: Option<&str>) -> (&'static str, i64) { Some(codes::HOST_FOREIGN_CONTRIBUTION) => codes::HOST_FOREIGN_CONTRIBUTION, Some(codes::HOST_REMOTE_DISCONNECTED) => codes::HOST_REMOTE_DISCONNECTED, Some(codes::HOST_PLATFORM_UNAVAILABLE) => codes::HOST_PLATFORM_UNAVAILABLE, + Some(codes::HOST_ALREADY_EXISTS) => codes::HOST_ALREADY_EXISTS, + Some(codes::HOST_DISK_CHANGED) => codes::HOST_DISK_CHANGED, // A backend exit is reported to pages, never to the backend itself. Some(codes::BACKEND_EXITED) => codes::HOST_FAILED, _ => codes::HOST_FAILED, diff --git a/rust/crates/plugin-rpc/src/host_requests.rs b/rust/crates/plugin-rpc/src/host_requests.rs index d7b70841..6914ea5b 100644 --- a/rust/crates/plugin-rpc/src/host_requests.rs +++ b/rust/crates/plugin-rpc/src/host_requests.rs @@ -67,9 +67,6 @@ pub(crate) enum HostParams { /// `plugin.host.invalidParams` or, for a field it does not know, /// `plugin.host.unsupportedOption` itself; for methods whose params /// Core cannot type without owning their domain. - // No row uses it yet; the file, editor, and window services that follow - // add their rows with it. - #[allow(dead_code)] Object, } @@ -268,6 +265,33 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: Some("workspace.search"), params: HostParams::Object, }, + // Plan API-11: file changes the host makes on the backend's behalf. The + // host never overwrites a file, saves an open document before it moves + // or trashes its file, and moves to the trash instead of deleting. + HostMethod { + method: "lithe/host/workspace/create", + service: "workspace", + permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), + params: HostParams::Object, + }, + HostMethod { + method: "lithe/host/workspace/rename", + service: "workspace", + permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), + params: HostParams::Object, + }, + HostMethod { + method: "lithe/host/workspace/copy", + service: "workspace", + permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), + params: HostParams::Object, + }, + HostMethod { + method: "lithe/host/workspace/trash", + service: "workspace", + permission: Some(PERMISSION_WORKSPACE_FILES_WRITE), + params: HostParams::Object, + }, HostMethod { method: "lithe/host/documents/list", service: "documents", @@ -280,6 +304,26 @@ pub(crate) const HOST_METHODS: &[HostMethod] = &[ permission: Some("documents.read"), params: HostParams::Object, }, + // Plan API-11: saving and closing an open document through its owner, + // which keeps the document's version, dirty state and undo history. + HostMethod { + method: "lithe/host/documents/save", + service: "documents", + permission: Some(PERMISSION_DOCUMENTS_SAVE), + params: HostParams::Object, + }, + HostMethod { + method: "lithe/host/documents/saveAs", + service: "documents", + permission: Some(PERMISSION_DOCUMENTS_SAVE), + params: HostParams::Object, + }, + HostMethod { + method: "lithe/host/documents/close", + service: "documents", + permission: Some(PERMISSION_DOCUMENTS_SAVE), + params: HostParams::Object, + }, HostMethod { method: "lithe/host/editor/registerActions", service: "editor", diff --git a/rust/crates/plugin-rpc/src/lib.rs b/rust/crates/plugin-rpc/src/lib.rs index cfd70412..395e1c61 100644 --- a/rust/crates/plugin-rpc/src/lib.rs +++ b/rust/crates/plugin-rpc/src/lib.rs @@ -157,6 +157,8 @@ pub const HOST_PERMISSIONS: &[&str] = &[ "debug.start", PERMISSION_LANGUAGE_SERVER_REQUEST, PERMISSION_DOCUMENTS_CONTENT_PROVIDER, + PERMISSION_DOCUMENTS_SAVE, + PERMISSION_WORKSPACE_FILES_WRITE, ]; /// Permission of the `languageServer` host service (plan API-25): a backend @@ -168,6 +170,17 @@ pub const PERMISSION_LANGUAGE_SERVER_REQUEST: &str = "languageServer.request"; /// backend supplies the read-only text of URIs of a scheme it registers. pub(crate) const PERMISSION_DOCUMENTS_CONTENT_PROVIDER: &str = "documents.contentProvider"; +/// Permission of `documents/save`, `saveAs` and `close` (plan API-11): the +/// backend asks the document's owner to write or close an open document. A +/// close saves first; the owner never discards the user's edits for it. +pub(crate) const PERMISSION_DOCUMENTS_SAVE: &str = "documents.save"; + +/// Permission of `workspace/create`, `rename`, `copy` and `trash` (plan +/// API-11): the backend changes files inside the context's root folders. +/// None of them overwrites a file, and `trash` moves to the system trash +/// instead of deleting. +pub(crate) const PERMISSION_WORKSPACE_FILES_WRITE: &str = "workspace.files.write"; + const CREDENTIALS_GET: &str = "lithe/host/credentials/get"; const CREDENTIALS_SET: &str = "lithe/host/credentials/set"; @@ -309,6 +322,14 @@ pub mod codes { /// The plugin has no package or managed runtime for the remote host's /// platform, so the process the request needs cannot run there. pub const HOST_PLATFORM_UNAVAILABLE: &str = "plugin.host.platformUnavailable"; + /// The file or folder the request would create, or the target of a + /// rename, copy or save as, already exists. The host never overwrites + /// it. + pub const HOST_ALREADY_EXISTS: &str = "plugin.host.alreadyExists"; + /// The file on disk changed, or was deleted, after the document last + /// read or wrote it, so a save would overwrite a change the document + /// does not hold. Nothing was written; the user settles the conflict. + pub const HOST_DISK_CHANGED: &str = "plugin.host.diskChanged"; /// A page's call or a host operation ended because the backend process /// exited. Reported by hosts to pages, never sent to a backend. pub const BACKEND_EXITED: &str = "plugin.backend.exited"; @@ -866,6 +887,98 @@ mod tests { .contains(&json!(WORKSPACE_GET_HOST_PATHS))); } + /// 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. + #[test] + fn saves_and_file_changes_are_method_grants_of_their_own() { + assert_eq!( + methods_for_permission(PERMISSION_DOCUMENTS_SAVE), + [ + "lithe/host/documents/save", + "lithe/host/documents/saveAs", + "lithe/host/documents/close", + ] + ); + let writes = methods_for_permission(PERMISSION_WORKSPACE_FILES_WRITE); + assert_eq!( + writes, + [ + "lithe/host/workspace/create", + "lithe/host/workspace/rename", + "lithe/host/workspace/copy", + "lithe/host/workspace/trash", + ] + ); + let context = json!({ "contextID": "w-3f2a", "generation": 2 }); + let params = json!({ "context": context, "resource": { "rootID": "r0", "path": "a.txt" } }); + let reading = BTreeSet::from([ + HOST_SERVICE_WORKSPACE.to_string(), + "lithe/host/workspace/readFile".to_string(), + ]); + for method in &writes { + assert!(is_host_grant(method), "{method}"); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &reading) + .unwrap_err() + .code, + codes::HOST_PERMISSION_DENIED, + "{method}" + ); + let granted = BTreeSet::from([method.to_string()]); + assert_eq!( + host_request(method, Some(¶ms), Some(0), &granted), + Ok(HostRoute::Forward(HOST_SERVICE_WORKSPACE)), + "{method}" + ); + } + let save = BTreeSet::from(["lithe/host/documents/save".to_string()]); + assert_eq!( + host_request( + "lithe/host/documents/save", + Some(&json!({ "context": context, "documentID": "d1" })), + Some(0), + &save, + ), + Ok(HostRoute::Forward("documents")) + ); + // Every code a host may report keeps a number of its own. + let host_codes = [ + codes::HOST_UNAVAILABLE, + codes::HOST_INVALID_PARAMS, + codes::HOST_CANCELLED, + codes::HOST_PERMISSION_DENIED, + codes::HOST_CONTEXT_EXPIRED, + codes::HOST_AUTHORITY_UNSUPPORTED, + codes::HOST_VERSION_CONFLICT, + codes::HOST_LIMIT_EXCEEDED, + codes::HOST_TIMEOUT, + codes::HOST_NOT_FOUND, + codes::HOST_READ_ONLY, + codes::HOST_UNSUPPORTED_OPTION, + codes::HOST_PRECONDITION_FAILED, + codes::HOST_BUSY, + codes::HOST_RATE_LIMITED, + codes::HOST_LANGUAGE_SERVER_UNAVAILABLE, + codes::HOST_LANGUAGE_SERVER_ERROR, + codes::HOST_METHOD_NOT_DECLARED, + codes::HOST_TOOL_UNRESOLVED, + codes::HOST_FOREIGN_CONTRIBUTION, + codes::HOST_REMOTE_DISCONNECTED, + codes::HOST_PLATFORM_UNAVAILABLE, + codes::HOST_ALREADY_EXISTS, + codes::HOST_DISK_CHANGED, + codes::HOST_FAILED, + ]; + for code in host_codes { + assert_eq!(host_failure(Some(code)).0, code, "{code}"); + } + let numbers: BTreeSet = host_codes.iter().map(|code| host_rpc_code(code)).collect(); + assert_eq!(numbers.len(), host_codes.len()); + assert_eq!(host_rpc_code(codes::HOST_ALREADY_EXISTS), -32080); + assert_eq!(host_rpc_code(codes::HOST_DISK_CHANGED), -32081); + } + /// A message over the bound is cut at a character boundary, never inside /// a multi-byte character. #[test] diff --git a/rust/fixtures/plugins/host-api-v1.json b/rust/fixtures/plugins/host-api-v1.json index f96dd033..484cf7c1 100644 --- a/rust/fixtures/plugins/host-api-v1.json +++ b/rust/fixtures/plugins/host-api-v1.json @@ -20,6 +20,26 @@ "input": { "method": "lithe/host/workspace/getHostPaths", "service": "workspace", "grants": ["workspace", "lithe/host/workspace/getHostPaths"] }, "expected": { "allowed": true } }, + { + "name": "a read grant does not grant file changes", + "input": { "method": "lithe/host/workspace/create", "service": "workspace", "grants": ["workspace", "lithe/host/workspace/readFile"] }, + "expected": { "allowed": false, "code": "plugin.host.permissionDenied" } + }, + { + "name": "the file-change grant admits its own method", + "input": { "method": "lithe/host/workspace/trash", "service": "workspace", "grants": ["lithe/host/workspace/trash"] }, + "expected": { "allowed": true } + }, + { + "name": "a document read grant does not grant saving", + "input": { "method": "lithe/host/documents/save", "service": "documents", "grants": ["lithe/host/documents/getSnapshot"] }, + "expected": { "allowed": false, "code": "plugin.host.permissionDenied" } + }, + { + "name": "the save grant admits saving", + "input": { "method": "lithe/host/documents/save", "service": "documents", "grants": ["lithe/host/documents/save"] }, + "expected": { "allowed": true } + }, { "name": "a method cannot be attributed to another service", "input": { "method": "lithe/host/editor/applyEdits", "service": "workspace", "grants": ["workspace"] }, diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index d260eede..7dc93905 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -4140,6 +4140,8 @@ notifications. | `plugin.host.foreignContribution` | `-32026` | The named server or contribution belongs to another plugin | | `plugin.host.remoteDisconnected` | `-32078` | The connection to the remote host was lost while the operation ran; whether it took effect on the host is unknown, and the backend asks again once the context is current | | `plugin.host.platformUnavailable` | `-32079` | The plugin has no package or managed runtime for the remote host's `platform`, so the process the request needs cannot run there | + | `plugin.host.alreadyExists` | `-32080` | The target of a create, copy, rename or save-as already exists; the host never overwrites it | + | `plugin.host.diskChanged` | `-32081` | The file changed or was deleted on disk after the document read it; nothing was written, and the user chooses which version to keep | JSON-RPC reserves `-32768` to `-32000` for the protocol and lets implementations define `-32099` to `-32000` as server errors. `-32000` @@ -4263,6 +4265,9 @@ methods. Unknown options fail before side effects with `unsupportedOption`. | --- | --- | --- | --- | | `documents/list` | `documents.read` | none | `{documents:[]}` | | `documents/getSnapshot` | `documents.read` | `documentID` | `{document:, text}` from the dirty live buffer | +| `documents/save` | `documents.save` | `documentID,expectedVersion?` | `{document:}` after the write, `isDirty:false`; see [Saving documents and changing files](#saving-documents-and-changing-files) | +| `documents/saveAs` | `documents.save` | `documentID,target` (a `{rootID,path}` that does not exist) | `{document:}` of the new file, opened and selected | +| `documents/close` | `documents.save` | `documentID` | `null` after saving the document and closing its tab | | `editor/registerActions` | `editor.actions` (+ `documents.read`) | `id,function,selector` | `{subscriptionID}`; independent editor actions, see below | | `editor/registerProviders` | `editor.providers` (+ `documents.read`) | `id,selector,providers` | `{subscriptionID}`; editor language-feature providers, see below | | `editor/getActive` | `documents.read` | none | summary of the foreground text tab, or `null` | @@ -4275,6 +4280,10 @@ methods. Unknown options fail before side effects with `unsupportedOption`. | `workspace/readFile` | `workspace.files.read` | `resource,maximumBytes?` | `{resource,source:"disk",byteCount,isTruncated,identity,text?,encoding?,base64?}` | | `workspace/watch` | `workspace.files.watch` | `resource,recursive?` (default false) | `{subscriptionID}`; events contain `{rootID,changedPaths,requiresRescan}` | | `workspace/findFiles` | `workspace.search` | `resource` naming the root (`path:""`), `query,fileMask?,cursor?,limit?` | `{matches:[],nextCursor,isTruncated,source:"disk"}` | +| `workspace/create` | `workspace.files.write` | `resource,kind` (`file` or `directory`), `text?` (files only) | `{resource,kind}`; never overwrites | +| `workspace/rename` | `workspace.files.write` | `resource,target` | `{resource}` of the target; open documents follow | +| `workspace/copy` | `workspace.files.write` | `resource,target` | `{resource}` of the copy; never overwrites | +| `workspace/trash` | `workspace.files.write` | `resource` | `null` after moving it to the system trash | | `workspace/findText` | `workspace.search` | root `resource,pattern,fileMask?,caseSensitive?,wholeWords?,regularExpression?,cursor?,limit?` | same envelope, matches `{resource,line,preview,range:null}`; the upstream search owner currently reports lines, not exact match spans | | `editor/open`, `editor/reveal` | `editor.open` | `resource,activation?` (`select` or `background`), `range?,tab?` (`regular` only) | document identity/version and state, `wasAlreadyOpen,windowIsForeground,appliedSelection` | | `preview/openHTML` | `preview.open` | HTML `resource,presentation?` (`editorAndPreview` or `previewOnly`), `range?` | open result plus `usesLiveBuffer:true,presentation`; explicitly changes the existing tab's presentation | @@ -4321,6 +4330,67 @@ On `versionConflict`, reread and recompute; on `contextExpired`, resolve the original target again, never substitute the focused window. `busy`/`rateLimited` may be retried with bounds; `permissionDenied`/`readOnly` need user intervention. +#### Saving documents and changing files + +`documents.save` grants `documents/save`, `documents/saveAs` and +`documents/close`. `workspace.files.write` grants `workspace/create`, +`workspace/rename`, `workspace/copy` and `workspace/trash`. Neither grants +any other method, and no other permission grants these; a plugin that only +reads keeps reading. The host makes each change through the same owner as the +user's command, so a saved document keeps its version, undo history and +language session, and an open document follows its file when the file moves. + +None of these methods asks the user anything. They have the 30-second machine +deadline, and a change that would need the user's choice is refused instead: + +- **Nothing is overwritten.** `saveAs`, `create`, `rename` and `copy` fail with + `alreadyExists` when the target exists. A rename that changes only the case + of a name on a case-insensitive file system is not a collision. +- **Nothing is discarded.** `save` writes the document's current text, including + edits the user made after the plugin asked; a save already running finishes + first, and the result reports the version that was written. `close` saves + first and closes only after the save succeeds and the file on disk matches + the document. `rename` and `trash` save the open documents under the resource + first; when one of those saves fails, nothing is moved. +- **Nothing is deleted.** `trash` moves the file or directory to the system + trash, from which the user restores it. Its open documents are saved and + their tabs close. There is no permanent delete. +- **A disk change is the user's to resolve.** When the file changed or was + deleted on disk after the document read it, `save` and `close` fail with + `diskChanged` and write nothing; the editor keeps showing the user its own + choice between the two versions. + +| Method | Errors in addition to `invalidParams`, `contextExpired`, `authorityUnsupported` and `permissionDenied` | +| --- | --- | +| `documents/save` | `notFound` (no such document); `versionConflict` with `details.currentVersion` when `expectedVersion` is given and differs; `busy` (IME composition); `preconditionFailed` (an untitled document, which needs `saveAs`; a document with no file, such as a virtual one; a hard-linked file, whose save the user must choose); `diskChanged`; `failed` (the write failed; the user also sees the host's save-failed notice) | +| `documents/saveAs` | `notFound` (no such document, or the target's parent directory does not exist); `alreadyExists`; `busy` (IME composition, or a save of the document is running); `failed` | +| `documents/close` | the errors of `save`; `preconditionFailed` is not among them, since an untitled or virtual document closes without a write (an untitled document keeps its draft) | +| `workspace/create` | `notFound` (the parent directory does not exist); `alreadyExists`; `limitExceeded` (`text` is over 128 KiB of UTF-8); `failed` | +| `workspace/rename` | `notFound` (the resource or the target's parent); `alreadyExists`; `diskChanged`, `busy` or `failed` from saving an open document; `failed` | +| `workspace/copy` | `notFound` (the resource or the target's parent); `alreadyExists`; `failed` | +| `workspace/trash` | `notFound`; `diskChanged`, `busy` or `failed` from saving an open document; `failed` (the system trash refused the item) | + +Paths: `resource` and `target` are `{rootID,path}` resources of one root, and +`target` is the full new path, not a directory to move into. The root itself +(`path:""`) cannot be created, renamed, copied or trashed, and a target inside +its own source is refused; both are `invalidParams`. The target's parent must +exist; nothing creates missing directories. The host checks that the parent of +each path resolves inside the root, and acts on the last component itself: a +symbolic link is renamed, copied or trashed as a link, never as the file it +points to. A copy keeps symbolic links inside a copied directory as links. + +`create` writes `text` as UTF-8, or makes an empty file; a directory takes no +`text`. It does not open the file; call `editor/open` for that. `saveAs` writes +the document's current text as UTF-8 with its line endings, then opens the new +file and selects it; the original document stays open and unchanged, except +that an untitled document whose text did not change during the write closes, +as it does for the user's Save As. `rename`, `copy` and `trash` refresh the +project tree and version control status as the user's commands do. + +On cancellation or timeout, the change may already be on disk; read the target +back with `workspace/stat` before retrying. Watch events report these changes +like any other. + ### Plugin-owned native terminals [`terminal-backend.plugin.json`](fixtures/backend/terminal-backend.plugin.json) is the @@ -5262,6 +5332,8 @@ command payload is a Core `invalid_request` failure instead. | `plugin.host.foreignContribution` | Core | The named language server belongs to another plugin | | `plugin.host.remoteDisconnected` | Host | The connection to the remote host was lost while the operation ran | | `plugin.host.platformUnavailable` | Host | The plugin has no package or managed runtime for the remote host's platform | +| `plugin.host.alreadyExists` | Host | The target of a file change already exists | +| `plugin.host.diskChanged` | Host | A save found the file changed or deleted on disk and wrote nothing | | `plugin.backend.exited` | Host | A page's call, or a host operation for the backend, ended because the backend process exited | Host-facing plugin states are `notInstalled`, `installed` (enabled or diff --git a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json index 70b72d1a..47deab18 100644 --- a/shared/plugins/contract/v1/fixtures/backend/function-protocol.json +++ b/shared/plugins/contract/v1/fixtures/backend/function-protocol.json @@ -523,6 +523,10 @@ {"name": "a content scheme starts with a letter", "version": 0, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "1metals", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a content provider names a plugin function", "version": 0, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"context": {"contextID": "w1", "generation": 1}, "scheme": "metals-library", "function": "not a function"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, {"name": "a content provider needs a context", "version": 0, "hostServices": ["lithe/host/documents/registerContentProvider"], "method": "lithe/host/documents/registerContentProvider", "params": {"scheme": "metals-library", "function": "documents.read"}, "expected": {"rpcCode": -32602, "code": "plugin.host.invalidParams"}}, + {"name": "a save is forwarded with the documents.save grant", "version": 0, "hostServices": ["lithe/host/documents/save"], "method": "lithe/host/documents/save", "params": {"context": {"contextID": "w1", "generation": 1}, "documentID": "d1", "expectedVersion": 3}, "expected": {"forward": "documents"}}, + {"name": "a document read grant never authorizes a save", "version": 0, "hostServices": ["lithe/host/documents/getSnapshot"], "method": "lithe/host/documents/save", "params": {"context": {"contextID": "w1", "generation": 1}, "documentID": "d1"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "the aggregate workspace grant never authorizes a file change", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/create", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "notes/a.md"}, "kind": "file"}, "expected": {"rpcCode": -32010, "code": "plugin.host.permissionDenied"}}, + {"name": "a file change is forwarded with its own grant", "version": 0, "hostServices": ["lithe/host/workspace/rename"], "method": "lithe/host/workspace/rename", "params": {"context": {"contextID": "w1", "generation": 1}, "resource": {"rootID": "r0", "path": "a.md"}, "target": {"rootID": "r0", "path": "b.md"}}, "expected": {"forward": "workspace"}}, {"name": "a declared caller lists the providers of a function", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/providers", "params": {"functionID": "languageImport.settings"}, "expected": {"relay": true}}, {"name": "a declared caller invokes another plugin's function through the relay", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000}, "expected": {"relay": true}}, {"name": "a nested invocation names the relayed call it belongs to", "version": 0, "hostServices": ["functions"], "method": "lithe/host/functions/invoke", "params": {"pluginID": "dev.lithe.fixture.go", "functionID": "languageImport.settings", "context": {"contextID": "w1", "generation": 1}, "params": {"project": "app"}, "timeoutMilliseconds": 5000, "parentOperationID": "17"}, "expected": {"relay": true}}, @@ -643,7 +647,9 @@ {"name": "the method is not in the language server's declared session", "code": "plugin.host.methodNotDeclared", "expected": {"code": "plugin.host.methodNotDeclared", "rpcCode": -32024}}, {"name": "the server belongs to another plugin", "code": "plugin.host.foreignContribution", "expected": {"code": "plugin.host.foreignContribution", "rpcCode": -32026}}, {"name": "the connection to the remote host was lost", "code": "plugin.host.remoteDisconnected", "expected": {"code": "plugin.host.remoteDisconnected", "rpcCode": -32078}}, - {"name": "the plugin has nothing that runs on the remote host's platform", "code": "plugin.host.platformUnavailable", "expected": {"code": "plugin.host.platformUnavailable", "rpcCode": -32079}} + {"name": "the plugin has nothing that runs on the remote host's platform", "code": "plugin.host.platformUnavailable", "expected": {"code": "plugin.host.platformUnavailable", "rpcCode": -32079}}, + {"name": "the target of a file change already exists", "code": "plugin.host.alreadyExists", "expected": {"code": "plugin.host.alreadyExists", "rpcCode": -32080}}, + {"name": "the file on disk changed under the document", "code": "plugin.host.diskChanged", "expected": {"code": "plugin.host.diskChanged", "rpcCode": -32081}} ], "hostNotifications": [ { "name": "changed contexts reach a workspace session", "version": 0, "hostServices": ["workspace"], "method": "lithe/host/workspace/didChangeContexts", "params": { "revision": 4 }, "expected": { "delivered": true } }, diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 9a7342ed..fb87808d 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -100,7 +100,9 @@ "run.start", "debug.start", "languageServer.request", - "documents.contentProvider"] } + "documents.contentProvider", + "documents.save", + "workspace.files.write"] } }, "activationEvents": { "type": "array", diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index 4f3ae445..4cf2b6fa 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -193,8 +193,10 @@ | `credentials/get`、`credentials/set`、`credentials/delete` | `credentials.store` | 插件私有的密钥,存在平台的密钥库里,不在状态目录或插件包中;`key` 是 1–128 个字母、数字、`.`、`_`、`:`、`-`,密钥最多 16 KiB;卸载插件时删除 | | `documents/list`、`documents/getSnapshot`、`editor/getActive`、`editor/getSelections` | `documents.read` | 列出打开的文档,读编辑器里未保存的内容、当前标签页和选区 | | `editor/applyEdits`、`editor/replaceSelections`、`editor/insertText` | `editor.edit` | 带 `expectedVersion` 的编辑;一批编辑是一次原子操作、一步撤销 | +| `documents/save`、`documents/saveAs`、`documents/close` | `documents.save` | 保存、另存为、关闭打开的文档;关闭前先保存,从不丢弃用户的修改 | | `workspace/readDirectory`、`workspace/stat`、`workspace/readFile` | `workspace.files.read` | 读磁盘上的目录和文件 | | `workspace/watch` | `workspace.files.watch` | 订阅文件变化,事件经 `subscriptions/notify` 送达 | +| `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash` | `workspace.files.write` | 新建文件或目录、重命名、复制、移到系统废纸篓;从不覆盖已有文件,也不永久删除 | | `workspace/findFiles`、`workspace/findText` | `workspace.search` | 按文件名或内容搜索,分页返回 | | `editor/open`、`editor/reveal` | `editor.open` | 打开文件并定位到某处 | | `preview/openHTML` | `preview.open` | 用内置预览打开 HTML 文件 | @@ -212,6 +214,7 @@ 遇到 `contextExpired` 要重新找到原来的目标,不要改用当前聚焦的窗口;`busy`、`rateLimited` 可以有限次重试; `permissionDenied`、`readOnly` 需要用户处理。 - 后台没有挂载编辑器的文档可以列出和读取,但编辑与选区可能返回 `busy`。 +- 保存和文件变更不弹任何询问:目标已存在时得到 `alreadyExists`,文件在磁盘上被改过或删掉时 `save`、`close` 得到 `diskChanged` 且不写入,交给用户在编辑器里选择保留哪一版;未命名文档要用 `saveAs`,硬链接文件的保存要用户选择,二者都得到 `preconditionFailed`。`rename`、`trash` 先保存其下打开的文档,保存失败就什么都不动。规则见契约的[保存文档与变更文件](../contract/v1/README.md#saving-documents-and-changing-files)。 - 消息有频率和排队上限(每插件 10 秒 5 条、最多 3 条待答;同一窗口最多 10 条;正文最多 2,000 个字符,按钮最多 3 个、每个最多 40 个字符),用户回答前请求一直挂起。 另有几组方法,各自带权限,调用前同样先查 `getCapabilities.services`,清单条件见对应的契约章节: @@ -252,6 +255,8 @@ | `plugin.host.foreignContribution` | `-32026` | 指名的服务器或贡献属于别的插件 | | `plugin.host.remoteDisconnected` | `-32078` | 操作进行中和远端主机断开,不知道它是否已在远端生效;上下文恢复后先重新读取状态再决定,不要自动重放修改 | | `plugin.host.platformUnavailable` | `-32079` | 插件没有适合远端主机 `platform` 的程序包或托管运行时,所需进程无法在那里运行;告诉用户缺什么 | +| `plugin.host.alreadyExists` | `-32080` | 新建、复制、重命名或另存为的目标已存在,宿主不会覆盖;换一个目标,或先问用户 | +| `plugin.host.diskChanged` | `-32081` | 文件在文档读入后被磁盘上的改动修改或删除,什么都没写;由用户在编辑器里选择保留哪一版,不要重试保存 | `-32000` 到 `-32009` 留给后端自己的失败,宿主号码从 `-32010` 起。跨插件调用另有 `plugin.function.failed`(`-32070`)和 `plugin.function.invalidResult`(`-32071`),见第 11 节。 @@ -518,8 +523,10 @@ The host opens a set of public methods, each group behind a permission. `getCapa | `credentials/get`, `credentials/set`, `credentials/delete` | `credentials.store` | Secrets private to the plugin, kept in the platform's secret store, never in the state directory or the package; a `key` is 1 to 128 letters, digits, `.`, `_`, `:`, or `-`, a secret is at most 16 KiB; deleted when the plugin is uninstalled | | `documents/list`, `documents/getSnapshot`, `editor/getActive`, `editor/getSelections` | `documents.read` | List open documents; read unsaved editor content, the active tab, and selections | | `editor/applyEdits`, `editor/replaceSelections`, `editor/insertText` | `editor.edit` | Edits with `expectedVersion`; a batch is one atomic operation and one undo step | +| `documents/save`, `documents/saveAs`, `documents/close` | `documents.save` | Save, save as, and close an open document; a close saves first and never discards the user's edits | | `workspace/readDirectory`, `workspace/stat`, `workspace/readFile` | `workspace.files.read` | Read directories and files on disk | | `workspace/watch` | `workspace.files.watch` | Subscribe to file changes; events arrive through `subscriptions/notify` | +| `workspace/create`, `workspace/rename`, `workspace/copy`, `workspace/trash` | `workspace.files.write` | Create a file or directory, rename, copy, or move to the system trash; never overwrites a file or deletes permanently | | `workspace/findFiles`, `workspace/findText` | `workspace.search` | Search by file name or content, paged | | `editor/open`, `editor/reveal` | `editor.open` | Open a file and go to a location | | `preview/openHTML` | `preview.open` | Open an HTML file in the built-in preview | @@ -537,6 +544,7 @@ The [contract](../contract/v1/README.md#public-document-file-and-window-methods) on `contextExpired`, find the original target again instead of switching to the focused window; `busy` and `rateLimited` may be retried a bounded number of times; `permissionDenied` and `readOnly` need the user. - Documents open in the background without a mounted editor can be listed and read, but edits and selections may return `busy`. +- Saves and file changes never ask the user anything: an existing target gives `alreadyExists`; a file changed or deleted on disk gives `diskChanged` from `save` and `close`, with nothing written, and the user chooses in the editor which version to keep; an untitled document needs `saveAs`, and a hard-linked file's save needs the user's choice, both giving `preconditionFailed`. `rename` and `trash` save the open documents under the resource first and move nothing when a save fails. The rules are in the contract's [Saving documents and changing files](../contract/v1/README.md#saving-documents-and-changing-files). - Messages have rate and queue limits (5 per 10 seconds per plugin, at most 3 awaiting an answer, at most 10 per window; text of at most 2,000 characters, at most 3 buttons of at most 40 characters each), and the request stays pending until the user answers. Several more groups of methods, each behind its own permission, also need a `getCapabilities.services` check before calling; their manifest conditions are in the contract sections named below: @@ -577,6 +585,8 @@ Host failures are typed: each JSON-RPC number maps one-to-one to an `error.data. | `plugin.host.foreignContribution` | `-32026` | The named server or contribution belongs to another plugin | | `plugin.host.remoteDisconnected` | `-32078` | The connection to the remote host was lost while the operation ran, so whether it took effect there is unknown; once the context is current, read the state again before deciding, and do not replay a change automatically | | `plugin.host.platformUnavailable` | `-32079` | The plugin has no package or managed runtime for the remote host's `platform`, so the process it needs cannot run there; tell the user what is missing | +| `plugin.host.alreadyExists` | `-32080` | The target of a create, copy, rename, or save-as already exists, and the host never overwrites it; pick another target or ask the user first | +| `plugin.host.diskChanged` | `-32081` | The file changed or was deleted on disk after the document read it, and nothing was written; the user chooses in the editor which version to keep, so do not retry the save | `-32000` through `-32009` are reserved for the backend's own failures; host numbers start at `-32010`. Cross-plugin calls add `plugin.function.failed` (`-32070`) and `plugin.function.invalidResult` (`-32071`); see section 11. diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index e2ccb694..741b5f16 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -36,6 +36,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;Lithe 桌面端尚未注册这两个方法 | [插件后端](domains/backend.md) | | API-09 | 文档与选区读取 | 已公开 | `documents/list`、`documents/getSnapshot`、`editor/getActive`、`editor/getSelections`,包含未保存状态、版本、编码、换行符 | — | [编辑器](domains/editor.md) | | API-10 | 版本化编辑 | 已公开 | `editor/applyEdits`、`replaceSelections`、`insertText`;校验版本,拒绝输入法组字中和只读文档,一批编辑是一次撤销 | — | [编辑器](domains/editor.md) | +| API-11 | 保存与文件变更 | 已公开 | [`documents/save`、`saveAs`、`close`](../contract/v1/README.md#saving-documents-and-changing-files)(权限 `documents.save`)和 `workspace/create`、`rename`、`copy`、`trash`(权限 `workspace.files.write`);经文档所有者保存,关闭前先保存,从不覆盖、不丢弃修改、不永久删除,删除只移到系统废纸篓;需要用户选择时直接拒绝,不弹询问 | 一次保存全部文档、永久删除;保存前事件见 API-43 | [编辑器](domains/editor.md)、[插件后端](domains/backend.md) | | API-12 | 多文件编辑、虚拟文档、diff | 部分完成 | [内容提供者 `documents/registerContentProvider`](../contract/v1/README.md#content-providers):把一个 URI scheme 绑定到后端函数,打开该 scheme 的文档时宿主取只读内容(≤1 MiB,每个工作区窗口每个 scheme 一个) | 跨文件编辑、对比视图 | [编辑器](domains/editor.md) | | API-13 | 原生视图数据源 | 部分完成 | [插件视图](../contract/v1/README.md#plugin-views):工具窗口和[设置区域](../contract/v1/README.md#settings-regions)里,后端视图函数(经 `lithe/function/invoke` 按事件调用)返回界面树(宿主控件、树、显示插件工具解析结果的工具行)和画布节点,或按节点 ID 的补丁;Core 命令 `plugins.ui.applyResult` 按预算和界面规则校验每个结果,宿主用原生控件绘制 | 插件主动推送视图、树的懒加载 | [界面](domains/ui.md) | | API-14 | 网页消息 | 部分完成 | [包内网页](../contract/v1/README.md#web-content)的桥接、状态和生命周期 | 通用的页面双向消息 | [界面](domains/ui.md) | @@ -63,7 +64,6 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | ID | 名称 | 状态 | 计划提供 | | --- | --- | --- | --- | -| API-11 | 保存与文件变更 | 未做 | 保存、另存为、关闭,以及工作区文件的创建、改名、删除 | | API-18 | 剪贴板、Finder | 未做 | 剪贴板读写、在 Finder 中显示 | | API-26 | 诊断集合 | 未做 | 后端推送的诊断集合,带文档版本;现有的 LSP 诊断不属于这个 API | | API-28 | 自定义编辑器 | 未做 | 插件自有文档的编辑器,含保存、撤销、恢复 | @@ -106,6 +106,13 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-10 | `editor/applyEdits` | 按范围批量编辑,先校验 `expectedVersion` | `editor.edit` | 0 | | API-10 | `editor/replaceSelections` | 替换选区的文本:一个替换文本用于全部选区,或每个选区一个 | `editor.edit` | 0 | | API-10 | `editor/insertText` | 在指定位置插入文本 | `editor.edit` | 0 | +| API-11 | `documents/save` | 保存打开的文档,写入当前全部内容;可带 `expectedVersion`;文件在磁盘上变了时返回 `plugin.host.diskChanged`,不写入 | `documents.save` | 0 | +| API-11 | `documents/saveAs` | 把文档当前内容写到一个不存在的新文件并打开它;目标已存在时返回 `plugin.host.alreadyExists` | `documents.save` | 0 | +| API-11 | `documents/close` | 先保存再关闭文档的标签,从不丢弃修改 | `documents.save` | 0 | +| API-11 | `workspace/create` | 新建文件(可带不超过 128 KiB 的文本)或目录,不覆盖已有项 | `workspace.files.write` | 0 | +| API-11 | `workspace/rename` | 重命名或移动文件、目录;先保存其下打开的文档,文档跟着文件走 | `workspace.files.write` | 0 | +| API-11 | `workspace/copy` | 复制文件或目录到一个不存在的目标,符号链接保持为链接 | `workspace.files.write` | 0 | +| API-11 | `workspace/trash` | 先保存并关闭其下打开的文档,再把文件或目录移到系统废纸篓;不永久删除 | `workspace.files.write` | 0 | | API-12 | `documents/registerContentProvider` | 把一个 URI scheme 绑定到后端函数,打开该 scheme 的文档时宿主调用函数取只读内容(≤1 MiB),返回 `subscriptionID`;用 `subscriptions/dispose` 撤销 | `documents.contentProvider` | 0 | | API-15 | `editor/open` | 在编辑器中打开文件,没有缓冲区时从磁盘读取;可以前台或后台打开,并定位光标 | `editor.open` | 0 | | API-15 | `editor/reveal` | 参数和 `editor/open` 相同,但只处理已打开的文件;文件没打开时返回 `plugin.host.notFound`,不会从磁盘打开 | `editor.open` | 0 | @@ -212,6 +219,7 @@ Status meanings: | 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; the Lithe desktop client does not register these two methods | [Plugin backend](domains/backend.md) | | API-09 | Documents and selections | Public | `documents/list`, `documents/getSnapshot`, `editor/getActive`, `editor/getSelections`, with dirty state, version, encoding, and line ending | — | [Editor](domains/editor.md) | | API-10 | Versioned edits | Public | `editor/applyEdits`, `replaceSelections`, `insertText`; version checks, refusal during IME composition and in read-only documents, one undo step per batch | — | [Editor](domains/editor.md) | +| API-11 | Save and file operations | Public | [`documents/save`, `saveAs`, `close`](../contract/v1/README.md#saving-documents-and-changing-files) (permission `documents.save`) and `workspace/create`, `rename`, `copy`, `trash` (permission `workspace.files.write`); saves go through the document's owner, a close saves first, nothing is overwritten, discarded or deleted permanently, and a delete only moves to the system trash; a change that needs the user's choice is refused without asking | Saving all documents at once, permanent deletes; pre-save events are API-43 | [Editor](domains/editor.md), [Plugin backend](domains/backend.md) | | API-12 | Multi-file edits, virtual documents, diff | Partial | [Content providers `documents/registerContentProvider`](../contract/v1/README.md#content-providers): bind a URI scheme to a backend function, and the host fetches read-only content from it when a document of that scheme opens (≤1 MiB, one provider per scheme per workspace window) | Cross-file edits, a diff view | [Editor](domains/editor.md) | | API-13 | Native view data sources | Partial | [Plugin views](../contract/v1/README.md#plugin-views) in tool windows and [settings regions](../contract/v1/README.md#settings-regions): a backend view function, called through `lithe/function/invoke` once per event, returns a UI tree (host controls, trees, and tool rows showing how the plugin's tools resolve) and canvas nodes, or patches by node ID; the Core command `plugins.ui.applyResult` checks each result against budgets and surface rules, and the host draws it with native controls | Views pushed by the plugin on its own, lazy tree loading | [UI](domains/ui.md) | | API-14 | Webview messaging | Partial | The [package web page](../contract/v1/README.md#web-content) bridge, state, and lifecycle | General two-way page messaging | [UI](domains/ui.md) | @@ -239,7 +247,6 @@ Status meanings: | ID | Name | Status | Planned | | --- | --- | --- | --- | -| API-11 | Save and file operations | Not started | Save, save as, close, and creating, renaming, and deleting workspace files | | API-18 | Clipboard and Finder | Not started | Reading and writing the clipboard, revealing in Finder | | API-26 | Diagnostics collections | Not started | Diagnostics collections pushed by a backend, with document versions; existing LSP diagnostics are not this API | | API-28 | Custom editors | Not started | Editors for plugin-owned documents, with save, undo, and restore | @@ -282,6 +289,13 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-10 | `editor/applyEdits` | Applies a batch of range edits after checking `expectedVersion` | `editor.edit` | 0 | | API-10 | `editor/replaceSelections` | Replaces the text of selections: one replacement for all of them, or one per selection | `editor.edit` | 0 | | API-10 | `editor/insertText` | Inserts text at a position | `editor.edit` | 0 | +| API-11 | `documents/save` | Saves an open document, writing all of its current text; takes an optional `expectedVersion`; when the file changed on disk it returns `plugin.host.diskChanged` and writes nothing | `documents.save` | 0 | +| API-11 | `documents/saveAs` | Writes the document's current text to a new file that does not exist and opens it; an existing target returns `plugin.host.alreadyExists` | `documents.save` | 0 | +| API-11 | `documents/close` | Saves the document, then closes its tab; never discards edits | `documents.save` | 0 | +| API-11 | `workspace/create` | Creates a file (optionally with at most 128 KiB of text) or a directory, never over an existing item | `workspace.files.write` | 0 | +| API-11 | `workspace/rename` | Renames or moves a file or directory; saves the open documents under it first, and they follow the file | `workspace.files.write` | 0 | +| API-11 | `workspace/copy` | Copies a file or directory to a target that does not exist, keeping symbolic links as links | `workspace.files.write` | 0 | +| API-11 | `workspace/trash` | Saves and closes the open documents under the resource, then moves it to the system trash; never deletes permanently | `workspace.files.write` | 0 | | API-12 | `documents/registerContentProvider` | Binds a URI scheme to a backend function; when a document of that scheme opens, the host calls the function to get read-only content (≤1 MiB), and the call returns a `subscriptionID`, which `subscriptions/dispose` withdraws | `documents.contentProvider` | 0 | | API-15 | `editor/open` | Opens a file in the editor, reading it from disk when no buffer exists; opens it in the foreground or background and can place the caret | `editor.open` | 0 | | API-15 | `editor/reveal` | Takes the same params as `editor/open` but only handles files already open; a file that is not open returns `plugin.host.notFound` and is not opened from disk | `editor.open` | 0 | diff --git a/shared/plugins/reference/domains/backend.md b/shared/plugins/reference/domains/backend.md index ad17a41b..b45f37da 100644 --- a/shared/plugins/reference/domains/backend.md +++ b/shared/plugins/reference/domains/backend.md @@ -17,8 +17,8 @@ | 清单字段 | `backend`(与[启动进程](../../contract/v1/README.md#process-start)的字段相同,`launch` 加 `arguments` 等);跨插件调用另有 `pluginFunctions` 段(`exports`、`calls`) | | 能力版本 | `backend` `0`;`ui` 的后端命令需要同时声明 `ui: 0` 和 `backend: 0`;跨插件调用需要 `pluginFunctions: 0` 和 `backend: 0`。`requires` 必须恰好列出清单用到的能力;启动进程是基础契约,不是能力,不写 `requires.serverProcess`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | 协议 | `litheFunctions` `0`(版本就是 `backend` 的版本)、`litheLogging` `0`,见[进程协议版本](../capabilities-and-versions.md#进程协议版本) | -| API 编号 | API-01、04、05、06、07、08、20、21、22、23、24、35、37、40、41,见 [API 总表](../api-catalog.md#现在能用的-api) | -| 权限 | `backend.launch`;宿主服务按方法另加权限(`credentials.store`、`workspace.metadata`、`workspace.files.read`、`workspace.files.watch`、`workspace.search`、`terminal.create`、`run.start` 等),见[已公开的宿主方法](../api-catalog.md#已公开的宿主方法)。跨插件调用没有清单权限:调用方的 `calls` 和被调方的 `exports` 就是双方的同意 | +| API 编号 | API-01、04、05、06、07、08、11、20、21、22、23、24、35、37、40、41,见 [API 总表](../api-catalog.md#现在能用的-api) | +| 权限 | `backend.launch`;宿主服务按方法另加权限(`credentials.store`、`workspace.metadata`、`workspace.files.read`、`workspace.files.watch`、`workspace.files.write`、`workspace.search`、`terminal.create`、`run.start` 等),见[已公开的宿主方法](../api-catalog.md#已公开的宿主方法)。跨插件调用没有清单权限:调用方的 `calls` 和被调方的 `exports` 就是双方的同意 | | 激活事件 | 至少要有一种启动方式:网页工具窗口第一次调用 `functions.*`;`ui.commands[]` 的命令(`onCommand:`);可选的 `onWorkspaceOpen`;或宿主查询的提供者(工具链或快捷键导入提供者,以及 `launch.kind: "backend"` 的语言服务器)。都没有是 `plugin.manifest.invalid`。只导出函数的插件不需要网页、命令或 `onWorkspaceOpen`,被调用时启动后端;只调用的插件仍要有其中一种 | | 官方 SDK | [Node.js 0.5.0](../../sdk/node/README.md)、[Java 0.5.0](../../sdk/java/README.md)、[Rust 0.4.0](../../sdk/rust/README.md)、[Go](../../sdk/go/README.md)(未发布),Node.js 和 Rust 的发布标签为 `sdk-node-v0.5.0`、`sdk-rust-v0.4.0`;Java 按[获取说明](../../sdk/java/README.md#getting-the-sdk)固定 Core commit 引入源码,Go 用模块标签 `shared/plugins/sdk/go/v<版本>`(还没有推送),见[官方 SDK](../capabilities-and-versions.md#官方-sdk)。四个 SDK 都实现函数协议,封装凭据、工作区、文档与编辑器(含 `editor/registerActions`)、预览、浏览器、窗口消息、`functions/providers` 和 `functions/invoke`,被调函数能读到 `caller`,用法见各 SDK 的 README;`parentOperationID` 不传时,SDK 取正在处理的 `lithe/function/invoke` 的 `operationID`。`run/*`、`debug/start`、`languageServer/*`、`documents/registerContentProvider` 和 `editor/registerProviders` 没有专门的封装,用 SDK 的通用宿主请求(`request`,Go 是 `Request`)调用。原生终端有封装,见[从插件打开原生终端](../../guides/native-terminals.md) | @@ -55,7 +55,8 @@ | 凭据 | `credentials/get`、`set`、`delete` | `credentials.store` | | 工作区上下文 | `workspace/listContexts`、`getContext`、`getFolders` | `workspace.metadata` | | 文件与搜索 | `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText` | `workspace.files.read`、`workspace.files.watch`、`workspace.search` | -| 文档与编辑器 | `documents/*`、`editor/*`,见[编辑器](editor.md) | `documents.read`、`editor.edit`、`editor.open`、`editor.actions`、`editor.providers` | +| 文件变更 | `workspace/create`、`rename`、`copy`、`trash`:不覆盖已有项,删除只移到系统废纸篓,见[契约](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | +| 文档与编辑器 | `documents/*`、`editor/*`,见[编辑器](editor.md) | `documents.read`、`documents.save`、`editor.edit`、`editor.open`、`editor.actions`、`editor.providers` | | 预览、浏览器、窗口消息 | `preview/openHTML`、`browser/openExternal`、`window/*` | `preview.open`、`browser.open`、`window.messages` | | 原生终端 | `terminal/*` | `terminal.create` | | Run 与调试会话 | `run/start`、`run/stop`、`debug/start` | `run.start`、`debug.start` | @@ -238,8 +239,8 @@ A plugin backend is the plugin's own long-lived process. It runs what a web page | Manifest field | `backend` (the same fields as [process start](../../contract/v1/README.md#process-start): `launch`, `arguments`, and so on); cross-plugin calls add a `pluginFunctions` section (`exports`, `calls`) | | Capability versions | `backend` `0`; backend commands of `ui` need both `ui: 0` and `backend: 0`; cross-plugin calls need `pluginFunctions: 0` and `backend: 0`. `requires` must list exactly the capabilities the manifest uses; process start is base contract, not a capability, so do not write `requires.serverProcess`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | Protocols | `litheFunctions` `0` (the version is the version of `backend`), `litheLogging` `0`; see [process protocol versions](../capabilities-and-versions.md#process-protocol-versions) | -| API IDs | API-01, 04, 05, 06, 07, 08, 20, 21, 22, 23, 24, 35, 37, 40, 41; see the [API catalog](../api-catalog.md#apis-usable-now) | -| Permissions | `backend.launch`; host services need their own permission per method (`credentials.store`, `workspace.metadata`, `workspace.files.read`, `workspace.files.watch`, `workspace.search`, `terminal.create`, `run.start`, …); see [public host methods](../api-catalog.md#public-host-methods). Cross-plugin calls have no manifest permission: the caller's `calls` and the provider's `exports` are the consent of the two sides | +| API IDs | API-01, 04, 05, 06, 07, 08, 11, 20, 21, 22, 23, 24, 35, 37, 40, 41; see the [API catalog](../api-catalog.md#apis-usable-now) | +| Permissions | `backend.launch`; host services need their own permission per method (`credentials.store`, `workspace.metadata`, `workspace.files.read`, `workspace.files.watch`, `workspace.files.write`, `workspace.search`, `terminal.create`, `run.start`, …); see [public host methods](../api-catalog.md#public-host-methods). Cross-plugin calls have no manifest permission: the caller's `calls` and the provider's `exports` are the consent of the two sides | | Activation | At least one way to start is required: a web tool window's first `functions.*` call; a `ui.commands[]` command (`onCommand:`); the optional `onWorkspaceOpen`; or a provider the host queries (a toolchain or keymap import provider, or a language server with `launch.kind: "backend"`). None of them is `plugin.manifest.invalid`. A plugin that only exports functions needs no page, command, or `onWorkspaceOpen`: a call starts its backend; a plugin that only calls still needs one of them | | Official SDKs | [Node.js 0.5.0](../../sdk/node/README.md), [Java 0.5.0](../../sdk/java/README.md), [Rust 0.4.0](../../sdk/rust/README.md), [Go](../../sdk/go/README.md) (unreleased). Node.js and Rust use release tags `sdk-node-v0.5.0` and `sdk-rust-v0.4.0`; Java uses [sources from a pinned Core commit](../../sdk/java/README.md#getting-the-sdk); Go uses module tags `shared/plugins/sdk/go/v` (none pushed yet); see [official SDKs](../capabilities-and-versions.md#official-sdks). All four implement the function protocol and wrap credentials, workspaces, documents and editors (including `editor/registerActions`), preview, browser, window messages, `functions/providers`, and `functions/invoke`; a called function can read `caller`; see each SDK's README for usage. When `parentOperationID` is omitted, the SDK uses the `operationID` of the `lithe/function/invoke` being handled. `run/*`, `debug/start`, `languageServer/*`, `documents/registerContentProvider`, and `editor/registerProviders` have no dedicated wrappers; call them through the SDK's generic host request (`request`, `Request` in Go). Native terminals are wrapped; see [Open a native Lithe terminal from a plugin](../../guides/native-terminals.md) | @@ -276,7 +277,8 @@ A backend sends requests to the host with the prefix `lithe/host/`. Each service | Credentials | `credentials/get`, `set`, `delete` | `credentials.store` | | Workspace contexts | `workspace/listContexts`, `getContext`, `getFolders` | `workspace.metadata` | | Files and search | `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText` | `workspace.files.read`, `workspace.files.watch`, `workspace.search` | -| Documents and editors | `documents/*`, `editor/*`; see [Editor](editor.md) | `documents.read`, `editor.edit`, `editor.open`, `editor.actions`, `editor.providers` | +| File changes | `workspace/create`, `rename`, `copy`, `trash`: never over an existing item, and a delete only moves to the system trash; see the [contract](../../contract/v1/README.md#saving-documents-and-changing-files) | `workspace.files.write` | +| Documents and editors | `documents/*`, `editor/*`; see [Editor](editor.md) | `documents.read`, `documents.save`, `editor.edit`, `editor.open`, `editor.actions`, `editor.providers` | | Preview, browser, window messages | `preview/openHTML`, `browser/openExternal`, `window/*` | `preview.open`, `browser.open`, `window.messages` | | Native terminals | `terminal/*` | `terminal.create` | | Run and debug sessions | `run/start`, `run/stop`, `debug/start` | `run.start`, `debug.start` | diff --git a/shared/plugins/reference/domains/editor.md b/shared/plugins/reference/domains/editor.md index 8b2c02cd..b1c7d683 100644 --- a/shared/plugins/reference/domains/editor.md +++ b/shared/plugins/reference/domains/editor.md @@ -11,8 +11,8 @@ | 清单字段 | 没有专用字段;用 `backend` 加下面的权限 | | 能力 | `requires.backend: 0`,见[能力与协议版本](../capabilities-and-versions.md) | | 协议 | `litheFunctions`,版本 `0` | -| API 编号 | API-09、10、12、15、16、25、27,见 [API 总表](../api-catalog.md) | -| 权限 | `documents.read`、`editor.edit`、`editor.open`、`preview.open`、`browser.open`、`editor.actions`(同时需要 `documents.read`)、`editor.providers`(同时需要 `documents.read`)、`documents.contentProvider`(只授予 `documents/registerContentProvider`,不授予读写文档) | +| API 编号 | API-09、10、11、12、15、16、25、27,见 [API 总表](../api-catalog.md) | +| 权限 | `documents.read`、`editor.edit`、`documents.save`、`editor.open`、`preview.open`、`browser.open`、`editor.actions`(同时需要 `documents.read`)、`editor.providers`(同时需要 `documents.read`)、`documents.contentProvider`(只授予 `documents/registerContentProvider`,不授予读写文档) | | 激活事件 | 与后端相同:`onWorkspaceOpen`、`onCommand:` 或网页调用 | | Lithe 桌面端 | 已声明 `backend`;各方法是否可用由后端用 `getCapabilities` 在运行时发现,见[宿主现状](#宿主现状) | @@ -22,6 +22,7 @@ | --- | --- | --- | --- | | `documents/list`、`documents/getSnapshot`、`editor/getActive`、`editor/getSelections` | `documents.read` | API-09 | 包含未保存状态、版本、编码、换行符;快照最多 128 KiB | | `editor/applyEdits`、`editor/replaceSelections`、`editor/insertText` | `editor.edit` | API-10 | 校验文档版本;输入法组字中和只读文档会被拒绝;一批编辑是一次撤销 | +| `documents/save`、`documents/saveAs`、`documents/close` | `documents.save` | API-11 | 经文档所有者保存,版本、撤销记录和语言会话不变;关闭前先保存,从不丢弃修改;另存为的目标必须不存在;文件在磁盘上变了时返回 `diskChanged`,不写入;不弹任何询问,见[契约](../../contract/v1/README.md#saving-documents-and-changing-files) | | `editor/open`、`editor/reveal` | `editor.open` | API-15 | 返回 `documentID` 和版本;传入范围时只把光标放到起点 | | `preview/openHTML` | `preview.open` | API-16 | `editorAndPreview` 或 `previewOnly` | | `browser/openExternal` | `browser.open` | API-16 | HTTP(S) 地址或已保存的 HTML | @@ -100,8 +101,8 @@ Through the plugin-function protocol, a plugin backend reads open documents and | Manifest field | None of its own; use `backend` with the permissions below | | Capability | `requires.backend: 0`; see [capabilities and protocol versions](../capabilities-and-versions.md) | | Protocol | `litheFunctions`, version `0` | -| API IDs | API-09, 10, 12, 15, 16, 25, 27; see the [API catalog](../api-catalog.md) | -| Permissions | `documents.read`, `editor.edit`, `editor.open`, `preview.open`, `browser.open`, `editor.actions` (also needs `documents.read`), `editor.providers` (also needs `documents.read`), `documents.contentProvider` (grants only `documents/registerContentProvider`, not reading or editing documents) | +| API IDs | API-09, 10, 11, 12, 15, 16, 25, 27; see the [API catalog](../api-catalog.md) | +| Permissions | `documents.read`, `editor.edit`, `documents.save`, `editor.open`, `preview.open`, `browser.open`, `editor.actions` (also needs `documents.read`), `editor.providers` (also needs `documents.read`), `documents.contentProvider` (grants only `documents/registerContentProvider`, not reading or editing documents) | | Activation | As for the backend: `onWorkspaceOpen`, `onCommand:`, or a page call | | Lithe desktop | Declares `backend`; a backend finds which methods are usable with `getCapabilities` at runtime. See [Host status](#host-status) | @@ -111,6 +112,7 @@ Through the plugin-function protocol, a plugin backend reads open documents and | --- | --- | --- | --- | | `documents/list`, `documents/getSnapshot`, `editor/getActive`, `editor/getSelections` | `documents.read` | API-09 | Includes unsaved state, version, encoding, line endings; snapshots up to 128 KiB | | `editor/applyEdits`, `editor/replaceSelections`, `editor/insertText` | `editor.edit` | API-10 | Checks the document version; refused during IME composition and on read-only documents; one batch is one undo step | +| `documents/save`, `documents/saveAs`, `documents/close` | `documents.save` | API-11 | Saves through the document's owner, keeping its version, undo history and language session; a close saves first and never discards edits; a save-as target must not exist; a file changed on disk returns `diskChanged` with nothing written; nothing asks the user, see the [contract](../../contract/v1/README.md#saving-documents-and-changing-files) | | `editor/open`, `editor/reveal` | `editor.open` | API-15 | Returns `documentID` and version; a range only places the caret at its start | | `preview/openHTML` | `preview.open` | API-16 | `editorAndPreview` or `previewOnly` | | `browser/openExternal` | `browser.open` | API-16 | An HTTP(S) URL or saved HTML | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index c9ab575c..ef5511eb 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,7 @@ ## 待合入 +- [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-11):新增宿主方法 `documents/save`、`documents/saveAs`、`documents/close`(新权限 `documents.save`)和 `workspace/create`、`workspace/rename`、`workspace/copy`、`workspace/trash`(新权限 `workspace.files.write`)。每个权限只授予自己的方法,原有权限(包括聚合的 `workspace` 授权和 `documents.read`)都不授予它们。宿主经文档所有者保存,保留版本、撤销记录和语言会话;`close` 先保存再关闭,从不丢弃修改;`saveAs`、`create`、`rename`、`copy` 的目标已存在时失败,从不覆盖;`trash` 只移到系统废纸篓,没有永久删除;`rename`、`trash` 先保存其下打开的文档,保存失败就不动。这些方法不弹询问:需要用户选择的情形(未命名文档、硬链接文件、文件在磁盘上已改变)直接拒绝。新增失败码 `plugin.host.alreadyExists`(`-32080`,目标已存在)和 `plugin.host.diskChanged`(`-32081`,文件在磁盘上被改动或删除,没有写入)。清单 schema 的权限枚举加上两个新权限,fixture `backend/function-protocol.json` 新增 4 个宿主请求用例和 2 个失败码用例,`rust/fixtures/plugins/host-api-v1.json` 新增 4 个授权用例。四个官方 SDK 新增 7 个方法的封装和两个失败码。桌面端实现见 1lck/Lithe-IDEA#DESKTOPPR。没有新增能力版本、通知或 SDK 版本。 - [#176](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/176),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`languageServers` 0 内的说明补充(—):写明后端决定启动方式的语言服务器在 `immediate` 设置变化时的行为。启动应答自带 `workspaceConfiguration` 时,宿主用这次启动的四个目录、工作区 `context` 和新的 `settings` 再调用一次启动函数,同样交给 `plugins.languageServers.decodeLaunch` 解码,只把计划里的 `workspaceConfiguration` 通过 `lsp.updateWorkspaceConfiguration` 发出(整体替换原配置),应答的其余部分等下次启动;应答不带时发送声明的展开,不再调用函数。所以这类启动函数每次启动可能被调用多次,安装或下载只应在缺少时进行。契约 README 的 Workspace configuration 和 Backend-resolved launch 两节、`reference/domains/languages.md` 与 `settings.md` 的中英文随之补充。桌面端实现见 1lck/Lithe-IDEA#2319。Core 代码、能力版本、宿主方法、通知和协议字段都不变。 - [#175](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/175),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`ui` 0 内的补充(API-13、API-23):撤回 #174 新增的 `ui` 1,设置区域 `tool` 行的可选布尔字段 `choose` 改为 `ui` 0 内的补充,清单写 `requires.ui: 0` 即可使用。`capabilities.rs` 和清单 schema 的 `requires.ui` 回到只有 0,能力对照表删去 `ui` 1 一行。`choose` 不是布尔值时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`;旧宿主的 Core 不认识这个字段,同样会拒绝带它的视图,所以插件要等包含本改动的桌面端发布后再写。fixture `ui/view-results.json` 改为两个用例(接受选择器、`choose` 不是布尔值时拒绝),替换原来“`requires.ui` 为 0 时拒绝”的用例。`ui` 1 没有随任何宿主发布过。没有新增能力版本、宿主方法、通知或进程协议字段。 - [#174](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/174),[@xiaoyumuxi](https://github.com/xiaoyumuxi),**`ui` 1**(API-13、API-23):设置区域视图的 `tool` 行新增可选的布尔字段 `choose`,带上后这一行同时是该工具的选择器,像解释器下拉框一样列出自动选择、已发现和已添加的安装(带版本和来源)、添加目录和打开工具链页的入口;选择只改设置窗口的草稿,“应用”提交、“取消”丢弃,行上显示待提交的选择,应用后启动和运行拿到选中的安装。清单 `requires.ui` 为 0 时 Core 以 `plugin.ui.invalidView` 拒绝整个结果,位置指向 `choose`。契约 README 的插件视图一节补充:为某个工作区显示的视图(项目窗口里的工具窗口,或从项目窗口打开的设置页)调用时,带上该窗口的工作区上下文作为 invoke 的 `params.context`,后端可以在 `click` 里用它调用 `run/start` 等需要上下文的宿主方法;没有工作区时不带。fixture `ui/view-results.json` 新增一个用例,Node SDK 的视图节点类型加上 `choose`,Rust 和 Go SDK 的工作区上下文说明随之修正。没有新增宿主方法、通知或进程协议字段。(`ui` 1 已由 #175 撤回,`choose` 改为 `ui` 0 内的补充。) @@ -122,6 +123,13 @@ | API-10 | `editor/applyEdits` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-10 | `editor/replaceSelections` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-10 | `editor/insertText` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | +| API-11 | `documents/save` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `documents/saveAs` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `documents/close` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `workspace/create` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `workspace/rename` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `workspace/copy` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | +| API-11 | `workspace/trash` | 0 | 待合入 | [#API11PR](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/API11PR) | | API-12 | `documents/registerContentProvider` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-15 | `editor/open` | 0 | 2026-11-11 | [#17](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/17) | | API-15 | `editor/reveal` | 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 30d05f59..fa7faf09 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -274,6 +274,7 @@ must(backend.OnCommand("db.refresh", func(_ string, workspace *lithe.WorkspaceCo | `Workspace().GetHostPaths(context, rootIDs...)`, `.ProcessRoots(context)` | Root paths on the remote host of a remote context; see [Remote workspaces](#remote-workspaces). | | `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). | | `Preview().OpenHTML`, `Browser().OpenExternal`, `Window().ShowInformation`, `.ShowWarning`, `.ShowError` | Preview, browser, and messages. | | `Terminal().Create`, `.Show`, `.Close`, `.Reopen`, `.Dispose`, `.OnExit` | Native terminals; see [Native terminal API](#native-terminal-api). | | `Functions().Providers(functionID)`, `.Invoke(context, call)` | The plugins that export a function, and a call to one of them; see [Calling other plugins](#calling-other-plugins). | @@ -303,7 +304,7 @@ What the SDK does for you, and what it leaves to you: reread and recompute; on `contextExpired` resolve the original target again, never the focused window; retry `busy` and `rateLimited` (after the `retryAfterMilliseconds` detail) with a bound; `permissionDenied` and - `readOnly` need the user. An unknown param is + `readOnly` need the user, and so does `diskChanged`; on `alreadyExists` pick another target. An unknown param is `plugin.host.unsupportedOption` naming it in the `option` detail, so you can retry without it. `lithe.HostErrorCodes` lists the codes and numbers the contract defines. diff --git a/shared/plugins/sdk/go/lithe/errors.go b/shared/plugins/sdk/go/lithe/errors.go index e437ad27..d04c0d5f 100644 --- a/shared/plugins/sdk/go/lithe/errors.go +++ b/shared/plugins/sdk/go/lithe/errors.go @@ -44,6 +44,8 @@ var HostErrorCodes = []ErrorCode{ {"plugin.host.foreignContribution", -32026}, {"plugin.host.remoteDisconnected", -32078}, {"plugin.host.platformUnavailable", -32079}, + {"plugin.host.alreadyExists", -32080}, + {"plugin.host.diskChanged", -32081}, } // RelayErrorCodes are the codes a cross-plugin call fails with. diff --git a/shared/plugins/sdk/go/lithe/errors_test.go b/shared/plugins/sdk/go/lithe/errors_test.go index cf8df428..b27295e9 100644 --- a/shared/plugins/sdk/go/lithe/errors_test.go +++ b/shared/plugins/sdk/go/lithe/errors_test.go @@ -68,7 +68,7 @@ func TestHostFailuresKeepTheirCodeOrTakeItFromTheNumber(t *testing.T) { } func TestTheHostAndRelayTablesHoldEveryDocumentedCodeOnce(t *testing.T) { - if len(HostErrorCodes) != 23 || len(RelayErrorCodes) != 11 { + if len(HostErrorCodes) != 25 || len(RelayErrorCodes) != 11 { t.Fatalf("tables hold %d and %d codes", len(HostErrorCodes), len(RelayErrorCodes)) } codes := map[string]bool{} diff --git a/shared/plugins/sdk/go/lithe/host.go b/shared/plugins/sdk/go/lithe/host.go index 7bffe747..d1934e21 100644 --- a/shared/plugins/sdk/go/lithe/host.go +++ b/shared/plugins/sdk/go/lithe/host.go @@ -1052,6 +1052,32 @@ func (w *Workspace) FindText(context WorkspaceContext, params any) (json.RawMess return w.host.scoped(methodFindText, context, params) } +// Create takes resource, kind ("file" or "directory") and text? for a file, +// and answers { resource, kind }. It never overwrites: an existing resource is +// plugin.host.alreadyExists. +func (w *Workspace) Create(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodCreate, context, params) +} + +// Rename takes resource and target, the full new path, and answers +// { resource }. The host saves the open documents under resource first, and +// they follow the file. +func (w *Workspace) Rename(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodRename, context, params) +} + +// Copy takes resource and target, a path that does not exist, and answers +// { resource } of the copy. +func (w *Workspace) Copy(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodCopy, context, params) +} + +// Trash takes resource and moves it to the system trash after saving and +// closing its open documents; nothing is deleted permanently. +func (w *Workspace) Trash(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodTrash, context, params) +} + // Documents is open documents, read from their live buffers. type Documents struct{ host *Host } @@ -1065,6 +1091,25 @@ func (d *Documents) GetSnapshot(context WorkspaceContext, params any) (json.RawM return d.host.scoped(methodDocumentsSnap, context, params) } +// Save takes documentID, expectedVersion? and answers { document } after the +// write. A file changed on disk is plugin.host.diskChanged, and nothing is +// written. +func (d *Documents) Save(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsSave, context, params) +} + +// SaveAs takes documentID and target, a path that does not exist, and answers +// { document } of the new file, which the host opens. +func (d *Documents) SaveAs(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsAs, context, params) +} + +// Close takes documentID, saves the document and then closes its tab; it +// never discards the user's edits. +func (d *Documents) Close(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsClose, context, params) +} + // Editor is the text editor. type Editor struct{ host *Host } diff --git a/shared/plugins/sdk/go/lithe/host_services_test.go b/shared/plugins/sdk/go/lithe/host_services_test.go index d11535aa..3e23f5b1 100644 --- a/shared/plugins/sdk/go/lithe/host_services_test.go +++ b/shared/plugins/sdk/go/lithe/host_services_test.go @@ -803,6 +803,47 @@ func TestNativeTerminalMethodsKeepContextAndLiteralArguments(t *testing.T) { s.close() } +func TestSaveAndFileChangeMethodsCarryTheirParamsWithTheContext(t *testing.T) { + backend := lithe.NewBackend("file-changes-test") + host := backend.Handle().Host() + s := startSession(t, backend, []any{0}) + resource := map[string]any{"rootID": "r1", "path": "src/a.txt"} + target := map[string]any{"rootID": "r1", "path": "src/b.txt"} + for _, call := range []struct { + method string + params map[string]any + run func(map[string]any) (json.RawMessage, error) + }{ + {"documents/save", map[string]any{"documentID": "d1", "expectedVersion": 3}, + func(p map[string]any) (json.RawMessage, error) { return host.Documents().Save(testContext(), p) }}, + {"documents/saveAs", map[string]any{"documentID": "d1", "target": target}, + func(p map[string]any) (json.RawMessage, error) { return host.Documents().SaveAs(testContext(), p) }}, + {"documents/close", map[string]any{"documentID": "d1"}, + func(p map[string]any) (json.RawMessage, error) { return host.Documents().Close(testContext(), p) }}, + {"workspace/create", map[string]any{"resource": resource, "kind": "file", "text": "x"}, + func(p map[string]any) (json.RawMessage, error) { return host.Workspace().Create(testContext(), p) }}, + {"workspace/rename", map[string]any{"resource": resource, "target": target}, + func(p map[string]any) (json.RawMessage, error) { return host.Workspace().Rename(testContext(), p) }}, + {"workspace/copy", map[string]any{"resource": resource, "target": target}, + func(p map[string]any) (json.RawMessage, error) { return host.Workspace().Copy(testContext(), p) }}, + {"workspace/trash", map[string]any{"resource": resource}, + func(p map[string]any) (json.RawMessage, error) { return host.Workspace().Trash(testContext(), p) }}, + } { + operation := background(func() (json.RawMessage, error) { return call.run(call.params) }) + request := s.take("lithe/host/" + call.method) + eq(t, at(request, "params", "context"), `{"contextID": "w1", "generation": 2}`) + for key, value := range call.params { + want, _ := json.Marshal(value) + eq(t, at(request, "params", key), string(want)) + } + s.reply(request, nil) + result := done(t, operation) + must(t, result.err) + eq(t, result.value, `null`) + } + s.close() +} + func TestHostPathRootIDsCoreRefusesFailLocallyAndTheAnswerHoldsHostPaths(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 785a2da3..0b02a6cd 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -46,8 +46,15 @@ const ( methodWatch = "lithe/host/workspace/watch" methodFindFiles = "lithe/host/workspace/findFiles" methodFindText = "lithe/host/workspace/findText" + methodCreate = "lithe/host/workspace/create" + methodRename = "lithe/host/workspace/rename" + methodCopy = "lithe/host/workspace/copy" + methodTrash = "lithe/host/workspace/trash" methodDocumentsList = "lithe/host/documents/list" methodDocumentsSnap = "lithe/host/documents/getSnapshot" + methodDocumentsSave = "lithe/host/documents/save" + methodDocumentsAs = "lithe/host/documents/saveAs" + methodDocumentsClose = "lithe/host/documents/close" methodEditorActions = "lithe/host/editor/registerActions" methodEditorActive = "lithe/host/editor/getActive" methodEditorSelect = "lithe/host/editor/getSelections" diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 4501f4f2..dafe7ba4 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().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). | | `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. | | `functions().providers(functionId)`, `.invoke(context, call)` | [Calls to other plugins' functions](#calling-other-plugins), relayed by Core. | | `request(method, params)`, `subscribe(method, params, listener)` | Any `lithe/host/*` method, including ones a later host adds. | @@ -320,7 +321,7 @@ What the SDK does for you, and what it leaves to you: reread and recompute; on `contextExpired` resolve the original target again, never the focused window; retry `busy` and `rateLimited` (after `details().get("retryAfterMilliseconds")`) with a bound; `permissionDenied` - and `readOnly` need the user. An unknown param is + and `readOnly` need the user, and so does `diskChanged`; on `alreadyExists` pick another target. An unknown param is `plugin.host.unsupportedOption` naming it in `details().get("option")`, so you can retry without it. - **Cancellation has no rollback.** Cancelling the token given to 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 af7b9b33..49e40387 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 @@ -532,6 +532,37 @@ public CompletableFuture> findFiles(Map context, public CompletableFuture> findText(Map context, Map params) { return scoped(Protocol.HOST_WORKSPACE_FIND_TEXT, context, params); } + + /** + * Permission {@code workspace.files.write}. {@code params}: {@code resource, kind} ({@code "file"} or + * {@code "directory"}) and {@code text?} for a file; answers {@code { resource, kind }}. An existing + * {@code resource} fails with {@code plugin.host.alreadyExists}; nothing is overwritten. + */ + public CompletableFuture> create(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_CREATE, context, params); + } + + /** + * Permission {@code workspace.files.write}. {@code params}: {@code resource, target}, the full new path; + * answers {@code { resource }}. The host saves the open documents under {@code resource} first, and they + * follow the move. + */ + public CompletableFuture> rename(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_RENAME, context, params); + } + + /** Permission {@code workspace.files.write}. {@code params}: {@code resource, target}; answers {@code { resource }}. */ + public CompletableFuture> copy(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_COPY, context, params); + } + + /** + * Permission {@code workspace.files.write}. {@code params}: {@code resource}; answers null. The host saves + * and closes the open documents under it, then moves it to the system trash. + */ + public CompletableFuture> trash(Map context, Map params) { + return scoped(Protocol.HOST_WORKSPACE_TRASH, context, params); + } } /** Open documents, read from their live buffers. */ @@ -547,6 +578,31 @@ public CompletableFuture> list(Map context) { public CompletableFuture> getSnapshot(Map context, Map params) { return scoped(Protocol.HOST_DOCUMENTS_GET_SNAPSHOT, context, params); } + + /** + * Permission {@code documents.save}. {@code params}: {@code documentID, expectedVersion?}; answers + * {@code { document }}. A file changed on disk fails with {@code plugin.host.diskChanged}, and nothing is + * written. + */ + public CompletableFuture> save(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_SAVE, context, params); + } + + /** + * Permission {@code documents.save}. {@code params}: {@code documentID, target}, which must not exist; + * answers {@code { document }} of the new file, which the host opens. + */ + public CompletableFuture> saveAs(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_SAVE_AS, context, params); + } + + /** + * Permission {@code documents.save}. {@code params}: {@code documentID}; answers null. The host saves the + * document first and never discards the user's edits. + */ + public CompletableFuture> close(Map context, Map params) { + return scoped(Protocol.HOST_DOCUMENTS_CLOSE, context, params); + } } /** The text editor. */ diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java index 327a6c5c..c71e3561 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/HostError.java @@ -59,6 +59,8 @@ public final class HostError extends PluginSdkError { codes.put("plugin.function.invalidResult", -32071); codes.put("plugin.host.remoteDisconnected", -32078); codes.put("plugin.host.platformUnavailable", -32079); + codes.put("plugin.host.alreadyExists", -32080); + codes.put("plugin.host.diskChanged", -32081); CODES = Collections.unmodifiableMap(codes); Map byNumber = new HashMap<>(); for (Map.Entry entry : codes.entrySet()) { 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 e3f3ca2a..9bb2d225 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 @@ -71,8 +71,15 @@ public final class Protocol { public static final String HOST_WORKSPACE_WATCH = "lithe/host/workspace/watch"; public static final String HOST_WORKSPACE_FIND_FILES = "lithe/host/workspace/findFiles"; public static final String HOST_WORKSPACE_FIND_TEXT = "lithe/host/workspace/findText"; + public static final String HOST_WORKSPACE_CREATE = "lithe/host/workspace/create"; + public static final String HOST_WORKSPACE_RENAME = "lithe/host/workspace/rename"; + public static final String HOST_WORKSPACE_COPY = "lithe/host/workspace/copy"; + public static final String HOST_WORKSPACE_TRASH = "lithe/host/workspace/trash"; public static final String HOST_DOCUMENTS_LIST = "lithe/host/documents/list"; public static final String HOST_DOCUMENTS_GET_SNAPSHOT = "lithe/host/documents/getSnapshot"; + public static final String HOST_DOCUMENTS_SAVE = "lithe/host/documents/save"; + public static final String HOST_DOCUMENTS_SAVE_AS = "lithe/host/documents/saveAs"; + public static final String HOST_DOCUMENTS_CLOSE = "lithe/host/documents/close"; public static final String HOST_EDITOR_REGISTER_ACTIONS = "lithe/host/editor/registerActions"; public static final String HOST_EDITOR_GET_ACTIVE = "lithe/host/editor/getActive"; public static final String HOST_EDITOR_GET_SELECTIONS = "lithe/host/editor/getSelections"; 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 6ef915a5..21b70087 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 @@ -17,6 +17,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -27,6 +28,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; @@ -127,6 +129,46 @@ void nativeTerminalMethodsKeepContextAndLiteralArguments() { } finally { host.close(); } } + @Test + void saveAndFileChangeMethodsCarryTheirParamsWithTheContext() { + Backend backend = Backend.create(null, null); + TestHost host = session(backend); + try { + Map resource = map("rootID", "r1", "path", "src/a.txt"); + Map target = map("rootID", "r1", "path", "src/b.txt"); + Host.Workspace workspace = backend.host().workspace(); + Host.Documents documents = backend.host().documents(); + Map calls = new LinkedHashMap<>(); + calls.put(Protocol.HOST_DOCUMENTS_SAVE, map("documentID", "d1", "expectedVersion", 3L)); + calls.put(Protocol.HOST_DOCUMENTS_SAVE_AS, map("documentID", "d1", "target", target)); + calls.put(Protocol.HOST_DOCUMENTS_CLOSE, map("documentID", "d1")); + calls.put(Protocol.HOST_WORKSPACE_CREATE, map("resource", resource, "kind", "file", "text", "x")); + calls.put(Protocol.HOST_WORKSPACE_RENAME, map("resource", resource, "target", target)); + calls.put(Protocol.HOST_WORKSPACE_COPY, map("resource", resource, "target", target)); + calls.put(Protocol.HOST_WORKSPACE_TRASH, map("resource", resource)); + Map, Map, CompletableFuture>>> wrappers = + new LinkedHashMap<>(); + wrappers.put(Protocol.HOST_DOCUMENTS_SAVE, documents::save); + wrappers.put(Protocol.HOST_DOCUMENTS_SAVE_AS, documents::saveAs); + wrappers.put(Protocol.HOST_DOCUMENTS_CLOSE, documents::close); + wrappers.put(Protocol.HOST_WORKSPACE_CREATE, workspace::create); + wrappers.put(Protocol.HOST_WORKSPACE_RENAME, workspace::rename); + wrappers.put(Protocol.HOST_WORKSPACE_COPY, workspace::copy); + wrappers.put(Protocol.HOST_WORKSPACE_TRASH, workspace::trash); + for (Map.Entry call : calls.entrySet()) { + String method = call.getKey(); + Map params = object(call.getValue()); + CompletableFuture> answer = wrappers.get(method).apply(CONTEXT, params); + Map request = nextRequest(host, method); + Map expected = new LinkedHashMap<>(params); + expected.put("context", CONTEXT); + assertEquals(expected, object(request.get("params")), method); + host.send(map("id", request.get("id"), "result", null)); + assertNull(value(answer), method); + } + } finally { host.close(); } + } + @Test void theSdkAnswersPluginFunctionsOnlyWhenTheHostOffersVersionZero() { Object[][] cases = {{Arrays.asList(0L), true}, {Arrays.asList(2L, 99L, 0L), true}, {Arrays.asList(1L), false}, diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 77fde6dd..17d9c9c8 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -290,6 +290,7 @@ backend.onCommand('db.refresh', async ({ workspaceContext }) => { | `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.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). | | `preview.openHTML`, `browser.openExternal`, `window.showInformation`, `.showWarning`, `.showError` | Preview, browser, and messages. | | `functions.providers(functionID)` | The enabled plugins that export a function: `{ providers: [{ pluginID, version }] }`. See [Calling other plugins](#calling-other-plugins). | | `functions.invoke(context, call)` | Calls one provider's exported function in a workspace context: `{ value }`. `call` is `{ pluginID, functionID, params?, timeoutMilliseconds?, parentOperationID? }`. | @@ -316,7 +317,7 @@ What the SDK does for you, and what it leaves to you: `HostError`. On `versionConflict` reread and recompute; on `contextExpired` resolve the original target again, never the focused window; retry `busy` and `rateLimited` (after `details.retryAfterMilliseconds`) with a bound; - `permissionDenied` and `readOnly` need the user. An unknown param is + `permissionDenied` and `readOnly` need the user, and so does `diskChanged`; on `alreadyExists` pick another target. An unknown param is `plugin.host.unsupportedOption` naming it in `details.option`, so you can retry without it. - **Cancellation has no rollback.** Aborting a request's signal, or ending diff --git a/shared/plugins/sdk/node/src/host.mjs b/shared/plugins/sdk/node/src/host.mjs index ff45a7ca..9792a310 100644 --- a/shared/plugins/sdk/node/src/host.mjs +++ b/shared/plugins/sdk/node/src/host.mjs @@ -303,6 +303,10 @@ export function createHost(channel, callSignal, parentOperationId) { subscribe(HOST_METHODS.workspaceWatch, { ...params, context: contextReference(context) }, onEvent, options), findFiles: scoped(HOST_METHODS.workspaceFindFiles), findText: scoped(HOST_METHODS.workspaceFindText), + create: scoped(HOST_METHODS.workspaceCreate), + rename: scoped(HOST_METHODS.workspaceRename), + copy: scoped(HOST_METHODS.workspaceCopy), + trash: scoped(HOST_METHODS.workspaceTrash), }), functions: Object.freeze({ providers: async (functionID, options) => { @@ -315,6 +319,9 @@ export function createHost(channel, callSignal, parentOperationId) { documents: Object.freeze({ list: scoped(HOST_METHODS.documentsList), getSnapshot: scoped(HOST_METHODS.documentsGetSnapshot), + save: scoped(HOST_METHODS.documentsSave), + saveAs: scoped(HOST_METHODS.documentsSaveAs), + close: scoped(HOST_METHODS.documentsClose), }), editor: Object.freeze({ getActive: scoped(HOST_METHODS.editorGetActive), diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index a8cbb222..4ca8937f 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -330,11 +330,37 @@ export interface Host { cursor?: string; limit?: number; }, FindPage<{ resource: WorkspaceResource; line: number; preview: string; range: TextRange | null }>>; + /** + * Permission `workspace.files.write`. Never overwrites: an existing + * `resource` is `plugin.host.alreadyExists`. `text` is for a file only. + */ + create: Scoped<{ resource: WorkspaceResource; kind: 'file' | 'directory'; text?: string }, { resource: WorkspaceResource; kind: 'file' | 'directory' }>; + /** + * Permission `workspace.files.write`. `target` is the full new path. The + * host saves the open documents under `resource` first; they follow the file. + */ + rename: Scoped<{ resource: WorkspaceResource; target: WorkspaceResource }, { resource: WorkspaceResource }>; + /** Permission `workspace.files.write`. `target` must not exist. */ + copy: Scoped<{ resource: WorkspaceResource; target: WorkspaceResource }, { resource: WorkspaceResource }>; + /** + * Permission `workspace.files.write`. Saves and closes the open documents + * under `resource`, then moves it to the system trash; nothing is deleted permanently. + */ + trash: Scoped<{ resource: WorkspaceResource }, null>; }; - /** Permission `documents.read`. */ + /** Permission `documents.read`, and `documents.save` for `save`, `saveAs` and `close`. */ readonly documents: { list: ScopedOptional; getSnapshot: Scoped<{ documentID: string }, { document: DocumentSummary; text: string }>; + /** + * Writes the document's current text. A file changed on disk is + * `plugin.host.diskChanged`, and nothing is written. + */ + save: Scoped<{ documentID: string; expectedVersion?: number }, { document: DocumentSummary }>; + /** Writes to `target`, which must not exist, and opens the new file. */ + saveAs: Scoped<{ documentID: string; target: WorkspaceResource }, { document: DocumentSummary }>; + /** Saves the document, then closes its tab; never discards the user's edits. */ + close: Scoped<{ documentID: string }, null>; }; readonly editor: { getActive: ScopedOptional; @@ -903,6 +929,8 @@ export const HOST_ERRORS: Readonly<{ 'plugin.function.invalidResult': -32071; 'plugin.host.remoteDisconnected': -32078; 'plugin.host.platformUnavailable': -32079; + 'plugin.host.alreadyExists': -32080; + 'plugin.host.diskChanged': -32081; }>; /** Host request method names. */ @@ -911,7 +939,9 @@ export const HOST_METHODS: Readonly { + const { backend, host } = await session(); + try { + const resource = { rootID: 'r1', path: 'src/a.txt' }; + const target = { rootID: 'r1', path: 'src/b.txt' }; + const calls = [ + ['documents/save', backend.host.documents.save, { documentID: 'd1', expectedVersion: 3 }], + ['documents/saveAs', backend.host.documents.saveAs, { documentID: 'd1', target }], + ['documents/close', backend.host.documents.close, { documentID: 'd1' }], + ['workspace/create', backend.host.workspace.create, { resource, kind: 'file', text: 'x' }], + ['workspace/rename', backend.host.workspace.rename, { resource, target }], + ['workspace/copy', backend.host.workspace.copy, { resource, target }], + ['workspace/trash', backend.host.workspace.trash, { resource }], + ]; + for (const [method, call, params] of calls) { + const answer = call(CONTEXT, params); + const sent = await nextRequest(host, `lithe/host/${method}`); + assert.deepEqual(sent.params, { ...params, context: CONTEXT }, method); + host.send({ id: sent.id, result: null }); + assert.equal(await answer, null, method); + } + } finally { await host.close(); } +}); + const RELAY_PROVIDERS = 'lithe/host/functions/providers'; const RELAY_INVOKE = 'lithe/host/functions/invoke'; /** The provider and function the fixture's relay cases name. */ diff --git a/shared/plugins/sdk/node/test/types/host.mts b/shared/plugins/sdk/node/test/types/host.mts index d0a5dd36..426887ea 100644 --- a/shared/plugins/sdk/node/test/types/host.mts +++ b/shared/plugins/sdk/node/test/types/host.mts @@ -170,4 +170,27 @@ async function remoteRoots(context: WorkspaceContext) { const unavailable: -32079 = HOST_ERRORS['plugin.host.platformUnavailable']; void failure; void unavailable; } + +async function fileChanges(context: WorkspaceContext) { + const resource = { rootID: context.folders[0]!.rootID, path: 'notes/today.md' }; + const created = await backend.host.workspace.create(context, { resource, kind: 'file', text: '# Today' }); + const kind: 'file' | 'directory' = created.kind; + void kind; + // @ts-expect-error A created item is a file or a directory. + await backend.host.workspace.create(context, { resource, kind: 'link' }); + await backend.host.workspace.rename(context, { resource, target: { ...resource, path: 'notes/done.md' } }); + await backend.host.workspace.copy(context, { resource, target: { ...resource, path: 'notes/copy.md' } }); + const trashed: null = await backend.host.workspace.trash(context, { resource }); + void trashed; + const saved = await backend.host.documents.save(context, { documentID: 'd1', expectedVersion: 2 }); + const dirty: boolean = saved.document.isDirty; + void dirty; + await backend.host.documents.saveAs(context, { documentID: 'd1', target: resource }); + const closed: null = await backend.host.documents.close(context, { documentID: 'd1' }); + void closed; + const exists: -32080 = HOST_ERRORS['plugin.host.alreadyExists']; + const changed: -32081 = HOST_ERRORS['plugin.host.diskChanged']; + void exists; void changed; +} +void fileChanges; void remoteRoots; diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 02f759f2..25da91ab 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -373,6 +373,7 @@ backend | `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). | | `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. | | `functions().providers(function_id)`, `.invoke(&context, call)` | The plugins that export a function, and a call to one of them; see [Calling other plugins](#calling-other-plugins). | | `request(method, params)`, `subscribe(method, params)` | Any `lithe/host/*` method, including ones a later host adds. | @@ -400,7 +401,7 @@ What the SDK does for you, and what it leaves to you: kept as sent. On `versionConflict` reread and recompute; on `contextExpired` resolve the original target again, never the focused window; retry `busy` and `rateLimited` (after the `retryAfterMilliseconds` detail) with a - bound; `permissionDenied` and `readOnly` need the user. An unknown param is + bound; `permissionDenied` and `readOnly` need the user, and so does `diskChanged`; on `alreadyExists` pick another target. An unknown param is `plugin.host.unsupportedOption` naming it in the `option` detail, so you can retry without it. - **Cancellation has no rollback.** Cancelling the token given to diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/error.rs b/shared/plugins/sdk/rust/plugin-sdk/src/error.rs index 7fa049b0..aa7ba438 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/error.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/error.rs @@ -91,7 +91,7 @@ pub mod sdk_codes { /// Stable `plugin.host.*` failure codes and their JSON-RPC numbers. A later /// host adds codes at numbers no code of the contract uses yet. -pub const HOST_ERROR_CODES: [(&str, i64); 23] = [ +pub const HOST_ERROR_CODES: [(&str, i64); 25] = [ ("plugin.host.unavailable", -32601), ("plugin.host.invalidParams", -32602), ("plugin.host.failed", -32603), @@ -115,6 +115,8 @@ pub const HOST_ERROR_CODES: [(&str, i64); 23] = [ ("plugin.host.foreignContribution", -32026), ("plugin.host.remoteDisconnected", -32078), ("plugin.host.platformUnavailable", -32079), + ("plugin.host.alreadyExists", -32080), + ("plugin.host.diskChanged", -32081), ]; /// The `plugin.function.*` failures a relayed call from another plugin may @@ -337,7 +339,7 @@ mod tests { #[test] fn the_host_and_relay_tables_hold_every_documented_code_once() { - assert_eq!(HOST_ERROR_CODES.len(), 23); + assert_eq!(HOST_ERROR_CODES.len(), 25); assert_eq!(RELAY_ERROR_CODES.len(), 11); let mut codes = std::collections::BTreeSet::new(); let mut numbers = std::collections::BTreeSet::new(); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs index 15067e54..0651a7af 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/host.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/host.rs @@ -916,6 +916,32 @@ impl Workspace { self.host .scoped(methods::WORKSPACE_FIND_TEXT, context, params) } + + /// `params`: `resource, kind` (`"file"` or `"directory"`), `text?` for a + /// file; answers `{ resource, kind }`. Never overwrites: an existing + /// resource is `plugin.host.alreadyExists`. + pub fn create(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::WORKSPACE_CREATE, context, params) + } + + /// `params`: `resource, target`, the full new path; answers + /// `{ resource }`. The host saves the open documents under `resource` + /// first, and they follow the file. + pub fn rename(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::WORKSPACE_RENAME, context, params) + } + + /// `params`: `resource, target`, a path that does not exist; answers + /// `{ resource }` of the copy. + pub fn copy(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::WORKSPACE_COPY, context, params) + } + + /// `params`: `resource`. Saves and closes its open documents, then moves + /// it to the system trash; nothing is deleted permanently. + pub fn trash(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::WORKSPACE_TRASH, context, params) + } } /// A path on the remote host of a `remote` workspace context, from @@ -1085,6 +1111,26 @@ impl Documents { self.host .scoped(methods::DOCUMENTS_GET_SNAPSHOT, context, params) } + + /// `params`: `documentID, expectedVersion?`; answers `{ document }` after + /// the write. A file changed on disk is `plugin.host.diskChanged`, and + /// nothing is written. + pub fn save(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::DOCUMENTS_SAVE, context, params) + } + + /// `params`: `documentID, target`, a path that does not exist; answers + /// `{ document }` of the new file, which the host opens. + pub fn save_as(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host + .scoped(methods::DOCUMENTS_SAVE_AS, context, params) + } + + /// `params`: `documentID`. Saves the document, then closes its tab; it + /// never discards the user's edits. + pub fn close(&self, context: &WorkspaceContext, params: Value) -> Result { + self.host.scoped(methods::DOCUMENTS_CLOSE, context, params) + } } /// The text editor. diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs index 84383352..b948da26 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/protocol.rs @@ -58,8 +58,15 @@ pub(crate) mod methods { pub const WORKSPACE_WATCH: &str = "lithe/host/workspace/watch"; pub const WORKSPACE_FIND_FILES: &str = "lithe/host/workspace/findFiles"; pub const WORKSPACE_FIND_TEXT: &str = "lithe/host/workspace/findText"; + pub const WORKSPACE_CREATE: &str = "lithe/host/workspace/create"; + pub const WORKSPACE_RENAME: &str = "lithe/host/workspace/rename"; + pub const WORKSPACE_COPY: &str = "lithe/host/workspace/copy"; + pub const WORKSPACE_TRASH: &str = "lithe/host/workspace/trash"; pub const DOCUMENTS_LIST: &str = "lithe/host/documents/list"; pub const DOCUMENTS_GET_SNAPSHOT: &str = "lithe/host/documents/getSnapshot"; + pub const DOCUMENTS_SAVE: &str = "lithe/host/documents/save"; + pub const DOCUMENTS_SAVE_AS: &str = "lithe/host/documents/saveAs"; + pub const DOCUMENTS_CLOSE: &str = "lithe/host/documents/close"; pub const EDITOR_REGISTER_ACTIONS: &str = "lithe/host/editor/registerActions"; pub const EDITOR_GET_ACTIVE: &str = "lithe/host/editor/getActive"; pub const EDITOR_GET_SELECTIONS: &str = "lithe/host/editor/getSelections"; 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 a40f76c3..c762041d 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/host_services.rs @@ -783,6 +783,60 @@ fn native_terminal_methods_keep_context_and_literal_arguments() { session.close(); } +#[test] +fn save_and_file_change_methods_carry_their_params_with_the_context() { + let backend = Backend::new("file-changes-test"); + let handle = backend.handle(); + let mut session = Session::start(backend); + let resource = json!({ "rootID": "r1", "path": "src/a.txt" }); + let target = json!({ "rootID": "r1", "path": "src/b.txt" }); + let calls = [ + ( + "documents/save", + json!({ "documentID": "d1", "expectedVersion": 3 }), + ), + ( + "documents/saveAs", + json!({ "documentID": "d1", "target": target }), + ), + ("documents/close", json!({ "documentID": "d1" })), + ( + "workspace/create", + json!({ "resource": resource, "kind": "file", "text": "x" }), + ), + ( + "workspace/rename", + json!({ "resource": resource, "target": target }), + ), + ( + "workspace/copy", + json!({ "resource": resource, "target": target }), + ), + ("workspace/trash", json!({ "resource": resource })), + ]; + for (method, params) in calls { + let host = handle.host(); + let sent = params.clone(); + let operation = background(move || match method { + "documents/save" => host.documents().save(&context(), sent), + "documents/saveAs" => host.documents().save_as(&context(), sent), + "documents/close" => host.documents().close(&context(), sent), + "workspace/create" => host.workspace().create(&context(), sent), + "workspace/rename" => host.workspace().rename(&context(), sent), + "workspace/copy" => host.workspace().copy(&context(), sent), + _ => host.workspace().trash(&context(), sent), + }); + let request = session.take(&format!("lithe/host/{method}")); + assert_eq!(request["params"]["context"], context().to_value()); + for (key, value) in params.as_object().unwrap() { + assert_eq!(&request["params"][key], value, "{method} {key}"); + } + session.reply(&request, Value::Null); + assert_eq!(done(&operation).unwrap(), Value::Null); + } + session.close(); +} + #[test] fn host_path_root_ids_core_refuses_fail_locally_and_the_answer_holds_host_paths() { let backend = Backend::new("test-backend");