Files
RuneStone/docs/plugin-host.md
T
Knotty Wyvern 956ead818b Translate Project Management and add its tests and guide
- Every interface string of Project Management goes through the catalog: 539 new rows with fr, ja, and zh-CN.
- Storage and model messages use a local message() marker and stay free of host imports. The interface translates them.
- A board renders again when the language changes. Dates use the interface language.
- Fix: the ribbon button waits for the feature switches at startup, and the settings code loads no feature module.
- Add six smoke tests: board state, cards, menus, drag and drop, views, and language.
- Add docs/guides/project-management.md and UI-060. Update the user, plugin, SDK, host, development, and interface docs and CLAUDE.md.
- Name the fake board view of tree/renameUndo "Board fixture", because the native Project Management button is now in the ribbon.
2026-10-29 21:53:09 -07:00

271 lines
21 KiB
Markdown

# Plugin host internals
[Development](development.md) · [Plugin development](plugin-development.md) · [Install and manage plugins](plugins.md)
This reference describes how RuneStone stores, installs, downloads, and removes plugins, for developers who change the plugin host.
- [Storage and recovery](#storage-and-recovery)
- [Gitea downloads](#gitea-downloads)
- [Content security policy](#content-security-policy)
- [Window capabilities](#window-capabilities)
- [Modules and checks](#modules-and-checks)
## Storage and recovery
The native plugin service is in `src-tauri/src/plugins.rs`. Its root is the Tauri `app_data_dir()`.
```text
<application-data>/
plugin-state.json catalog: manifest, hash, enabled state, install time, removal record
plugins/<plugin-id>/ installed packages
plugin-data/<plugin-id>/settings.json
plugin-staging/ review copies, update backups, and update-<uuid>.json journals
plugin-removals/<token>/ packages during confirmed removal
```
The preferences of the app are not plugin data. They are in `settings.json` in the Tauri `app_config_dir()`.
On Windows and macOS, this is the same folder as `app_data_dir()`. See [the settings file](development.md#the-settings-file).
**Settings → Plug-ins → Open plugins folder** opens `plugins/`.
The service writes `plugin-state.json` to a temporary file, then renames it. It reads at most 4 MiB from that file.
After each change, the service sends the `plugins-changed` event to all windows. A settings write sends `plugin-settings-changed` with the plugin ID.
The browser preview (`pnpm dev`) has no installed plugins unless a smoke test supplies a desktop mock.
The built-in browser and the theme editor use the plugin API, but they are not packages. `builtInModules` in `src/lib/plugins/external.ts` lists them. The host starts them in each window, and the plugin menus do not list their tools. A browser window starts only the browser.
`builtInPackages` lists the IDs of old packages for features that RuneStone now includes. The host never loads such a package. Settings → Plug-ins shows it as included with RuneStone, so that the user can remove it.
Native features, such as Git, Terminal, and Project Management, do not use the plugin API. `syncFeatures` in `external.ts` gives each feature that is on a feature session (`src/lib/features/session.ts`) under the ID of its old package, so that its views and document types share the tab model of plugin views. A view pattern in the catalog gives a feature many editor views, for example one for each board (`board-<hex>`). A tab transfer of such a view works before the feature loads. The file tree identifies the files of a feature document type, such as PDF files, without the feature code. A launch rule (`src/lib/features/launch.ts`) can start a feature at once: Background starts when a folder or an image is selected. Browser windows start only the features with a browser window rule, which is Background. See [Native features](development.md#native-features).
`features_legacy` (`src-tauri/src/features.rs`) reads the catalog row and the kept `plugin-data/<id>/settings.json` of an old package. It accepts only the IDs of native features and changes no file.
### Scans
Each window asks for a new snapshot at these times:
| Trigger | Source |
| --- | --- |
| Window start | `startExternalPlugins` in `src/lib/plugins/external.ts` |
| Window focus | The same function |
| **Refresh** in Settings → Plug-ins | `PluginManager.svelte` |
| `plugins-changed` event | Any change from another window |
There is no timed scan. A change from a file manager appears at the next focus or **Refresh**. RuneStone does not support packages that users copy into the folder.
A scan reads file metadata, and reads and hashes files only when necessary. It does not run code, install dependencies, or run scripts.
- A package with a changed hash gets an error and becomes disabled. The user must review it and enable it again.
- When a package folder is missing, the service removes its catalog entry. It never restores a missing package.
- A valid package that someone copies directly into `plugins/` appears as disabled, with an unknown install time.
- The service never scans `plugin-staging/`.
### Package hashes
The package hash is a SHA-256 hash of all file names and contents. To avoid a full read of each package at each scan, the service keeps a cache in memory:
| Step | Reads |
| --- | --- |
| Scan (`plugins_snapshot`), `plugins_data`, and the row checks of other commands | The metadata of the package folder: entry names, file sizes, and modification times. The service reads and hashes the files again only when this metadata changed. |
| Enable (`plugins_set_enabled`) and load (`plugins_load`) | All files. The hash must agree with the hash that the user saw (enable) or the installed hash (load). The cache cannot approve code. |
| Asset (`plugins_asset`) | The metadata, then the one file. The file must have the SHA-256 hash from the last full read. |
| Install, update, and removal | All files, as before. These steps also clear the cache entry of the package. |
The cache keeps the metadata from before each read. A file that changes during a read thus causes a new read at the next check.
An edit that keeps the file size and the modification time stays hidden from a scan. The next load or asset read finds it, and the plugin then becomes disabled at the next scan.
### Waits for other windows
An update and a removal disable the plugin, then wait until no window holds a lease, at most 10 seconds.
The wait uses a condition variable that `plugins_release` and window close signal. It does not keep the plugin lock while it waits.
### Install and update
1. The ZIP picker accepts at most 100 `.zip` files. Folders and loose manifests are not installation inputs.
2. For each ZIP, the service applies the [package contract](plugin-development.md#package-contract) and writes a review copy to `plugin-staging/<token>/`. It does not change the source file.
3. The review shows the name, author, version, description, source, and destination. For an update, it also shows the installed and new versions. Each review belongs to one window and expires after 30 minutes. Closing the window discards it.
4. At install, the service makes sure that the source and the review copy still have the reviewed hash.
5. The service saves the new catalog entry as disabled and moves the review copy into `plugins/<id>/`. Then it enables the plugin if the user chose **Install and enable**. A crash cannot enable a partial package.
A package with an installed ID starts an update:
1. The service disables the plugin and waits up to 10 seconds for every window to stop it.
2. It writes an `update-<uuid>.json` journal, moves the old package to a backup folder, and moves the new package into place.
3. It saves the catalog with the new hash and the previous enabled state. Settings in `plugin-data/` stay the same.
4. At startup, an uncommitted journal restores the old package, disabled. A committed journal deletes the backup.
Each package succeeds or fails independently. Cancel deletes the review copies.
### Removal
1. **Uninstall** makes a removal plan with a hash of the package folder. The plan belongs to one window and expires after 5 minutes.
2. Confirmation uses the plan token once. A changed package needs a new confirmation.
3. The service disables the plugin and waits up to 10 seconds for every window to finish cleanup. A cleanup failure blocks removal until RuneStone restarts.
4. The service saves a removal record with the SHA-256 hash of each file. Then it moves the folder to `plugin-removals/<token>/` and deletes it.
5. If deletion stops, Settings shows **Removal incomplete** and **Retry cleanup**. Retry deletes the folder only when every remaining file matches its recorded hash. Otherwise it stops and names the folder.
6. At startup, the service examines each removal record. If the package is still in `plugins/` and its removal folder does not exist, the service clears the record. The plugin stays disabled.
Removal keeps `plugin-data/`, source ZIPs, and workspace documents. Loaded JavaScript can stay in memory, so RuneStone asks for a restart.
The uninstall dialog puts focus on **Cancel**. Escape cancels.
### Runtime leases
`plugins_load` returns the entry module and records a lease for the window. `plugins_release` ends the lease and records any cleanup error.
Updates and removals wait for all leases to end. A recorded cleanup error blocks enable, update, and removal until RuneStone restarts.
Native services for plugins, such as the folder grant commands (`folders_*`), need a lease for the calling window.
## Gitea downloads
`src-tauri/src/plugin_sources.rs` gets a plugin ZIP from a Gitea release. It is separate from package checks and installation.
It does not clone the repository, compile code, install dependencies, or run scripts.
For the user procedure, see [Install from a Gitea link](plugins.md#install-from-a-gitea-link-experimental).
### Accepted links and releases
- The link is a repository root, `https://<host>/<owner>/<repository>`, with an optional `.git` or trailing slash. Gitea must run at the root of the host.
- Links with credentials, a query, or a fragment are invalid. SSH links and branch links are invalid.
- Without a tag, the service reads `/api/v1/repos/<owner>/<repository>/releases/latest`. Gitea excludes drafts and prereleases from this route.
- With a tag (at most 200 characters), it reads `/releases/tags/<tag>`. Use an explicit tag for a prerelease.
- The release must not be a draft. It must have exactly one `.zip` attachment. Automatic source archives are not attachments.
### Limits
| Limit | Value |
| --- | --- |
| Release metadata | 2 MiB |
| Plugin ZIP | 100 MiB |
| Redirects for each request | 5 |
| Total time for each request | 60 seconds |
| Connection time | 10 seconds |
The [package limits](plugin-development.md#paths-and-limits) also apply to the extracted files.
### HTTPS, HTTP, and credentials
- For an HTTPS repository link, the ZIP link must use HTTPS. The service refuses a redirect from HTTPS to HTTP.
- HTTP links work for trusted local servers. The form shows a warning that HTTP sends the token and the package without encryption.
- The service sends the token as `Authorization: token <value>`, only to the origin of the release API. Redirects to another origin do not get the token.
- The form clears the token after each request and when it closes. RuneStone does not save the token.
- A private repository needs a token with read access to the release metadata and the attachment.
### Review
The service writes the downloaded bytes to `plugin-staging/`, applies the same checks as a local ZIP, and deletes the archive.
The review shows the repository, the tag, and the attachment link without its query. It pins the downloaded hash.
A change to the remote release after review does not change the pending installation.
The same ID, enable, update, and removal rules apply to local and remote packages.
## Content security policy
`app.security.csp` in `src-tauri/tauri.conf.json` holds the policy. It limits what a page can load. It does not isolate plugins: a plugin module runs in the app window with the same access as the app.
The policy stops a script that comes in through rendered content, for example a `<script>` element or an event attribute in a Markdown document.
| Directive | Sources | Reason |
| --- | --- | --- |
| `default-src` | `'self'` | All other types come only from the app. |
| `script-src` | `'self' blob: 'wasm-unsafe-eval'` | `blob:`: plugin entry modules, which `external.ts` loads from Blob URLs. `'wasm-unsafe-eval'`: PDF.js in the PDF Viewer feature decodes JPEG 2000 and JBIG2 images and compiles PostScript functions with WebAssembly. Its worker is a file of the app and gets no policy, so this source applies only to PDF.js code on the page. It does not permit `eval`. |
| `style-src` | `'self' 'unsafe-inline'` | Svelte `style` attributes, the `style` attribute in `src/app.html`, Mermaid SVG styles, and the `<style>` elements of CodeMirror, xterm in the Terminal feature, the Vite dev server, and plugins (CSV Viewer). |
| `img-src` | `'self' data: blob: https: http:` | `data:`: workspace images, browser frames, tab and site icons, and icons in CSS. `blob:`: background images. `https:` and `http:`: remote images in Markdown previews. |
| `font-src` | `'self' data:` | `'self'`: fonts that the app serves. The app serves no font now. `data:`: PDF.js can load the embedded fonts of a PDF from data addresses. |
| `connect-src` | `'self' ipc: http://ipc.localhost blob:` | `ipc:` and `http://ipc.localhost`: Tauri commands. `blob:`: the blur worker of the Background feature reads its image from a Blob URL. |
| `worker-src` | `'self' blob:` | `'self'`: workers that the app serves, such as the PDF.js worker of each PDF tab. `blob:`: the blur worker of the Background feature. |
| `object-src` | `'none'` | RuneStone uses no plugins of the web view. |
| `base-uri` | `'self'` | |
| `form-action` | `'none'` | No form sends data to an address. |
| `frame-ancestors` | `'none'` | |
No source permits `'unsafe-eval'`. The app, CodeMirror, Mermaid, and the current plugins do not use `eval` or `new Function`.
`style-src` needs `'unsafe-inline'`, because style attributes and generated `<style>` elements have no nonce.
Tauri sends the policy as a header with each HTML page of the installed app. It adds the SHA-256 hash of the inline start script of SvelteKit to `script-src`.
`dangerousDisableAssetCspModification: ["style-src"]` stops Tauri from adding nonces to `style-src`, because a nonce disables `'unsafe-inline'`. Tauri still adds the script hashes.
`pnpm tauri dev` loads the page from the Vite server. Tauri does not apply the policy there. Use the [CSP mode](development.md#csp-mode) of the smoke tests, or an installed build.
Workers that the app loads from its own files get no policy. Workers from Blob URLs get the policy of the page.
## Window capabilities
`src-tauri/capabilities/` gives commands to window labels. A plugin can call every command that its window allows.
| Capability | Windows | Plugins | Commands |
| --- | --- | --- | --- |
| `default.json` | `main`, `workspace-*`, `terminal-*` | All enabled plugins | All app commands |
| `settings.json` | `settings-main`, `settings-workspace-*` | All enabled plugins | Settings, plugins, the Background folder, folder grants, completion, browser, `pty_profiles`, and `pty_running` |
| `browser.json` | `browser-*` | Only the built-in browser (`builtInModules` in `src/lib/plugins/external.ts`) | Browser, `plugins_snapshot`, settings, spelling, window controls, and the read commands of the Background folder (`background_folder`, `background_list`, `background_read`, `background_read_sidecar`) |
A browser window loads no installed plugin, so its capability has no workspace, file, Git, terminal, or plugin package commands. The Background feature runs there to show the background behind a blank tab, so the window can read the Background folder. `tests/unit/plugins/windowCapabilities.spec.ts` and `tests/smoke/browser/window.smoke.mjs` check this.
The other windows load every enabled plugin. A smaller command set for them would limit only the app code, not the plugins. That split belongs to the plugin isolation work. Findings for that work:
- Terminal windows use the `pty_*` commands of the Terminal feature, the plugin host commands, and `core:window:allow-destroy`. Other plugins in the same window expect the full host API.
- Settings windows use no `workspace_*` or `git_*` commands, but plugin settings views run there. Of the `pty_*` commands, they use only `pty_profiles` for Settings → Terminal and `pty_running` before Terminal goes off.
- Commands that need a workspace (`workspace_*`, `git_*`, `pty_open`, `pty_new_window`) fail in a window without a bound workspace.
- `pty_write`, `pty_resize`, and `pty_close` act only on the sessions of the calling window. A session of another window counts as a missing session.
- `pty_open` needs an output channel and a page ID. The first open of a new page in a window, after a reload, closes the sessions of the earlier page. The host refuses a late open from an old page.
- `folders_*` need a plugin lease of the calling window. The `background_*` commands of the Background feature need no lease. They take no path: the host keeps the folder that the folder dialog gave.
- `browser_request` needs the session token that `browser_connect` gives the window. A plugin lease does not replace it.
- A new command for plugins goes in `default.json` and, if settings views need it, in `settings.json`. Add it to `browser.json` only when the built-in browser needs it.
## Modules and checks
| Module | Owns |
| --- | --- |
| `src-tauri/src/plugins.rs` | Package checks, discovery, installation, updates, persistence, removal, leases, settings, and assets |
| `src-tauri/src/plugin_sources.rs` | Gitea link parsing and release downloads |
| `src-tauri/src/backgrounds.rs` | The image folder of the native Background feature. Plugins use folder grants |
| `src-tauri/src/folders.rs` | Folder grants for `api.files`: the picker, stored grants, listing, reads, and settings files beside the images |
| `src-tauri/src/pty.rs` | The shell sessions of the Terminal feature. Output goes as raw bytes through the channel of `pty_open`, in messages of up to 64 KiB or 8 ms. `pty_running` counts the sessions of all windows |
| `src/lib/plugins/sdk.ts` | The public package API types |
| `src/lib/plugins/externalSession.ts` | Activation, API checks, contributions, mounts, and shutdown |
| `src/lib/plugins/external.ts` | Native state sync, module loading, scans, views, tabs, and document types |
| `src/lib/plugins/registry.ts` / `contracts.ts` | Shared contributions and their types |
| `src/lib/plugins/access.ts` / `PluginAccessMenu.svelte` | The **Plug-in views** and **Commands** menus |
| `src/lib/plugins/PluginManager.svelte` | Settings → Plug-ins: review, switches, Gitea form, and uninstall dialog |
| `src/lib/plugins/PluginSettings.svelte` | Plugin configuration pages in Settings |
| `src/lib/plugins/PluginTools.svelte` / `PluginEditor.svelte` | Dialog views and editor views |
| `src/lib/plugins/backgrounds.ts` | The background frames of one window. The Background feature sets them, and Project Management reads the board targets. Plugins have no access. |
| `src/lib/plugins/nativeServices.ts` | The host side of `api.files`. It binds the plugin ID. The plugin never sends it |
| `src/lib/plugins/services.ts` | `api.services`: services that one plugin offers to another in the same window |
| `src/lib/completion/` | The [completion API](completion.md) |
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
### Run the plugin checks
Run these commands from the RuneStone repository root.
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
Unit tests:
```powershell
node --experimental-strip-types --test tests/unit/plugins/plugins.spec.ts tests/unit/plugins/externalPlugins.spec.ts tests/unit/plugins/pluginPackaging.spec.ts tests/unit/plugins/pluginHostExtensions.spec.ts tests/unit/plugins/pluginDocuments.spec.ts tests/unit/plugins/pluginAccess.spec.ts tests/unit/plugins/completion.spec.ts tests/unit/plugins/windowCapabilities.spec.ts tests/unit/plugins/pluginNativeApis.spec.ts tests/unit/theme/backgrounds.spec.ts
```
Native tests use real temporary files and archives:
```powershell
cargo test --manifest-path src-tauri/Cargo.toml --lib plugin
```
Browser smoke tests mock desktop calls and use the real interface and module loader. Run them while `pnpm dev` runs:
```powershell
node tests/smoke/plugins/install.smoke.mjs
node tests/smoke/plugins/lifecycle.smoke.mjs
node tests/smoke/plugins/access.smoke.mjs
node tests/smoke/plugins/choiceMenus.smoke.mjs
node tests/smoke/find/pluginViews.smoke.mjs
node tests/smoke/tabs/lastTabAndSiteIcons.smoke.mjs
node tests/smoke/settings/general.smoke.mjs
node tests/smoke/browser/window.smoke.mjs
```
`pluginInstall.smoke.mjs` covers the link form, download errors, token clearing, cancel, focus, and disabled installation.
The native tests cover link parsing, release selection, redirects, credential boundaries, size limits, changed review copies, and invalid ZIPs.
Two native release tests are ignored by default:
| Test | Setup |
| --- | --- |
| `four_plugin_release_trial` | Set `RUNESTONE_GIT_TRIAL_PACKAGES` to a folder that contains exactly four plugin ZIPs. |
| `live_gitea_release_trial` | Set `RUNESTONE_GIT_TRIAL_URL`, `RUNESTONE_GIT_TRIAL_TAG`, and `RUNESTONE_GIT_TRIAL_ZIP` (the expected ZIP). Set `RUNESTONE_GIT_TRIAL_TOKEN` for a private repository. |
```powershell
cargo test --manifest-path src-tauri/Cargo.toml --lib four_plugin_release_trial -- --ignored --nocapture
```