Give plugins SDK APIs for terminals, granted folders, and plugin services
Plugins can now do through the SDK what they did with direct native calls. The SDK checks plugin shutdown, so these APIs can move to an isolated plugin context later. - api.pty opens shell sessions. pty_open accepts an optional channel. A channel session sends its output as raw bytes to its own webview and sends no pty-data or pty-exit events. Without a channel, the events stay, so the released Terminal plugin keeps working. The host closes the open sessions of a plugin when the plugin stops. - api.files gives folder grants. The user selects the folder, the host keeps the grants of each plugin in its retained data, and the plugin uses an opaque grant ID. The host rejects names with folder parts, links, and files over the size limit. Sidecar JSON files replace the per-image settings commands. - api.services lets one plugin offer data to another plugin in the same window. The host copies arguments and results. - The folder methods of api.backgrounds are deprecated. They stay for released Background Slideshow versions. - The plugin reference lists the native calls of each plugin and the SDK member that replaces each call.
This commit is contained in:
+103
-6
@@ -9,6 +9,10 @@ This reference gives the package contract, the build procedure, and the API for
|
||||
- [Build examples](#build-examples)
|
||||
- [Versions and releases](#versions-and-releases)
|
||||
- [Plugin API](#plugin-api)
|
||||
- [Use the SDK instead of native calls](#use-the-sdk-instead-of-native-calls)
|
||||
- [Terminal API](#terminal-api)
|
||||
- [Folder grants](#folder-grants)
|
||||
- [Plugin services](#plugin-services)
|
||||
- [Git API](#git-api)
|
||||
- [Background API](#background-api)
|
||||
|
||||
@@ -227,6 +231,9 @@ Older hosts ignore unknown fields in objects that you pass to the host, such as
|
||||
| `ui.showActionMenu(options)` | yes | Open the shared RuneStone action menu. See [Menus](#menus). |
|
||||
| `completion` | yes | Autocomplete fields and providers. See the [completion API](completion.md). |
|
||||
| `git` | yes | Git operations for the active workspace. See [Git API](#git-api). |
|
||||
| `pty` | yes | Terminal sessions. See [Terminal API](#terminal-api). |
|
||||
| `files` | yes | Folders outside the workspace that the user granted to the plugin. See [Folder grants](#folder-grants). |
|
||||
| `services` | yes | Data that one plugin offers to other plugins. See [Plugin services](#plugin-services). |
|
||||
| `backgrounds` | yes | Background image frames. See [Background API](#background-api). |
|
||||
|
||||
### Commands
|
||||
@@ -351,6 +358,92 @@ Only one enabled plugin can own each key. The host removes contributions before
|
||||
|
||||
A terminal contribution must stop its controls and native sessions before its cleanup finishes.
|
||||
|
||||
## Use the SDK instead of native calls
|
||||
|
||||
Do not call `invoke`, `listen`, or other `@tauri-apps/api` functions from a plugin. Do not read the private files of other plugins.
|
||||
Use the `api` members below. They check plugin shutdown, and they will stay available when a later host runs each plugin in its own isolated context.
|
||||
Make sure that an optional member exists before you use it. Keep the native call only as a fallback for older hosts.
|
||||
|
||||
The host still accepts the native calls of released plugins. A later host can remove them.
|
||||
|
||||
| Plugin | Current call | Purpose | Use instead |
|
||||
| --- | --- | --- | --- |
|
||||
| Terminal | `invoke("pty_open")`, `listen("pty-data")`, `listen("pty-exit")` | Start a shell and receive its output and exit code | `api.pty.open({ ..., onData, onExit })` |
|
||||
| Terminal | `invoke("pty_write")`, `invoke("pty_resize")`, `invoke("pty_close")` | Send input, change the size, stop the shell | `write`, `resize`, and `close` of the session from `api.pty.open` |
|
||||
| Terminal | `invoke("pty_profiles")` | List the installed shells | `api.pty.profiles()` |
|
||||
| Terminal | `invoke("pty_new_window")` | Open a terminal window | `api.pty.openWindow()` |
|
||||
| Terminal | `invoke("pty_dictation")` | Start Windows voice typing | `api.pty.dictation()` |
|
||||
| Terminal | `invoke("workspace_read", { rel: ".runestone/tasks.json" })` | Read the task list of the workspace | `api.workspace.read(path)` |
|
||||
| Background Slideshow | `api.backgrounds.chooseFolder`, `list`, `read`, `defaultFolder`, `readImageSettings`, `writeImageSettings` | Read images and per-image settings from a folder outside the workspace | `api.files` with a folder grant |
|
||||
| Background Slideshow | `api.workspace.readOptional(".runestone/pm/workspace.json")` | Read the board names of Project Management | A service of Project Management through `api.services` |
|
||||
|
||||
The Git, Project Management, Local Autocomplete, PDF Viewer, and CSV Viewer plugins make no native calls.
|
||||
Their test scripts replace `window.__TAURI_INTERNALS__` with a test double. That is test code and does not go into the package.
|
||||
|
||||
## Terminal API
|
||||
|
||||
`api.pty` (`version: 1`) starts shells in pseudo terminals. The types are `PtyApi` and `PtySession` in `src/lib/plugins/sdk.ts`.
|
||||
|
||||
| Member | Contract |
|
||||
| --- | --- |
|
||||
| `profiles()` | Returns the installed shells as `{ id, title, kind }`. |
|
||||
| `open(options)` | Starts a shell and returns a session. See the options below. |
|
||||
| `openWindow()` | Opens a terminal window for the workspace of the current window. |
|
||||
| `dictation()` | Starts Windows voice typing. Focus the terminal first. Fails on other systems. |
|
||||
|
||||
| Option | Rule |
|
||||
| --- | --- |
|
||||
| `cwd` | Required. The workspace root of the window. The start fails when the workspace changed. |
|
||||
| `cols`, `rows` | Required. Positive integers. |
|
||||
| `profile` | A profile `id` from `profiles()`. Without it, the host uses the first installed shell. |
|
||||
| `directory` | A start folder other than the workspace root. |
|
||||
| `onData(data)` | Required. Receives the output as a `Uint8Array`. A UTF-8 character can be split between two calls. |
|
||||
| `onExit(code)` | Receives the exit code, or `null`. |
|
||||
|
||||
A session has `id`, `write(text)`, `resize(cols, rows)`, and `close()`. `close()` stops the shell, and more calls return the same promise.
|
||||
Output goes only to the session that started the shell, as raw bytes.
|
||||
When the plugin stops, the host stops the output, runs the plugin cleanup, and then closes the sessions that are still open.
|
||||
|
||||
## Folder grants
|
||||
|
||||
`api.files` (`version: 1`) gives access to folders outside the workspace. The user selects each folder. The plugin cannot supply a path.
|
||||
A grant is `{ id, path, name }`. `id` is opaque. `path` and `name` are for display only.
|
||||
|
||||
| Member | Contract |
|
||||
| --- | --- |
|
||||
| `chooseFolder({ title? })` | Opens the folder picker. Returns a grant, or `null` on cancel. The same folder gives the same grant again. |
|
||||
| `pictureFolder(name)` | Creates `RuneStone <name>` in the Pictures folder of the user if necessary, and returns a grant for it. `name` has letters, digits, spaces, hyphens, and underscores, at most 64 characters. |
|
||||
| `grants()` | Returns the grants of this plugin. |
|
||||
| `revoke(grant)` | Removes a grant. Returns `false` when the plugin has no such grant. |
|
||||
| `list(grant)` | Returns `{ name, size }` for the ordinary files directly in the folder. Skips folders and links. |
|
||||
| `readBytes(grant, name)` | Reads one file of at most 64 MiB as a `Uint8Array`. |
|
||||
| `readSidecar(grant, name)` | Reads a sidecar file as text, or returns `null` when it does not exist. |
|
||||
| `writeSidecar(grant, name, contents, expected)` | Saves a sidecar file only if it still contains `expected`. Use `null` when the file does not exist. |
|
||||
|
||||
Each plugin has its own grants. The host keeps them with the retained data of the plugin, so they stay after a restart, an update, or a removal.
|
||||
A file name is one name without folder parts. The host rejects `..`, links, and files that resolve outside the granted folder.
|
||||
When the granted folder is removed or becomes a link, its grant stops working. Ask the user to choose the folder again.
|
||||
|
||||
A sidecar is a small JSON file that the plugin keeps beside the files of the user. Its name has the form `.runestone-<name>.json`, where `<name>` has letters, digits, hyphens, and underscores.
|
||||
A sidecar holds valid JSON of at most 1 MiB. The host writes no other files in a granted folder.
|
||||
|
||||
Store the grant `id` in the plugin settings. Before you use a saved grant, look for it in `grants()`.
|
||||
|
||||
## Plugin services
|
||||
|
||||
`api.services` (`version: 1`) lets a plugin offer data to other plugins in the same window. The host passes the calls, so no plugin reads the private files of another plugin.
|
||||
|
||||
| Member | Contract |
|
||||
| --- | --- |
|
||||
| `provide(name, methods)` | Offers an object of functions under a name. Returns `{ notify(), dispose() }`. One plugin can offer each name once. |
|
||||
| `get(plugin, name)` | Returns the methods of a service of another plugin, or `null` when it is not available. |
|
||||
| `subscribe(listener)` | Calls `listener(plugin, name)` when a service starts, stops, or calls `notify()`. Returns a cleanup function. |
|
||||
|
||||
A service name uses lowercase letters, digits, dots, and hyphens, and starts with a letter.
|
||||
Each method call returns a promise. The host copies the arguments and the result with `structuredClone`. Use only data that this function can copy, not functions or DOM nodes.
|
||||
When the provider stops, the host removes its services and notifies the subscribers. Calls through an old service object then fail. Call `get` again after a notification.
|
||||
Make the data of a service a documented contract of the provider. Give its name, methods, and result shapes in the documentation of the provider plugin.
|
||||
|
||||
## Git API
|
||||
|
||||
`api.git` gives Git operations for the active workspace of the window. The host runs the `git` command, one operation at a time.
|
||||
@@ -378,14 +471,17 @@ For its native service and test setup, see the [Git plugin development guide](ht
|
||||
`api.backgrounds` (`version: 1`) lets a plugin show image frames behind the RuneStone interface.
|
||||
Frames stay in the current window and do not change the saved appearance settings.
|
||||
|
||||
The folder methods are deprecated. They accept a folder path from the plugin. Use [folder grants](#folder-grants) in new code.
|
||||
The host keeps them for released versions of Background Slideshow.
|
||||
|
||||
| Method | Optional | Contract |
|
||||
| --- | --- | --- |
|
||||
| `chooseFolder()` | | Open the folder picker. Returns an absolute path, or `null` on cancel. |
|
||||
| `defaultFolder()` | yes | Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. |
|
||||
| `list(folder)` | | Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. |
|
||||
| `read(folder, name)` | | Read one image as bytes, at most 50 MiB. |
|
||||
| `readImageSettings(folder)` | yes | Read the per-image settings file text, or `null`. |
|
||||
| `writeImageSettings(folder, contents, expected)` | yes | Save the per-image settings file. See [Per-image settings](#per-image-settings). |
|
||||
| `chooseFolder()` | | Deprecated. Use `files.chooseFolder()`. Open the folder picker. Returns an absolute path, or `null` on cancel. |
|
||||
| `defaultFolder()` | yes | Deprecated. Use `files.pictureFolder("Backgrounds")`. Create `RuneStone Backgrounds` in the Pictures folder of the user and return its path. |
|
||||
| `list(folder)` | | Deprecated. Use `files.list(grant)`. Return `{ name }` for PNG, JPEG, GIF, and WebP files directly in the folder. |
|
||||
| `read(folder, name)` | | Deprecated. Use `files.readBytes(grant, name)`. Read one image as bytes, at most 50 MiB. |
|
||||
| `readImageSettings(folder)` | yes | Deprecated. Use `files.readSidecar(grant, ".runestone-backgrounds.json")`. Read the per-image settings file text, or `null`. |
|
||||
| `writeImageSettings(folder, contents, expected)` | yes | Deprecated. Use `files.writeSidecar`. Save the per-image settings file. See [Per-image settings](#per-image-settings). |
|
||||
| `set(target, frame)` | | Show a frame for a target. `null` removes the frame of this plugin. |
|
||||
| `get(target)` | | Return the active frame for a target, or `null`. |
|
||||
| `subscribe(listener)` | | Receive the target name when a frame changes. Returns a cleanup function. |
|
||||
@@ -426,4 +522,5 @@ Example: [Project Management](https://git.knottywyvern.com/kwyvern/RuneStone_PM/
|
||||
The per-image settings file is `.runestone-backgrounds.json` in the image folder.
|
||||
It must be JSON with `"schema": 1` and an `images` object, at most 1 MiB.
|
||||
`writeImageSettings` compares the current file to `expected` (`null` when the file does not exist). It fails when the file changed, so external edits are not lost.
|
||||
`files.writeSidecar` does the same comparison on the same file, but the host checks only that the text is JSON. The plugin checks the schema.
|
||||
Example: the [Background Slideshow image settings](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/development.md#per-image-settings) give the storage format and the rendering behavior.
|
||||
|
||||
@@ -12,6 +12,14 @@ fn main() {
|
||||
"backgrounds_read",
|
||||
"backgrounds_read_image_settings",
|
||||
"backgrounds_write_image_settings",
|
||||
"folders_choose",
|
||||
"folders_picture",
|
||||
"folders_grants",
|
||||
"folders_revoke",
|
||||
"folders_list",
|
||||
"folders_read",
|
||||
"folders_read_sidecar",
|
||||
"folders_write_sidecar",
|
||||
"spelling_suggestions",
|
||||
"spelling_menu_install",
|
||||
"spelling_menu_select",
|
||||
|
||||
@@ -96,6 +96,14 @@
|
||||
"allow-backgrounds-list",
|
||||
"allow-backgrounds-read",
|
||||
"allow-backgrounds-read-image-settings",
|
||||
"allow-backgrounds-write-image-settings"
|
||||
"allow-backgrounds-write-image-settings",
|
||||
"allow-folders-choose",
|
||||
"allow-folders-picture",
|
||||
"allow-folders-grants",
|
||||
"allow-folders-revoke",
|
||||
"allow-folders-list",
|
||||
"allow-folders-read",
|
||||
"allow-folders-read-sidecar",
|
||||
"allow-folders-write-sidecar"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -41,6 +41,14 @@
|
||||
"allow-backgrounds-list",
|
||||
"allow-backgrounds-read",
|
||||
"allow-backgrounds-read-image-settings",
|
||||
"allow-backgrounds-write-image-settings"
|
||||
"allow-backgrounds-write-image-settings",
|
||||
"allow-folders-choose",
|
||||
"allow-folders-picture",
|
||||
"allow-folders-grants",
|
||||
"allow-folders-revoke",
|
||||
"allow-folders-list",
|
||||
"allow-folders-read",
|
||||
"allow-folders-read-sidecar",
|
||||
"allow-folders-write-sidecar"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-choose"
|
||||
description = "Enables the folders_choose command without any pre-configured scope."
|
||||
commands.allow = ["folders_choose"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-choose"
|
||||
description = "Denies the folders_choose command without any pre-configured scope."
|
||||
commands.deny = ["folders_choose"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-grants"
|
||||
description = "Enables the folders_grants command without any pre-configured scope."
|
||||
commands.allow = ["folders_grants"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-grants"
|
||||
description = "Denies the folders_grants command without any pre-configured scope."
|
||||
commands.deny = ["folders_grants"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-list"
|
||||
description = "Enables the folders_list command without any pre-configured scope."
|
||||
commands.allow = ["folders_list"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-list"
|
||||
description = "Denies the folders_list command without any pre-configured scope."
|
||||
commands.deny = ["folders_list"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-picture"
|
||||
description = "Enables the folders_picture command without any pre-configured scope."
|
||||
commands.allow = ["folders_picture"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-picture"
|
||||
description = "Denies the folders_picture command without any pre-configured scope."
|
||||
commands.deny = ["folders_picture"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-read"
|
||||
description = "Enables the folders_read command without any pre-configured scope."
|
||||
commands.allow = ["folders_read"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-read"
|
||||
description = "Denies the folders_read command without any pre-configured scope."
|
||||
commands.deny = ["folders_read"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-read-sidecar"
|
||||
description = "Enables the folders_read_sidecar command without any pre-configured scope."
|
||||
commands.allow = ["folders_read_sidecar"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-read-sidecar"
|
||||
description = "Denies the folders_read_sidecar command without any pre-configured scope."
|
||||
commands.deny = ["folders_read_sidecar"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-revoke"
|
||||
description = "Enables the folders_revoke command without any pre-configured scope."
|
||||
commands.allow = ["folders_revoke"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-revoke"
|
||||
description = "Denies the folders_revoke command without any pre-configured scope."
|
||||
commands.deny = ["folders_revoke"]
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-folders-write-sidecar"
|
||||
description = "Enables the folders_write_sidecar command without any pre-configured scope."
|
||||
commands.allow = ["folders_write_sidecar"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-folders-write-sidecar"
|
||||
description = "Denies the folders_write_sidecar command without any pre-configured scope."
|
||||
commands.deny = ["folders_write_sidecar"]
|
||||
@@ -0,0 +1,554 @@
|
||||
//! Folder grants for plugins.
|
||||
//!
|
||||
//! A plugin gets access to a folder outside the workspace only through a grant. The user makes a
|
||||
//! grant with the folder picker, or the host makes one for a `RuneStone <name>` folder in Pictures.
|
||||
//! Each plugin has its own grant list in its retained data (`plugin-data/<id>/folder-grants.json`).
|
||||
//! A grant gives access to the ordinary files directly in its folder. Names with folder parts,
|
||||
//! links, and files that resolve outside the folder are rejected. The plugin cannot supply a path.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::fsutil::{self, is_link};
|
||||
use crate::plugins::PluginState;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use tauri::{AppHandle, Manager, Window};
|
||||
use tauri_plugin_dialog::DialogExt;
|
||||
|
||||
const GRANTS_FILE: &str = "folder-grants.json";
|
||||
const GRANT_LIMIT: usize = 64;
|
||||
const READ_LIMIT: u64 = 64 * 1024 * 1024;
|
||||
const SIDECAR_LIMIT: u64 = 1024 * 1024;
|
||||
const LIST_LIMIT: usize = 10_000;
|
||||
|
||||
/// Serializes changes to grant files and sidecar files.
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
|
||||
struct StoredGrant {
|
||||
id: String,
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Serialize, Deserialize)]
|
||||
struct GrantFile {
|
||||
schema: u32,
|
||||
grants: Vec<StoredGrant>,
|
||||
}
|
||||
|
||||
/// What a plugin receives: an opaque ID and the folder path for display.
|
||||
#[derive(Clone, Debug, Serialize, PartialEq)]
|
||||
pub struct FolderGrant {
|
||||
id: String,
|
||||
path: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, PartialEq)]
|
||||
pub struct FolderEntry {
|
||||
name: String,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl From<&StoredGrant> for FolderGrant {
|
||||
fn from(grant: &StoredGrant) -> Self {
|
||||
Self {
|
||||
id: grant.id.clone(),
|
||||
path: grant.path.to_string_lossy().into_owned(),
|
||||
name: grant
|
||||
.path
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| grant.path.to_string_lossy().into_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The grant lists of all plugins, in the folder that holds the retained plugin data.
|
||||
struct Grants {
|
||||
data: PathBuf,
|
||||
}
|
||||
|
||||
impl Grants {
|
||||
fn plugin_folder(&self, plugin: &str, create: bool) -> Result<PathBuf> {
|
||||
if plugin.is_empty()
|
||||
|| plugin.len() > 128
|
||||
|| !plugin.bytes().all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'.' || byte == b'-')
|
||||
|| !fsutil::is_plain_component(plugin)
|
||||
{
|
||||
return Err("Invalid plugin ID.".into());
|
||||
}
|
||||
let folder = self.data.join(plugin);
|
||||
match fs::symlink_metadata(&folder) {
|
||||
Ok(metadata) if metadata.is_dir() && !is_link(&metadata) => Ok(folder),
|
||||
Ok(_) => Err("The plugin data folder must be an ordinary folder.".into()),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound && create => {
|
||||
fs::create_dir(&folder)?;
|
||||
Ok(folder)
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(folder),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn load(&self, plugin: &str) -> Result<Vec<StoredGrant>> {
|
||||
let path = self.plugin_folder(plugin, false)?.join(GRANTS_FILE);
|
||||
let metadata = match fs::symlink_metadata(&path) {
|
||||
Ok(metadata) => metadata,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
if !metadata.is_file() || is_link(&metadata) {
|
||||
return Err("The folder grant list must be an ordinary file.".into());
|
||||
}
|
||||
let Some(bytes) = fsutil::read_to_limit(fsutil::open_entry(&path)?, SIDECAR_LIMIT)? else {
|
||||
return Err("The folder grant list exceeds 1 MiB.".into());
|
||||
};
|
||||
let file: GrantFile = serde_json::from_slice(&bytes)?;
|
||||
if file.schema != 1 {
|
||||
return Err("Unknown folder grant list schema.".into());
|
||||
}
|
||||
Ok(file.grants)
|
||||
}
|
||||
|
||||
fn save(&self, plugin: &str, grants: Vec<StoredGrant>) -> Result<()> {
|
||||
let folder = self.plugin_folder(plugin, true)?;
|
||||
let bytes = serde_json::to_vec_pretty(&GrantFile { schema: 1, grants })?;
|
||||
let temp = folder.join(format!("{GRANTS_FILE}.{}.tmp", uuid::Uuid::new_v4()));
|
||||
Ok(fsutil::replace_file(&folder.join(GRANTS_FILE), &temp, &bytes)?)
|
||||
}
|
||||
|
||||
/// Grant `folder` to `plugin`. Return the existing grant when the plugin already has the folder.
|
||||
fn add(&self, plugin: &str, folder: &Path) -> Result<FolderGrant> {
|
||||
let path = granted_root(folder)?;
|
||||
let _lock = LOCK.lock()?;
|
||||
let mut grants = self.load(plugin)?;
|
||||
if let Some(existing) = grants.iter().find(|grant| grant.path == path) {
|
||||
return Ok(existing.into());
|
||||
}
|
||||
if grants.len() >= GRANT_LIMIT {
|
||||
return Err(format!("A plugin can keep at most {GRANT_LIMIT} folder grants. Remove a grant first.").into());
|
||||
}
|
||||
let grant = StoredGrant { id: uuid::Uuid::new_v4().to_string(), path };
|
||||
let result = FolderGrant::from(&grant);
|
||||
grants.push(grant);
|
||||
self.save(plugin, grants)?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn list(&self, plugin: &str) -> Result<Vec<FolderGrant>> {
|
||||
Ok(self.load(plugin)?.iter().map(FolderGrant::from).collect())
|
||||
}
|
||||
|
||||
fn revoke(&self, plugin: &str, id: &str) -> Result<bool> {
|
||||
let _lock = LOCK.lock()?;
|
||||
let mut grants = self.load(plugin)?;
|
||||
let count = grants.len();
|
||||
grants.retain(|grant| grant.id != id);
|
||||
if grants.len() == count {
|
||||
return Ok(false);
|
||||
}
|
||||
self.save(plugin, grants)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Return the folder of a grant of this plugin. The folder must still be an ordinary folder
|
||||
/// at the same resolved path, so a folder that became a link does not redirect access.
|
||||
fn resolve(&self, plugin: &str, id: &str) -> Result<PathBuf> {
|
||||
uuid::Uuid::parse_str(id).map_err(|_| Error::new("Invalid folder grant."))?;
|
||||
let grant = self
|
||||
.load(plugin)?
|
||||
.into_iter()
|
||||
.find(|grant| grant.id == id)
|
||||
.ok_or_else(|| Error::new("This plugin has no grant for the folder. Choose the folder again."))?;
|
||||
let metadata = fs::symlink_metadata(&grant.path)
|
||||
.map_err(|_| Error::new("The granted folder is missing. Choose the folder again."))?;
|
||||
if !metadata.is_dir() || is_link(&metadata) || dunce::canonicalize(&grant.path)? != grant.path {
|
||||
return Err("The granted folder changed into a link or a file. Choose the folder again.".into());
|
||||
}
|
||||
Ok(grant.path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a chosen folder. Reject relative paths, parent segments, files, and whole drives.
|
||||
fn granted_root(folder: &Path) -> Result<PathBuf> {
|
||||
if !folder.is_absolute() || folder.components().any(|part| matches!(part, Component::ParentDir)) {
|
||||
return Err("Supply an absolute folder path without parent segments.".into());
|
||||
}
|
||||
let root = dunce::canonicalize(folder)?;
|
||||
if !root.is_dir() {
|
||||
return Err("The folder does not exist.".into());
|
||||
}
|
||||
if root.parent().is_none() {
|
||||
return Err("Choose a folder, not a whole drive.".into());
|
||||
}
|
||||
Ok(root)
|
||||
}
|
||||
|
||||
/// The path of one ordinary file directly in `root`.
|
||||
fn file_path(root: &Path, name: &str) -> Result<PathBuf> {
|
||||
if !fsutil::is_plain_component(name)
|
||||
|| name.contains(['/', '\\', ':'])
|
||||
|| name.ends_with(' ')
|
||||
|| Path::new(name).components().count() != 1
|
||||
|| !matches!(Path::new(name).components().next(), Some(Component::Normal(_)))
|
||||
{
|
||||
return Err("Supply one file name without folder parts.".into());
|
||||
}
|
||||
Ok(root.join(name))
|
||||
}
|
||||
|
||||
/// Open one ordinary file. Reject links, also a link that replaces the file after the check.
|
||||
fn open_plain(root: &Path, path: &Path) -> Result<(fs::File, u64)> {
|
||||
let metadata = fs::symlink_metadata(path)?;
|
||||
if !metadata.is_file() || is_link(&metadata) {
|
||||
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
|
||||
}
|
||||
let file = fsutil::open_entry(path)?;
|
||||
let opened = file.metadata()?;
|
||||
if !opened.is_file() || is_link(&opened) || dunce::canonicalize(path)?.parent() != Some(root) {
|
||||
return Err("Granted folder access is limited to ordinary files, not links or folders.".into());
|
||||
}
|
||||
Ok((file, opened.len()))
|
||||
}
|
||||
|
||||
fn list_files(root: &Path) -> Result<Vec<FolderEntry>> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in fs::read_dir(root)? {
|
||||
let entry = entry?;
|
||||
let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue };
|
||||
let Ok(metadata) = entry.metadata() else { continue };
|
||||
// `DirEntry::metadata` does not follow links.
|
||||
if !metadata.is_file() || is_link(&metadata) || file_path(root, &name).is_err() {
|
||||
continue;
|
||||
}
|
||||
entries.push(FolderEntry { name, size: metadata.len() });
|
||||
if entries.len() > LIST_LIMIT {
|
||||
return Err(format!("The folder has more than {LIST_LIMIT} files.").into());
|
||||
}
|
||||
}
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn read_file(root: &Path, name: &str) -> Result<Vec<u8>> {
|
||||
let path = file_path(root, name)?;
|
||||
let (file, size) = open_plain(root, &path)?;
|
||||
if size > READ_LIMIT {
|
||||
return Err("The file exceeds 64 MiB.".into());
|
||||
}
|
||||
fsutil::read_to_limit(file, READ_LIMIT)?.ok_or_else(|| Error::new("The file exceeds 64 MiB."))
|
||||
}
|
||||
|
||||
/// A sidecar is a small JSON file that a plugin keeps beside the user's files, such as
|
||||
/// `.runestone-backgrounds.json`. Its name starts with `.runestone-` and ends with `.json`.
|
||||
fn sidecar_path(root: &Path, name: &str) -> Result<PathBuf> {
|
||||
let stem = name.strip_prefix(".runestone-").and_then(|rest| rest.strip_suffix(".json"));
|
||||
if !stem.is_some_and(|stem| !stem.is_empty() && stem.len() <= 64 && stem.bytes().all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')) {
|
||||
return Err("A sidecar file name has the form .runestone-<name>.json.".into());
|
||||
}
|
||||
file_path(root, name)
|
||||
}
|
||||
|
||||
fn read_sidecar(root: &Path, name: &str) -> Result<Option<String>> {
|
||||
let path = sidecar_path(root, name)?;
|
||||
match fs::symlink_metadata(&path) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error.into()),
|
||||
Ok(_) => {}
|
||||
}
|
||||
let (file, size) = open_plain(root, &path)?;
|
||||
if size > SIDECAR_LIMIT {
|
||||
return Err("The sidecar file exceeds 1 MiB.".into());
|
||||
}
|
||||
let bytes = fsutil::read_to_limit(file, SIDECAR_LIMIT)?.ok_or_else(|| Error::new("The sidecar file exceeds 1 MiB."))?;
|
||||
String::from_utf8(bytes).map(Some).map_err(Error::from)
|
||||
}
|
||||
|
||||
/// Save a sidecar only if it still holds `expected` (`None` when the file does not exist).
|
||||
fn write_sidecar(root: &Path, name: &str, contents: &str, expected: Option<&str>) -> Result<()> {
|
||||
let path = sidecar_path(root, name)?;
|
||||
if contents.len() as u64 > SIDECAR_LIMIT {
|
||||
return Err("The sidecar file exceeds 1 MiB.".into());
|
||||
}
|
||||
serde_json::from_str::<serde_json::Value>(contents)?;
|
||||
let _lock = LOCK.lock()?;
|
||||
if read_sidecar(root, name)?.as_deref() != expected {
|
||||
return Err("The sidecar file changed. Read it again before you save.".into());
|
||||
}
|
||||
if expected.is_some() {
|
||||
fsutil::write_text(&path, contents, expected)
|
||||
} else {
|
||||
let temp = root.join(format!(".runestone-sidecar-{}.tmp", uuid::Uuid::new_v4()));
|
||||
Ok(fsutil::create_file(&path, &temp, contents.as_bytes())?)
|
||||
}
|
||||
}
|
||||
|
||||
fn grants(app: &AppHandle) -> Result<Grants> {
|
||||
Ok(Grants { data: app.path().app_data_dir()?.join("plugin-data") })
|
||||
}
|
||||
|
||||
/// Accept only a plugin that is enabled and loaded in the calling window.
|
||||
/// Check the lease on a blocking worker, because the plugin lock can wait for package work.
|
||||
async fn check(app: &AppHandle, window: &Window, plugin: &str) -> Result<()> {
|
||||
let (app, label, plugin) = (app.clone(), window.label().to_owned(), plugin.to_owned());
|
||||
tauri::async_runtime::spawn_blocking(move || app.state::<PluginState>().require_lease(&app, &label, &plugin)).await?
|
||||
}
|
||||
|
||||
/// Check the lease, run `work` on a blocking worker, and check the lease again,
|
||||
/// so that a plugin that stopped during the work receives no result.
|
||||
async fn run<T: Send + 'static>(
|
||||
app: &AppHandle,
|
||||
window: &Window,
|
||||
plugin: &str,
|
||||
work: impl FnOnce(Grants) -> Result<T> + Send + 'static,
|
||||
) -> Result<T> {
|
||||
check(app, window, plugin).await?;
|
||||
let store = grants(app)?;
|
||||
let result = tauri::async_runtime::spawn_blocking(move || work(store)).await??;
|
||||
check(app, window, plugin).await?;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_choose(app: AppHandle, window: Window, plugin: String, title: Option<String>) -> Result<Option<FolderGrant>> {
|
||||
check(&app, &window, &plugin).await?;
|
||||
let (picker_app, picker_window) = (app.clone(), window.clone());
|
||||
let title = title.filter(|title| !title.trim().is_empty() && title.len() <= 200).unwrap_or_else(|| "Choose a folder".into());
|
||||
let selected = tauri::async_runtime::spawn_blocking(move || {
|
||||
picker_app.dialog().file().set_parent(&picker_window).set_title(title).blocking_pick_folder()
|
||||
})
|
||||
.await?;
|
||||
let Some(selected) = selected else { return Ok(None) };
|
||||
let folder = selected.into_path().map_err(Error::from_display)?;
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| store.add(&id, &folder)).await.map(Some)
|
||||
}
|
||||
|
||||
/// Grant `RuneStone <name>` in the Pictures folder of the user. Create the folder if necessary.
|
||||
#[tauri::command]
|
||||
pub async fn folders_picture(app: AppHandle, window: Window, plugin: String, name: String) -> Result<FolderGrant> {
|
||||
if name.is_empty() || name.len() > 64 || name.starts_with([' ', '-', '_']) || !name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, ' ' | '-' | '_')) || name.ends_with(' ') {
|
||||
return Err("Supply a folder name with letters, digits, spaces, hyphens, or underscores.".into());
|
||||
}
|
||||
let folder = app.path().picture_dir()?.join(format!("RuneStone {name}"));
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| {
|
||||
fs::create_dir_all(&folder)?;
|
||||
let metadata = fs::symlink_metadata(&folder)?;
|
||||
if !metadata.is_dir() || is_link(&metadata) {
|
||||
return Err("The Pictures folder entry must be an ordinary folder.".into());
|
||||
}
|
||||
store.add(&id, &folder)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_grants(app: AppHandle, window: Window, plugin: String) -> Result<Vec<FolderGrant>> {
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| store.list(&id)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_revoke(app: AppHandle, window: Window, plugin: String, grant: String) -> Result<bool> {
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| store.revoke(&id, &grant)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_list(app: AppHandle, window: Window, plugin: String, grant: String) -> Result<Vec<FolderEntry>> {
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| list_files(&store.resolve(&id, &grant)?)).await
|
||||
}
|
||||
|
||||
/// Return the bytes as an `ArrayBuffer`, not as JSON or base64 text.
|
||||
#[tauri::command]
|
||||
pub async fn folders_read(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result<tauri::ipc::Response> {
|
||||
let id = plugin.clone();
|
||||
let bytes = run(&app, &window, &plugin, move |store| read_file(&store.resolve(&id, &grant)?, &name)).await?;
|
||||
Ok(tauri::ipc::Response::new(bytes))
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_read_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String) -> Result<Option<String>> {
|
||||
let id = plugin.clone();
|
||||
run(&app, &window, &plugin, move |store| read_sidecar(&store.resolve(&id, &grant)?, &name)).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn folders_write_sidecar(app: AppHandle, window: Window, plugin: String, grant: String, name: String, contents: String, expected: Option<String>) -> Result<()> {
|
||||
check(&app, &window, &plugin).await?;
|
||||
let store = grants(&app)?;
|
||||
// Check the lease again immediately before the write, on the blocking worker.
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
app.state::<PluginState>().require_lease(&app, window.label(), &plugin)?;
|
||||
write_sidecar(&store.resolve(&plugin, &grant)?, &name, &contents, expected.as_deref())
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let root = std::env::temp_dir().join(format!("runestone-folders-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&root).unwrap();
|
||||
Self(dunce::canonicalize(root).unwrap())
|
||||
}
|
||||
fn folder(&self, name: &str) -> PathBuf {
|
||||
let path = self.0.join(name);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
path
|
||||
}
|
||||
fn store(&self) -> Grants {
|
||||
Grants { data: self.folder("plugin-data") }
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Make a link, or return `false` when Windows does not allow links for this user.
|
||||
fn link(original: &Path, link: &Path, folder: bool) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let _ = folder;
|
||||
std::os::unix::fs::symlink(original, link).unwrap();
|
||||
true
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let result = if folder {
|
||||
std::os::windows::fs::symlink_dir(original, link)
|
||||
} else {
|
||||
std::os::windows::fs::symlink_file(original, link)
|
||||
};
|
||||
match result {
|
||||
Ok(()) => true,
|
||||
Err(error) if error.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PRIVILEGE_NOT_HELD as i32) => {
|
||||
eprintln!("The link check requires Windows Developer Mode or the symbolic-link privilege.");
|
||||
false
|
||||
}
|
||||
Err(error) => panic!("{error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grants_persist_per_plugin_and_can_be_revoked() {
|
||||
let fixture = Fixture::new();
|
||||
let images = fixture.folder("images");
|
||||
fs::write(images.join("a.png"), b"png").unwrap();
|
||||
let store = fixture.store();
|
||||
let grant = store.add("org.test.one", &images).unwrap();
|
||||
assert_eq!(grant.path, images.to_string_lossy());
|
||||
assert_eq!(grant.name, "images");
|
||||
// The same folder gives the same grant.
|
||||
assert_eq!(store.add("org.test.one", &images).unwrap().id, grant.id);
|
||||
// A new store reads the saved grants, as after a restart.
|
||||
let reopened = fixture.store();
|
||||
assert_eq!(reopened.list("org.test.one").unwrap(), vec![grant.clone()]);
|
||||
assert_eq!(read_file(&reopened.resolve("org.test.one", &grant.id).unwrap(), "a.png").unwrap(), b"png");
|
||||
// Another plugin cannot use the grant ID of the first plugin.
|
||||
assert!(reopened.resolve("org.test.two", &grant.id).is_err());
|
||||
assert!(reopened.list("org.test.two").unwrap().is_empty());
|
||||
assert!(!reopened.revoke("org.test.two", &grant.id).unwrap());
|
||||
assert!(reopened.resolve("org.test.one", &grant.id).is_ok());
|
||||
assert!(reopened.revoke("org.test.one", &grant.id).unwrap());
|
||||
assert!(reopened.resolve("org.test.one", &grant.id).is_err());
|
||||
assert!(reopened.list("org.test.one").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grants_reject_invalid_plugins_ids_and_folders() {
|
||||
let fixture = Fixture::new();
|
||||
let store = fixture.store();
|
||||
let folder = fixture.folder("images");
|
||||
for plugin in ["", "..", "../escape", "Upper", "a/b", "a\\b", "con"] {
|
||||
assert!(store.add(plugin, &folder).is_err(), "{plugin}");
|
||||
}
|
||||
assert!(store.add("org.test.one", Path::new("relative")).is_err());
|
||||
assert!(store.add("org.test.one", &folder.join("..").join("images")).is_err());
|
||||
assert!(store.add("org.test.one", &fixture.0.join("missing")).is_err());
|
||||
fs::write(fixture.0.join("file.txt"), "x").unwrap();
|
||||
assert!(store.add("org.test.one", &fixture.0.join("file.txt")).is_err());
|
||||
let drive = folder.ancestors().last().unwrap().to_path_buf();
|
||||
assert!(store.add("org.test.one", &drive).is_err());
|
||||
assert!(store.resolve("org.test.one", "not-a-uuid").is_err());
|
||||
assert!(store.resolve("org.test.one", &uuid::Uuid::new_v4().to_string()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_cannot_leave_the_granted_folder() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.folder("images");
|
||||
fs::write(fixture.0.join("secret.txt"), "secret").unwrap();
|
||||
fixture.folder("images/nested");
|
||||
fs::write(root.join("nested/inner.png"), "inner").unwrap();
|
||||
for name in ["../secret.txt", "..", ".", "nested/inner.png", "nested\\inner.png", "C:\\secret.txt", "/secret.txt", "a.png:stream", "", "nul", "trailing."] {
|
||||
assert!(read_file(&root, name).is_err(), "{name}");
|
||||
}
|
||||
assert!(read_file(&root, "nested").is_err(), "a folder is not a file");
|
||||
fs::write(root.join("b.txt"), "b").unwrap();
|
||||
fs::write(root.join("a.png"), "a").unwrap();
|
||||
assert_eq!(list_files(&root).unwrap(), vec![FolderEntry { name: "a.png".into(), size: 1 }, FolderEntry { name: "b.txt".into(), size: 1 }]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn links_are_rejected() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.folder("images");
|
||||
let outside = fixture.folder("outside");
|
||||
fs::write(outside.join("secret.png"), "secret").unwrap();
|
||||
if !link(&outside.join("secret.png"), &root.join("link.png"), false) {
|
||||
return;
|
||||
}
|
||||
assert!(list_files(&root).unwrap().is_empty(), "the listing skips links");
|
||||
assert!(read_file(&root, "link.png").is_err());
|
||||
// A granted folder that is replaced by a link loses its access.
|
||||
let store = fixture.store();
|
||||
let moved = fixture.folder("moved");
|
||||
let grant = store.add("org.test.one", &moved).unwrap();
|
||||
fs::remove_dir(&moved).unwrap();
|
||||
assert!(link(&outside, &moved, true));
|
||||
assert!(store.resolve("org.test.one", &grant.id).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_have_a_size_limit() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.folder("images");
|
||||
fs::File::create(root.join("large.bin")).unwrap().set_len(READ_LIMIT + 1).unwrap();
|
||||
assert!(read_file(&root, "large.bin").unwrap_err().to_string().contains("64 MiB"));
|
||||
fs::File::create(root.join(".runestone-large.json")).unwrap().set_len(SIDECAR_LIMIT + 1).unwrap();
|
||||
assert!(read_sidecar(&root, ".runestone-large.json").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidecars_keep_external_changes_and_accept_only_sidecar_names() {
|
||||
let fixture = Fixture::new();
|
||||
let root = fixture.folder("images");
|
||||
let name = ".runestone-backgrounds.json";
|
||||
let first = r#"{"schema":1,"images":{}}"#;
|
||||
let next = r#"{"schema":1,"images":{"a.png":{}}}"#;
|
||||
assert_eq!(read_sidecar(&root, name).unwrap(), None);
|
||||
write_sidecar(&root, name, first, None).unwrap();
|
||||
assert!(write_sidecar(&root, name, next, None).is_err());
|
||||
assert!(write_sidecar(&root, name, next, Some("stale")).is_err());
|
||||
write_sidecar(&root, name, next, Some(first)).unwrap();
|
||||
assert_eq!(read_sidecar(&root, name).unwrap().as_deref(), Some(next));
|
||||
assert!(write_sidecar(&root, name, "not json", Some(next)).is_err());
|
||||
assert!(write_sidecar(&root, name, &format!("\"{}\"", "x".repeat(SIDECAR_LIMIT as usize)), Some(next)).is_err());
|
||||
for bad in ["a.png", "settings.json", ".runestone-.json", ".runestone-a/b.json", ".runestone-a.json.png", "../.runestone-a.json"] {
|
||||
assert!(write_sidecar(&root, bad, "{}", None).is_err(), "{bad}");
|
||||
assert!(read_sidecar(&root, bad).is_err(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ mod tab_transfer;
|
||||
mod spelling;
|
||||
mod theme;
|
||||
mod backgrounds;
|
||||
mod folders;
|
||||
|
||||
use pty::PtyState;
|
||||
use tauri::Manager;
|
||||
@@ -39,6 +40,14 @@ pub fn run() {
|
||||
backgrounds::backgrounds_read,
|
||||
backgrounds::backgrounds_read_image_settings,
|
||||
backgrounds::backgrounds_write_image_settings,
|
||||
folders::folders_choose,
|
||||
folders::folders_picture,
|
||||
folders::folders_grants,
|
||||
folders::folders_revoke,
|
||||
folders::folders_list,
|
||||
folders::folders_read,
|
||||
folders::folders_read_sidecar,
|
||||
folders::folders_write_sidecar,
|
||||
theme::theme_export,
|
||||
spelling::spelling_menu_install,
|
||||
spelling::spelling_suggestions,
|
||||
|
||||
+109
-37
@@ -6,6 +6,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use portable_pty::{native_pty_system, CommandBuilder, MasterPty, PtySize};
|
||||
use serde::Serialize;
|
||||
use tauri::ipc::{Channel, InvokeResponseBody, JavaScriptChannelId};
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
@@ -72,6 +73,63 @@ pub struct PtyExit {
|
||||
pub code: Option<u32>,
|
||||
}
|
||||
|
||||
/// The destination of the output and the exit status of one terminal session.
|
||||
trait PtyOutput: Send {
|
||||
fn data(&self, bytes: &[u8]);
|
||||
fn exit(&self, code: Option<u32>);
|
||||
}
|
||||
|
||||
/// Window events for the released Terminal plugin, which listens for `pty-data` and `pty-exit`.
|
||||
/// The events go to the window that opened the session. A global `listen` in that window
|
||||
/// receives them. Tauri 2 also delivers an addressed event to a global `listen` in other windows.
|
||||
struct EventOutput {
|
||||
app: AppHandle,
|
||||
owner: String,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl PtyOutput for EventOutput {
|
||||
fn data(&self, bytes: &[u8]) {
|
||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-data", PtyData { id: self.id.clone(), data: bytes.to_vec() });
|
||||
}
|
||||
fn exit(&self, code: Option<u32>) {
|
||||
let _ = self.app.emit_to(self.owner.as_str(), "pty-exit", PtyExit { id: self.id.clone(), code });
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel to the webview that opened the session. Output goes as raw bytes (an
|
||||
/// `ArrayBuffer` in JavaScript). The exit status goes as `{ "exit": code }`.
|
||||
struct ChannelOutput(Channel<InvokeResponseBody>);
|
||||
|
||||
impl PtyOutput for ChannelOutput {
|
||||
fn data(&self, bytes: &[u8]) {
|
||||
let _ = self.0.send(InvokeResponseBody::Raw(bytes.to_vec()));
|
||||
}
|
||||
fn exit(&self, code: Option<u32>) {
|
||||
let _ = self.0.send(InvokeResponseBody::Json(serde_json::json!({ "exit": code }).to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Use the channel when the caller supplies one. Without a channel, use window events.
|
||||
fn output(channel: Option<Channel<InvokeResponseBody>>, events: impl FnOnce() -> Box<dyn PtyOutput>) -> Box<dyn PtyOutput> {
|
||||
match channel {
|
||||
Some(channel) => Box::new(ChannelOutput(channel)),
|
||||
None => events(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Send the output until the reader reaches EOF. Then send the exit status.
|
||||
fn pump(mut reader: impl Read, exit: std::sync::mpsc::Receiver<Option<u32>>, output: &dyn PtyOutput) {
|
||||
let mut buf = [0u8; 4096];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => output.data(&buf[..n]),
|
||||
}
|
||||
}
|
||||
output.exit(exit.recv().ok().flatten());
|
||||
}
|
||||
|
||||
type ShellProcess = (
|
||||
OpenPty,
|
||||
Box<dyn Read + Send>,
|
||||
@@ -223,6 +281,7 @@ fn spawn_shell(root: &Path, cols: u16, rows: u16, profile: Option<&str>, owner:
|
||||
pub async fn pty_open(
|
||||
app: AppHandle,
|
||||
window: tauri::Window,
|
||||
webview: tauri::Webview,
|
||||
workspace: State<'_, WorkspaceState>,
|
||||
id: String,
|
||||
cols: u16,
|
||||
@@ -230,13 +289,16 @@ pub async fn pty_open(
|
||||
cwd: String,
|
||||
profile: Option<String>,
|
||||
directory: Option<String>,
|
||||
channel: Option<JavaScriptChannelId>,
|
||||
) -> Result<()> {
|
||||
let root = current_root(&workspace, window.label())?;
|
||||
if root.to_string_lossy() != cwd {
|
||||
return Err(Error::new("workspace changed before the terminal started"));
|
||||
}
|
||||
let owner = window.label().to_owned();
|
||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory)).await?
|
||||
// A session with a channel sends no `pty-data` or `pty-exit` events.
|
||||
let channel = channel.map(|channel| channel.channel_on(webview));
|
||||
tauri::async_runtime::spawn_blocking(move || open(app, owner, root, id, cols, rows, profile, directory, channel)).await?
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -249,6 +311,7 @@ fn open(
|
||||
rows: u16,
|
||||
profile: Option<String>,
|
||||
directory: Option<String>,
|
||||
channel: Option<Channel<InvokeResponseBody>>,
|
||||
) -> Result<()> {
|
||||
let pty = app.state::<PtyState>();
|
||||
let mut guard = pty.inner.lock().map_err(|_| Error::new("pty lock"))?;
|
||||
@@ -257,7 +320,7 @@ fn open(
|
||||
}
|
||||
let directory = directory.map(PathBuf::from).unwrap_or(root);
|
||||
if !directory.is_dir() { return Err(Error::new("Terminal working directory does not exist")); }
|
||||
let (session, mut reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
||||
let (session, reader, mut child) = spawn_shell(&directory, cols, rows, profile.as_deref(), &owner)?;
|
||||
guard.insert(id.clone(), session);
|
||||
drop(guard);
|
||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||
@@ -275,41 +338,8 @@ fn open(
|
||||
drop(session);
|
||||
let _ = exit_tx.send(code);
|
||||
});
|
||||
let app_reader = app.clone();
|
||||
let reader_id = id.clone();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 4096];
|
||||
// Address the terminal events to the window that opened the session.
|
||||
// A global `listen` in that window receives them. Tauri 2 also delivers an addressed
|
||||
// event to a global `listen` in other windows. A listener with a window target does not
|
||||
// receive the events of other windows.
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
let data = buf[..n].to_vec();
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-data",
|
||||
PtyData {
|
||||
id: reader_id.clone(),
|
||||
data,
|
||||
},
|
||||
);
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
let code = exit_rx.recv().ok().flatten();
|
||||
let _ = app_reader.emit_to(
|
||||
owner.as_str(),
|
||||
"pty-exit",
|
||||
PtyExit {
|
||||
id: reader_id,
|
||||
code,
|
||||
},
|
||||
);
|
||||
});
|
||||
let output = output(channel, || Box::new(EventOutput { app: app.clone(), owner, id }));
|
||||
thread::spawn(move || pump(reader, exit_rx, output.as_ref()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -403,8 +433,50 @@ pub fn pty_dictation() -> Result<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Records the window events that a session would send.
|
||||
struct FakeEvents(Arc<Mutex<Vec<String>>>);
|
||||
impl PtyOutput for FakeEvents {
|
||||
fn data(&self, bytes: &[u8]) { self.0.lock().unwrap().push(format!("pty-data {}", String::from_utf8_lossy(bytes))); }
|
||||
fn exit(&self, code: Option<u32>) { self.0.lock().unwrap().push(format!("pty-exit {code:?}")); }
|
||||
}
|
||||
|
||||
fn run_pump(channel: Option<Channel<InvokeResponseBody>>, events: Arc<Mutex<Vec<String>>>) {
|
||||
let (exit_tx, exit_rx) = std::sync::mpsc::channel();
|
||||
exit_tx.send(Some(3)).unwrap();
|
||||
let output = output(channel, move || Box::new(FakeEvents(events)));
|
||||
pump(std::io::Cursor::new(b"hello \xce\xbb".to_vec()), exit_rx, output.as_ref());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_channel_session_sends_raw_bytes_and_no_window_events() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let received = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = received.clone();
|
||||
let channel = Channel::new(move |body| { sink.lock().unwrap().push(body); Ok(()) });
|
||||
run_pump(Some(channel), events.clone());
|
||||
assert!(events.lock().unwrap().is_empty(), "a channel session must not send pty-data or pty-exit events");
|
||||
let received = received.lock().unwrap();
|
||||
assert_eq!(received.len(), 2);
|
||||
match &received[0] {
|
||||
InvokeResponseBody::Raw(bytes) => assert_eq!(bytes, b"hello \xce\xbb"),
|
||||
InvokeResponseBody::Json(json) => panic!("output must be raw bytes, not JSON: {json}"),
|
||||
}
|
||||
match &received[1] {
|
||||
InvokeResponseBody::Json(json) => assert_eq!(serde_json::from_str::<serde_json::Value>(json).unwrap(), serde_json::json!({ "exit": 3 })),
|
||||
InvokeResponseBody::Raw(_) => panic!("the exit status must be JSON"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_without_a_channel_keeps_the_window_events() {
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
run_pump(None, events.clone());
|
||||
assert_eq!(*events.lock().unwrap(), vec!["pty-data hello λ".to_owned(), "pty-exit Some(3)".to_owned()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installed_profiles_start_and_report_shell_prompts() {
|
||||
let root = dunce::canonicalize(std::env::current_dir().unwrap()).unwrap();
|
||||
|
||||
@@ -3,8 +3,16 @@ import { completionHub } from "../completion/hub.ts";
|
||||
import { registerCompletionInput } from "../completion/input.ts";
|
||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||
import { backgroundHub } from "./backgrounds.ts";
|
||||
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
||||
import type { BackgroundFiles } from "./backgroundContracts.ts";
|
||||
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
|
||||
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
|
||||
|
||||
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
||||
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
||||
openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles;
|
||||
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
||||
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
|
||||
};
|
||||
|
||||
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
@@ -27,8 +35,11 @@ export class ExternalSession {
|
||||
private registry: ContributionRegistry;
|
||||
private backgroundOwner = Symbol('plugin backgrounds');
|
||||
private backgroundSubscriptions = new Set<() => void>();
|
||||
private serviceOwner = Symbol('plugin services');
|
||||
private serviceSubscriptions = new Set<() => void>();
|
||||
private ptySessions = new Map<string, () => Promise<void>>();
|
||||
readonly id: string;
|
||||
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
|
||||
private services: SessionServices;
|
||||
private changed: () => void;
|
||||
private show: PluginApi["openView"];
|
||||
private close?: PluginApi["closeView"];
|
||||
@@ -37,7 +48,7 @@ export class ExternalSession {
|
||||
private receiveTab?: (data: string) => void | Promise<void>;
|
||||
private openDocument: (path: string) => Promise<void>;
|
||||
private renameDocument?: PluginApi["renameDocument"];
|
||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
|
||||
constructor(id: string, services: SessionServices, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
|
||||
this.openDocument = openDocument;
|
||||
this.renameDocument = renameDocument;
|
||||
this.close = close;
|
||||
@@ -54,6 +65,9 @@ export class ExternalSession {
|
||||
};
|
||||
const api: PluginApi = {
|
||||
id: this.id, signal: this.controller.signal,
|
||||
...(this.services.pty ? { pty: this.ptyApi(this.services.pty) } : {}),
|
||||
...(this.services.files ? { files: this.filesApi(this.services.files) } : {}),
|
||||
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
||||
...(this.services.backgrounds ? { backgrounds: {
|
||||
version: 1 as const,
|
||||
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
|
||||
@@ -180,6 +194,85 @@ export class ExternalSession {
|
||||
this.check();
|
||||
return request().then(value => { this.check(); return value; });
|
||||
}
|
||||
private ptyApi(pty: PtyTransport): PtyApi {
|
||||
const size = (cols: unknown, rows: unknown) => {
|
||||
if (![cols, rows].every(value => Number.isInteger(value) && (value as number) > 0 && (value as number) <= 10_000)) throw new Error("Terminal columns and rows must be positive integers.");
|
||||
};
|
||||
const validate = (options: PtyOpenOptions) => {
|
||||
this.check();
|
||||
if (!options || typeof options.onData !== "function" || (options.onExit !== undefined && typeof options.onExit !== "function")) throw new Error("A terminal session needs an onData function.");
|
||||
if (typeof options.cwd !== "string") throw new Error("Supply the workspace folder as cwd.");
|
||||
size(options.cols, options.rows);
|
||||
};
|
||||
const open = async (options: PtyOpenOptions): Promise<PtySession> => {
|
||||
const id = crypto.randomUUID();
|
||||
let closed = false, exited = false, closing: Promise<void> | undefined;
|
||||
const exit = (code: number | null) => {
|
||||
if (exited) return;
|
||||
exited = true; this.ptySessions.delete(id);
|
||||
if (!closed && !this.stopped) options.onExit?.(code);
|
||||
};
|
||||
const opening = pty.open({ id, cwd: options.cwd, cols: options.cols, rows: options.rows, ...(options.profile === undefined ? {} : { profile: options.profile }), ...(options.directory === undefined ? {} : { directory: options.directory }) },
|
||||
data => { if (!closed && !this.stopped) options.onData(data); }, exit);
|
||||
// Wait for the start, so that a close cannot leave a late shell running.
|
||||
const close = () => closing ??= (async () => {
|
||||
closed = true;
|
||||
try { await opening; } catch { this.ptySessions.delete(id); return; }
|
||||
this.ptySessions.delete(id);
|
||||
await pty.close(id);
|
||||
})();
|
||||
this.ptySessions.set(id, close);
|
||||
try { await opening; } catch (error) { this.ptySessions.delete(id); closed = true; throw error; }
|
||||
if (this.stopped) { await close(); this.check(); }
|
||||
const live = () => { this.check(); if (closed) throw new Error("This terminal is closed."); };
|
||||
return {
|
||||
id,
|
||||
write: data => { live(); if (typeof data !== "string") throw new Error("Terminal input must be text."); return pty.write(id, data); },
|
||||
resize: (cols, rows) => { live(); size(cols, rows); return pty.resize(id, cols, rows); },
|
||||
close,
|
||||
};
|
||||
};
|
||||
return {
|
||||
version: 1,
|
||||
profiles: () => this.backgroundRequest(() => pty.profiles()),
|
||||
open: options => { validate(options); return open(options); },
|
||||
openWindow: () => { this.check(); return pty.openWindow(); },
|
||||
dictation: () => { this.check(); return pty.dictation(); },
|
||||
};
|
||||
}
|
||||
private filesApi(files: FilesTransport): FilesApi {
|
||||
const text = (value: unknown, label: string) => { if (typeof value !== "string" || !value) throw new Error(`Supply the ${label} as text.`); };
|
||||
return {
|
||||
version: 1,
|
||||
chooseFolder: options => this.backgroundRequest(() => files.chooseFolder(options?.title === undefined ? undefined : { title: String(options.title) })),
|
||||
pictureFolder: name => { text(name, "folder name"); return this.backgroundRequest(() => files.pictureFolder(name)); },
|
||||
grants: () => this.backgroundRequest(() => files.grants()),
|
||||
revoke: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.revoke(grant)); },
|
||||
list: grant => { text(grant, "grant ID"); return this.backgroundRequest(() => files.list(grant)); },
|
||||
readBytes: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readBytes(grant, name)); },
|
||||
readSidecar: (grant, name) => { text(grant, "grant ID"); text(name, "file name"); return this.backgroundRequest(() => files.readSidecar(grant, name)); },
|
||||
writeSidecar: (grant, name, contents, expected) => {
|
||||
text(grant, "grant ID"); text(name, "file name");
|
||||
if (typeof contents !== "string" || (expected !== null && typeof expected !== "string")) throw new Error("Supply the sidecar text and the expected text or null.");
|
||||
return this.backgroundRequest(() => files.writeSidecar(grant, name, contents, expected));
|
||||
},
|
||||
};
|
||||
}
|
||||
private servicesApi(hub: ServiceHub): NonNullable<PluginApi["services"]> {
|
||||
return {
|
||||
version: 1,
|
||||
provide: (name, methods) => { this.check(); return hub.provide(this.serviceOwner, this.id, name, methods); },
|
||||
get: (plugin, name) => { this.check(); return hub.get(plugin, name, () => !this.stopped); },
|
||||
subscribe: listener => {
|
||||
this.check();
|
||||
if (typeof listener !== "function") throw new Error("A service listener must be a function.");
|
||||
const off = hub.subscribe((plugin, name) => { if (!this.stopped) listener(plugin, name); });
|
||||
const cleanup = () => { off(); this.serviceSubscriptions.delete(cleanup); };
|
||||
this.serviceSubscriptions.add(cleanup);
|
||||
return cleanup;
|
||||
},
|
||||
};
|
||||
}
|
||||
async dropTab(data: string) {
|
||||
this.check();
|
||||
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
|
||||
@@ -207,6 +300,8 @@ export class ExternalSession {
|
||||
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
|
||||
for (const off of this.backgroundSubscriptions) off();
|
||||
backgroundHub.removeOwner(this.backgroundOwner);
|
||||
for (const off of this.serviceSubscriptions) off();
|
||||
(this.services.serviceHub ?? defaultServiceHub).removeOwner(this.serviceOwner);
|
||||
for (const remove of this.contributions.splice(0)) remove();
|
||||
this.stopping = (async () => {
|
||||
const errors: unknown[] = [];
|
||||
@@ -217,6 +312,10 @@ export class ExternalSession {
|
||||
try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); }
|
||||
}
|
||||
this.cleanups = [];
|
||||
// Stop the terminal sessions that the plugin cleanup left open.
|
||||
for (const close of [...this.ptySessions.values()]) {
|
||||
try { await deadline(close()); } catch (error) { errors.push(error); }
|
||||
}
|
||||
if (errors.length) throw new Error(errors.map(String).join("\n"));
|
||||
})();
|
||||
return this.stopping;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Channel, invoke } from "@tauri-apps/api/core";
|
||||
import type { FilesTransport, FolderEntry, FolderGrant, PtyProfile, PtyTransport } from "./sdk.ts";
|
||||
|
||||
/**
|
||||
* Terminal sessions over a channel to this webview. The output arrives as raw bytes, and no
|
||||
* `pty-data` or `pty-exit` event goes to other windows. The released Terminal plugin uses the
|
||||
* events instead, and the host keeps them for sessions without a channel.
|
||||
*/
|
||||
export const ptyTransport: PtyTransport = {
|
||||
open: (request, onData, onExit) => {
|
||||
const channel = new Channel<ArrayBuffer | { exit: number | null }>(message => {
|
||||
if (message instanceof ArrayBuffer) onData(new Uint8Array(message));
|
||||
else if (message && typeof message === "object" && "exit" in message) onExit(message.exit);
|
||||
});
|
||||
return invoke<void>("pty_open", { ...request, channel });
|
||||
},
|
||||
write: (id, data) => invoke<void>("pty_write", { id, data }),
|
||||
resize: (id, cols, rows) => invoke<void>("pty_resize", { id, cols, rows }),
|
||||
close: id => invoke<void>("pty_close", { id }),
|
||||
profiles: () => invoke<PtyProfile[]>("pty_profiles"),
|
||||
openWindow: () => invoke<void>("pty_new_window", { id: crypto.randomUUID() }),
|
||||
dictation: () => invoke<void>("pty_dictation"),
|
||||
};
|
||||
|
||||
/** Folder grants of one plugin. The plugin ID comes from the host, not from the plugin. */
|
||||
export function filesTransport(plugin: string): FilesTransport {
|
||||
return {
|
||||
chooseFolder: options => invoke<FolderGrant | null>("folders_choose", { plugin, title: options?.title ?? null }),
|
||||
pictureFolder: name => invoke<FolderGrant>("folders_picture", { plugin, name }),
|
||||
grants: () => invoke<FolderGrant[]>("folders_grants", { plugin }),
|
||||
revoke: grant => invoke<boolean>("folders_revoke", { plugin, grant }),
|
||||
list: grant => invoke<FolderEntry[]>("folders_list", { plugin, grant }),
|
||||
readBytes: async (grant, name) => new Uint8Array(await invoke<ArrayBuffer>("folders_read", { plugin, grant, name })),
|
||||
readSidecar: (grant, name) => invoke<string | null>("folders_read_sidecar", { plugin, grant, name }),
|
||||
writeSidecar: (grant, name, contents, expected) => invoke<void>("folders_write_sidecar", { plugin, grant, name, contents, expected }),
|
||||
};
|
||||
}
|
||||
@@ -19,7 +19,72 @@ export interface PluginDocumentType {
|
||||
create?: { label: string; defaultName: string; extension: string; contents(): string };
|
||||
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
||||
}
|
||||
export interface PtyProfile { id: string; title: string; kind: string }
|
||||
export interface PtyOpenOptions {
|
||||
/** The workspace root of the window. The host rejects the request when the workspace changed. */
|
||||
cwd: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
profile?: string;
|
||||
/** A start folder other than the workspace root. */
|
||||
directory?: string;
|
||||
/** Receives raw terminal output. UTF-8 characters can be split between two calls. */
|
||||
onData(data: Uint8Array): void;
|
||||
onExit?(code: number | null): void;
|
||||
}
|
||||
export interface PtySession {
|
||||
readonly id: string;
|
||||
write(data: string): Promise<void>;
|
||||
resize(cols: number, rows: number): Promise<void>;
|
||||
/** Stops the shell. Repeated calls return the same promise. */
|
||||
close(): Promise<void>;
|
||||
}
|
||||
/** Terminal sessions. The host closes the sessions of a plugin when the plugin stops. */
|
||||
export interface PtyApi {
|
||||
readonly version: 1;
|
||||
profiles(): Promise<PtyProfile[]>;
|
||||
open(options: PtyOpenOptions): Promise<PtySession>;
|
||||
openWindow(): Promise<void>;
|
||||
dictation(): Promise<void>;
|
||||
}
|
||||
/** The native side of `PtyApi`. `onData` and `onExit` receive the output of this session only. */
|
||||
export interface PtyTransport {
|
||||
open(request: { id: string; cwd: string; cols: number; rows: number; profile?: string; directory?: string }, onData: (data: Uint8Array) => void, onExit: (code: number | null) => void): Promise<void>;
|
||||
write(id: string, data: string): Promise<void>;
|
||||
resize(id: string, cols: number, rows: number): Promise<void>;
|
||||
close(id: string): Promise<void>;
|
||||
profiles(): Promise<PtyProfile[]>;
|
||||
openWindow(): Promise<void>;
|
||||
dictation(): Promise<void>;
|
||||
}
|
||||
export interface FolderGrant { id: string; path: string; name: string }
|
||||
export interface FolderEntry { name: string; size: number }
|
||||
/** Folders outside the workspace that the user granted to this plugin. */
|
||||
export interface FilesApi {
|
||||
readonly version: 1;
|
||||
chooseFolder(options?: { title?: string }): Promise<FolderGrant | null>;
|
||||
pictureFolder(name: string): Promise<FolderGrant>;
|
||||
grants(): Promise<FolderGrant[]>;
|
||||
revoke(grant: string): Promise<boolean>;
|
||||
list(grant: string): Promise<FolderEntry[]>;
|
||||
readBytes(grant: string, name: string): Promise<Uint8Array>;
|
||||
readSidecar(grant: string, name: string): Promise<string | null>;
|
||||
writeSidecar(grant: string, name: string, contents: string, expected: string | null): Promise<void>;
|
||||
}
|
||||
/** The native side of `FilesApi`, bound to one plugin ID by the host. */
|
||||
export type FilesTransport = Omit<FilesApi, "version">;
|
||||
export type ServiceMethods = Record<string, (...args: never[]) => unknown>;
|
||||
/** Data that one plugin offers to other plugins in the same window. */
|
||||
export interface ServicesApi {
|
||||
readonly version: 1;
|
||||
provide(name: string, methods: ServiceMethods): { notify(): void; dispose(): void };
|
||||
get(plugin: string, name: string): Record<string, (...args: unknown[]) => Promise<unknown>> | null;
|
||||
subscribe(listener: (plugin: string, name: string) => void): Dispose;
|
||||
}
|
||||
export interface PluginApi {
|
||||
pty?: PtyApi;
|
||||
files?: FilesApi;
|
||||
services?: ServicesApi;
|
||||
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
|
||||
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
|
||||
git?: import("../git/contracts.ts").GitApi;
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ServiceMethods } from "./sdk.ts";
|
||||
|
||||
const namePattern = /^[a-z][a-z0-9.-]{0,63}$/;
|
||||
|
||||
/**
|
||||
* Plugin services in one window. A provider plugin offers named methods, and other plugins call
|
||||
* them through the host. Arguments and results are copied with `structuredClone`, so a later
|
||||
* message-based SDK can keep the same contract. Calls always return promises.
|
||||
*/
|
||||
export class ServiceHub {
|
||||
private services = new Map<string, { owner: symbol; methods: ServiceMethods }>();
|
||||
private listeners = new Set<(plugin: string, name: string) => void>();
|
||||
|
||||
provide(owner: symbol, plugin: string, name: string, methods: ServiceMethods): { notify(): void; dispose(): void } {
|
||||
if (!namePattern.test(name)) throw new Error("A service name uses lowercase letters, digits, dots, and hyphens, and starts with a letter.");
|
||||
if (!methods || typeof methods !== "object" || !Object.keys(methods).length || Object.values(methods).some(method => typeof method !== "function")) {
|
||||
throw new Error("A service needs an object of functions.");
|
||||
}
|
||||
const key = plugin + "/" + name;
|
||||
if (this.services.has(key)) throw new Error("This plugin already provides the service.");
|
||||
const entry = { owner, methods: { ...methods } };
|
||||
this.services.set(key, entry);
|
||||
this.changed(plugin, name);
|
||||
let active = true;
|
||||
return {
|
||||
notify: () => { if (active) this.changed(plugin, name); },
|
||||
dispose: () => {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
if (this.services.get(key) === entry) { this.services.delete(key); this.changed(plugin, name); }
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Return callable copies of the methods, or `null` when the service is not available. */
|
||||
get(plugin: string, name: string, alive: () => boolean): Record<string, (...args: unknown[]) => Promise<unknown>> | null {
|
||||
const key = plugin + "/" + name;
|
||||
const entry = this.services.get(key);
|
||||
if (!entry) return null;
|
||||
const result: Record<string, (...args: unknown[]) => Promise<unknown>> = {};
|
||||
for (const method of Object.keys(entry.methods)) {
|
||||
result[method] = async (...args: unknown[]) => {
|
||||
const current = this.services.get(key);
|
||||
if (!alive()) throw new Error("This plugin is disabled.");
|
||||
if (current !== entry) throw new Error("The service is no longer available.");
|
||||
const value = await (entry.methods[method] as (...values: unknown[]) => unknown)(...structuredClone(args));
|
||||
if (!alive()) throw new Error("This plugin is disabled.");
|
||||
if (this.services.get(key) !== entry) throw new Error("The service is no longer available.");
|
||||
return structuredClone(value);
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
subscribe(listener: (plugin: string, name: string) => void): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => { this.listeners.delete(listener); };
|
||||
}
|
||||
|
||||
removeOwner(owner: symbol) {
|
||||
for (const [key, entry] of [...this.services]) {
|
||||
if (entry.owner !== owner) continue;
|
||||
this.services.delete(key);
|
||||
const [plugin, name] = key.split("/");
|
||||
this.changed(plugin, name);
|
||||
}
|
||||
}
|
||||
|
||||
private changed(plugin: string, name: string) {
|
||||
for (const listener of [...this.listeners]) {
|
||||
try { listener(plugin, name); } catch { /* One subscriber must not stop the others. */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const serviceHub = new ServiceHub();
|
||||
@@ -0,0 +1,156 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession, type SessionServices } from "../../../src/lib/plugins/externalSession.ts";
|
||||
import { ContributionRegistry } from "../../../src/lib/plugins/registry.ts";
|
||||
import { ServiceHub } from "../../../src/lib/plugins/services.ts";
|
||||
import type { FilesTransport, PluginApi, PtyTransport } from "../../../src/lib/plugins/sdk.ts";
|
||||
|
||||
const base: SessionServices = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
};
|
||||
|
||||
async function start(id: string, services: Partial<SessionServices>) {
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession(id, { ...base, ...services }, () => {}, () => {}, new ContributionRegistry());
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
return { api, session };
|
||||
}
|
||||
|
||||
function fakePty() {
|
||||
const calls: unknown[][] = [];
|
||||
const outputs = new Map<string, { data: (bytes: Uint8Array) => void; exit: (code: number | null) => void }>();
|
||||
let release: (() => void) | undefined;
|
||||
const transport: PtyTransport & { hold(): void } = {
|
||||
hold() { let done!: () => void; const wait = new Promise<void>(resolve => { done = resolve; }); release = done; holding = wait; },
|
||||
open: async (request, data, exit) => { calls.push(["open", request]); outputs.set(request.id, { data, exit }); await holding; },
|
||||
write: async (id, data) => { calls.push(["write", id, data]); },
|
||||
resize: async (id, cols, rows) => { calls.push(["resize", id, cols, rows]); },
|
||||
close: async id => { calls.push(["close", id]); },
|
||||
profiles: async () => [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }],
|
||||
openWindow: async () => { calls.push(["window"]); },
|
||||
dictation: async () => { calls.push(["dictation"]); },
|
||||
};
|
||||
let holding: Promise<void> = Promise.resolve();
|
||||
return { transport, calls, outputs, release: () => release?.() };
|
||||
}
|
||||
|
||||
test("terminal sessions deliver their own output and close when the plugin stops", async () => {
|
||||
const pty = fakePty();
|
||||
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
|
||||
assert.equal(api.pty!.version, 1);
|
||||
assert.deepEqual(await api.pty!.profiles(), [{ id: "pwsh", title: "PowerShell 7", kind: "powershell" }]);
|
||||
const received: string[] = [];
|
||||
const exits: (number | null)[] = [];
|
||||
const first = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh", onData: data => received.push(new TextDecoder().decode(data)), onExit: code => exits.push(code) });
|
||||
const second = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
|
||||
assert.notEqual(first.id, second.id);
|
||||
assert.deepEqual(pty.calls[0], ["open", { id: first.id, cwd: "C:/work", cols: 80, rows: 24, profile: "pwsh" }]);
|
||||
pty.outputs.get(first.id)!.data(new TextEncoder().encode("ready"));
|
||||
await first.write("dir\r");
|
||||
await first.resize(100, 30);
|
||||
assert.deepEqual(received, ["ready"]);
|
||||
assert.deepEqual(pty.calls.slice(-2), [["write", first.id, "dir\r"], ["resize", first.id, 100, 30]]);
|
||||
assert.throws(() => first.resize(0, 30), /positive integers/);
|
||||
// An exited session needs no close at shutdown.
|
||||
pty.outputs.get(first.id)!.exit(0);
|
||||
assert.deepEqual(exits, [0]);
|
||||
await session.stop();
|
||||
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", second.id]]);
|
||||
pty.outputs.get(second.id)!.data(new TextEncoder().encode("late"));
|
||||
assert.deepEqual(received, ["ready"]);
|
||||
assert.throws(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} }), /disabled/);
|
||||
assert.throws(() => api.pty!.openWindow(), /disabled/);
|
||||
assert.throws(() => second.write("x"), /disabled/);
|
||||
// Close stays safe after shutdown and is not repeated.
|
||||
await second.close();
|
||||
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
|
||||
});
|
||||
|
||||
test("a terminal session that starts after shutdown is closed", async () => {
|
||||
const pty = fakePty();
|
||||
const { api, session } = await start("org.test.terminal", { pty: pty.transport });
|
||||
pty.transport.hold();
|
||||
const opening = api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: () => {} });
|
||||
const stopping = session.stop();
|
||||
pty.release();
|
||||
await assert.rejects(opening, /disabled/);
|
||||
await stopping;
|
||||
const id = (pty.calls[0][1] as { id: string }).id;
|
||||
assert.deepEqual(pty.calls.filter(call => call[0] === "close"), [["close", id]]);
|
||||
});
|
||||
|
||||
test("a closed terminal session rejects input and closes once", async () => {
|
||||
const pty = fakePty();
|
||||
const { api } = await start("org.test.terminal", { pty: pty.transport });
|
||||
const output: string[] = [];
|
||||
const terminal = await api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24, onData: data => output.push(String(data.length)) });
|
||||
await Promise.all([terminal.close(), terminal.close()]);
|
||||
assert.equal(pty.calls.filter(call => call[0] === "close").length, 1);
|
||||
assert.throws(() => terminal.write("x"), /closed/);
|
||||
pty.outputs.get(terminal.id)!.data(new Uint8Array([1]));
|
||||
assert.deepEqual(output, []);
|
||||
await assert.rejects(Promise.resolve().then(() => api.pty!.open({ cwd: "C:/work", cols: 80, rows: 24 } as never)), /onData/);
|
||||
});
|
||||
|
||||
test("folder grant calls check shutdown before and after the native request", async () => {
|
||||
const calls: unknown[][] = [];
|
||||
let finish: ((value: unknown) => void) | undefined;
|
||||
const grant = { id: "7f1b6f6e-3c39-4b55-9f3e-4a3a6d1d7c11", path: "C:/Pictures/RuneStone Backgrounds", name: "RuneStone Backgrounds" };
|
||||
const files: FilesTransport = {
|
||||
chooseFolder: async options => { calls.push(["choose", options]); return grant; },
|
||||
pictureFolder: async name => { calls.push(["picture", name]); return grant; },
|
||||
grants: async () => [grant],
|
||||
revoke: async id => { calls.push(["revoke", id]); return true; },
|
||||
list: () => new Promise(resolve => { finish = resolve as (value: unknown) => void; }),
|
||||
readBytes: async (id, name) => { calls.push(["read", id, name]); return new Uint8Array([1, 2]); },
|
||||
readSidecar: async () => null,
|
||||
writeSidecar: async (id, name, contents, expected) => { calls.push(["write", id, name, contents, expected]); },
|
||||
};
|
||||
const { api, session } = await start("org.test.slides", { files });
|
||||
assert.deepEqual(await api.files!.chooseFolder({ title: "Images" }), grant);
|
||||
assert.deepEqual(await api.files!.pictureFolder("Backgrounds"), grant);
|
||||
assert.deepEqual(await api.files!.readBytes(grant.id, "a.png"), new Uint8Array([1, 2]));
|
||||
await api.files!.writeSidecar(grant.id, ".runestone-backgrounds.json", "{}", null);
|
||||
assert.equal(await api.files!.revoke(grant.id), true);
|
||||
assert.deepEqual(calls, [["choose", { title: "Images" }], ["picture", "Backgrounds"], ["read", grant.id, "a.png"], ["write", grant.id, ".runestone-backgrounds.json", "{}", null], ["revoke", grant.id]]);
|
||||
assert.throws(() => api.files!.readBytes("", "a.png"), /grant ID/);
|
||||
assert.throws(() => api.files!.writeSidecar(grant.id, ".runestone-a.json", "{}", undefined as never), /expected/);
|
||||
const pending = api.files!.list(grant.id);
|
||||
await session.stop();
|
||||
finish!([{ name: "a.png", size: 2 }]);
|
||||
await assert.rejects(pending, /disabled/);
|
||||
assert.throws(() => api.files!.grants(), /disabled/);
|
||||
});
|
||||
|
||||
test("plugin services copy data, stop with their provider, and stop for a stopped consumer", async () => {
|
||||
const serviceHub = new ServiceHub();
|
||||
const boards = [{ id: "b1", name: "Roadmap" }];
|
||||
const provider = await start("org.test.boards", { serviceHub });
|
||||
const consumer = await start("org.test.slides", { serviceHub });
|
||||
const changes: string[] = [];
|
||||
consumer.api.services!.subscribe((plugin, name) => changes.push(`${plugin}/${name}`));
|
||||
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
|
||||
const handle = provider.api.services!.provide("boards", { list: () => boards });
|
||||
assert.throws(() => provider.api.services!.provide("boards", { list: () => boards }), /already/);
|
||||
assert.throws(() => provider.api.services!.provide("Bad Name", { list: () => boards }), /service name/);
|
||||
const service = consumer.api.services!.get("org.test.boards", "boards")!;
|
||||
const result = await service.list() as typeof boards;
|
||||
assert.deepEqual(result, boards);
|
||||
result[0].name = "Changed";
|
||||
assert.equal(boards[0].name, "Roadmap", "the consumer receives a copy");
|
||||
handle.notify();
|
||||
assert.deepEqual(changes, ["org.test.boards/boards", "org.test.boards/boards"]);
|
||||
await provider.session.stop();
|
||||
assert.deepEqual(changes.at(-1), "org.test.boards/boards");
|
||||
await assert.rejects(service.list(), /no longer available/);
|
||||
assert.equal(consumer.api.services!.get("org.test.boards", "boards"), null);
|
||||
const again = await start("org.test.boards", { serviceHub });
|
||||
again.api.services!.provide("boards", { list: () => boards });
|
||||
const fresh = consumer.api.services!.get("org.test.boards", "boards")!;
|
||||
await consumer.session.stop();
|
||||
await assert.rejects(fresh.list(), /disabled/);
|
||||
const count = changes.length;
|
||||
await again.session.stop();
|
||||
assert.equal(changes.length, count, "a stopped consumer receives no notifications");
|
||||
});
|
||||
Reference in New Issue
Block a user