Add completion, browser integration, and workspace improvements

This commit is contained in:
Knotty Wyvern
2026-10-07 11:25:17 -07:00
parent dd9fc64676
commit a8b1defb9d
86 changed files with 3524 additions and 203 deletions
+7
View File
@@ -14,3 +14,10 @@ src-tauri/gen
/.audit /.audit
/plugin-packages/ /plugin-packages/
src-tauri/browser-engine/
output/browser-installer-build.log
output/browser-test.conf.json
# Local workspace settings and project data
/.runestone/
+37
View File
@@ -8,6 +8,43 @@ product plans in `docs/`, with links from the README.
Keep the roadmap visual and organized around goals, user outcomes, and milestones. Keep the roadmap visual and organized around goals, user outcomes, and milestones.
Keep detailed capability lists and design constraints in the product scope reference. Keep detailed capability lists and design constraints in the product scope reference.
## Kanban workflow
Move implementation-ready cards to Review after the relevant checks pass.
Reserve Done for the user's acceptance. Automated checks do not replace that review.
Keep unresolved work In progress. Do not start blocked cards or cards outside the requested scope.
## Versioning
Apply this policy to RuneStone and its plugins. Each project keeps its own version number.
Use `zz.yy.xx`. Keep routine implementation work in the current `zz.yy` series.
Increase `xx` once for each new completed build. The number has no two-digit limit.
Keep the current version during source edits, fixes, improvements, documentation work, and automated checks.
A build means a RuneStone installer or a plugin ZIP, unless the user requests another distributable.
Development servers, test runs, and intermediate compilation output do not count as new builds.
Set the next version when producing the build. Keep all version fields consistent.
If no build completes, restore the previous version fields. Failed attempts and retries do not consume version numbers.
Report a new version as available only after its build artifact exists.
Publishing an existing artifact does not increase its version.
Increase `yy` only for a deliberate release ready for build testing, with user direction. Reset `xx` to zero for that release.
Increase `zz` only for a full release, with user direction. Reset `yy` and `xx` to zero for that release.
Passing automated checks alone does not authorize a `yy` or `zz` increase.
Keep version fields consistent within each project. Do not increase versions for instruction-only edits.
Use lowercase letter suffixes for hotfix release labels, such as `0.2.11a` and `0.2.11b`.
Where packaging requires numeric versions, use letters in release labels or tags until that package format supports suffixes.
For those packages, increase `xx` for each changed hotfix build and record its numeric version in the release notes.
The current plugin contract requires numeric versions in `plugin.json`. Do not bypass its validator or overwrite an existing release ZIP.
See [versioning for plugin authors and agents](docs/plugins.md#versioning-for-plugin-authors-and-agents) for the package guidance.
## Windows installer
- Default to reinstall when RuneStone is already installed, including builds with the same version.
- Do not make users uninstall RuneStone before they can reinstall or update it.
- Preserve workspace files and user settings during reinstall and update.
- Keep the existing protection against version downgrades.
## Plugin packages ## Plugin packages
Use `docs/plugins.md` as the package and release reference for all plugin work. Use `docs/plugins.md` as the package and release reference for all plugin work.
+57
View File
@@ -0,0 +1,57 @@
# Completion plugin API
This source update adds `api.completion`, capability version 1. It is optional in package API version 1.
Plugins must feature-detect it. The existing 0.1.7 installer does not contain this source update.
## Register a field
```javascript
const completion = api.completion;
if (completion?.version === 1) {
const field = completion.registerInput(textarea, {
id: "draft",
kind: "prose",
sensitive: false
});
api.onDispose(() => field.dispose());
}
```
The host prefixes field IDs with the owning plugin ID and disposes registrations when the plugin stops. IDs must be unique per active owner.
Inputs and text areas use a preview below the field. Custom editors use `registerSurface` with snapshot, preview, and insert callbacks.
Snapshots include document identity, revision, caret, selection, focus, composition, sensitivity, read-only state, and prose or code kind.
The host validates the snapshot before acceptance. Custom insert callbacks must make one undoable transaction and reject stale expected text.
## Register a provider
`registerProvider` accepts an ID, delay, deadline, and an asynchronous completion function. Only one provider can be active in a window.
The function receives bounded prefix and suffix text, document and surface identity, language, mode, and an abort signal.
It can publish partial text through its callback and return the final insertion. No candidate enters the document before acceptance.
Call `invalidate()` when settings or reference context changes.
## Local transport
`transport(request, signal, onLine)` sends a bounded request through the desktop host. Each callback receives one response line.
Supported routes are `/v1/models`, `/v1/chat/completions`, `/api/tags`, and `/api/generate`.
Only explicit loopback addresses are allowed. Redirects and system proxies are disabled. Request bodies and responses have size limits.
The transport supports no remote credentials in this version. It is not a general HTTP API.
The host cancels display immediately. A blocked native read can continue until its bounded timeout.
## Current boundaries
Surface and provider APIs are available. Automatic context-source registration, remote adapters, and credential storage remain planned.
External plugins retain RuneStone's existing full-application trust level. This API does not add a permission sandbox.
See [the implementation](../src/lib/completion/contracts.ts), [host tests](../scripts/completion.spec.ts), and the [plugin trial guide](../../RuneStone_LocalModel/docs/trial-guide.md).
+18
View File
@@ -64,6 +64,8 @@ The interface uses Svelte 5, TypeScript, and Vite.
CodeMirror handles live Markdown editing, Monaco handles source editing, and xterm handles terminals. CodeMirror handles live Markdown editing, Monaco handles source editing, and xterm handles terminals.
Windows is the first target. The older WriterHost component remains unused. Windows is the first target. The older WriterHost component remains unused.
Use the [Linux readiness guide](linux.md) for Linux setup, native tests, and package checks.
See the setup steps below to install dependencies and run the desktop app. See the setup steps below to install dependencies and run the desktop app.
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints. See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md). Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md).
@@ -180,3 +182,19 @@ Read Rust errors in the terminal that runs `pnpm tauri dev`.
In the Windows development window, press Ctrl+Shift+I to open the web inspector. In the Windows development window, press Ctrl+Shift+I to open the web inspector.
Use its console for frontend errors. Use its console for frontend errors.
See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector). See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector).
## RuneStone 0.1.8: Settings windows and pasted Markdown
Desktop Settings opens in a separate movable window for each workspace window.
Repeated requests focus the existing Settings window.
Closing the workspace window also closes its Settings window.
Settings opened before a workspace closes when that workspace opens, so plugin context cannot remain stale.
Saved preferences synchronize across windows. The browser preview keeps the Settings dialog.
The separate window has dedicated native permissions and loads only the browser settings contribution.
Plugin installation still lists all installed plugins.
Live Markdown formatting refreshes when background parsing finishes after a large paste.
Run `scripts/markdownPaste.smoke.mjs` against the development server to check pasted source and rendered formatting.
Run `scripts/settingsWindow.smoke.mjs` to check the Settings layout, save synchronization, and mocked native requests.
The browser checks do not test native title-bar movement or desktop clipboard behavior.
+122
View File
@@ -0,0 +1,122 @@
# Linux readiness
[Developer guide](development.md) · [Release guide](releases.md)
Linux support is experimental. No native Linux build or desktop test is recorded yet.
Voice typing is outside the Linux acceptance criteria.
The first target is one known Linux desktop, with a local workspace and Bash.
## 1. Record the target
Run these commands on the Linux box:
```sh
cat /etc/os-release
uname -m
printf 'Desktop: %s\nSession: %s\n' "$XDG_CURRENT_DESKTOP" "$XDG_SESSION_TYPE"
```
Record the distribution, version, processor architecture, desktop, and session type with the test results.
Test the session you use first. Test both Wayland and X11 before claiming support for both.
An Intel/AMD build does not establish ARM support.
## 2. Prepare the Linux build environment
Install Node.js 24, pnpm 10, and stable Rust on the Linux box.
Use a separate Linux checkout. Do not copy Windows `node_modules` or `src-tauri/target` folders.
Install the system packages for your distribution from [Tauri's Linux prerequisites](https://v2.tauri.app/start/prerequisites/#linux).
For Ubuntu or Debian with WebKitGTK 4.1 available, use:
```sh
sudo apt update
sudo apt install build-essential pkg-config curl wget file \
libwebkit2gtk-4.1-dev libxdo-dev libssl-dev \
libayatana-appindicator3-dev librsvg2-dev
```
These commands are an Ubuntu/Debian example, not instructions for every Linux distribution.
The first Rust build and package build need internet access for dependencies and packaging tools.
## 3. Check the source and open the app
From the Linux checkout, install the project dependencies:
```sh
pnpm install --frozen-lockfile
```
The full test suite needs the Table formulas package.
Clone `RuneStone_TableFormulas` beside RuneStone and install its dependencies, as described in the [plugin guide](plugins.md).
Then run these checks from RuneStone:
```sh
pnpm build:plugins
pnpm check
pnpm test
pnpm build
cargo test --manifest-path src-tauri/Cargo.toml --lib --locked
```
Run the desktop app in your graphical Linux session:
```sh
pnpm tauri dev
```
A successful build does not establish desktop compatibility.
Browser tests use mocked desktop calls and Chromium. They do not test Linux file access or WebKitGTK behavior.
## 4. Complete the desktop checks
Use a disposable workspace outside the installation folder.
Record each result, the source commit, and any error message.
All checks below remain unverified on Linux.
| Area | Pass criteria |
| --- | --- |
| Launch and windows | Open from the desktop, move, resize, minimize, maximize, and close. Unsaved edits trigger the close guard. |
| Files and paths | Create, save, reopen, rename, copy, and delete files. Check spaces, Unicode, and distinct `Note.md` and `note.md` files. |
| External edits | Edit a file in another editor. RuneStone detects the change and prevents silent replacement of conflicting edits. |
| Editors | Edit Markdown, source code, tables, images, and diagrams. Check undo, keyboard shortcuts, and both themes. |
| Clipboard and dialogs | Copy and paste text, tables, and images. Check folder selection, external links, and file reveal. |
| Plugins | Install plugin ZIPs through Settings, enable them, restart, disable them, and remove them. Check plugin data persistence. |
| Terminal plugin | Install the Terminal ZIP. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
| Settings | Change preferences, restart, and confirm persistence. Check separate workspace windows. |
Install the Terminal package separately as described in the [plugin guide](plugins.md).
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
Current filename rules reject some names that Linux permits, including colons and backslashes.
Use ordinary portable filenames for the first trial. Record unsupported names as a limitation.
Mounted network shares need separate tests because Linux mount paths do not reliably select the current polling fallback.
Do not claim network workspace support from a local-disk test.
## 5. Build and test a package
After the desktop checks pass, build on Linux for the target processor architecture.
Choose the package format that matches the trial:
```sh
# Ubuntu or Debian
pnpm tauri build --bundles deb -- --locked
# AppImage trial
pnpm tauri build --bundles appimage -- --locked
```
Do not use `pnpm build:installer` on Linux. That command selects the Windows installer.
Packages appear under `src-tauri/target/release/bundle/deb/` or `src-tauri/target/release/bundle/appimage/`.
Install the Debian package with the distribution package manager, or make the AppImage executable and open it.
Test launch without development tools, same-version reinstall, upgrade, and removal on a separate test account.
Reinstall and upgrade must preserve settings and workspace files. Removal must preserve workspaces outside the installation folder.
For shared packages, build on the oldest distribution you intend to support that supplies WebKitGTK 4.1.
A package built on a newer system can require libraries unavailable on an older system.
An AppImage does not remove this compatibility limit.
See [Tauri's AppImage guidance](https://v2.tauri.app/distribute/appimage/) and [Debian packaging guidance](https://v2.tauri.app/distribute/debian/).
Call a distribution supported only after its native tests and package checks pass.
Repeat the automated checks on a Linux runner before each Linux release.
No Linux automation is configured yet. Add it when the build host and target distribution are known.
+77 -5
View File
@@ -61,7 +61,8 @@ A changed source requires a new review. Cancelling the review removes its tempor
Try the example with `pnpm package:plugin fixtures/plugins/workspace-overview`. Try the example with `pnpm package:plugin fixtures/plugins/workspace-overview`.
Install the resulting ZIP from `plugin-packages/`, then choose Install and enable. Install the resulting ZIP from `plugin-packages/`, then choose Install and enable.
Use the puzzle button in the main toolbar to run Show workspace overview or open the Workspace overview view. Use Open tab or view beside New tab to open Workspace overview.
Use Commands in the toolbar to run Show workspace overview.
## Uninstall with one confirmation ## Uninstall with one confirmation
@@ -163,6 +164,28 @@ The entry is one compiled `.js` or `.mjs` module. Bundle dependencies into it.
Relative module imports cannot resolve from its Blob URL. Read packaged assets through the API instead. Relative module imports cannot resolve from its Blob URL. Read packaged assets through the API instead.
Raw TypeScript, Svelte source, native libraries, plugin dependencies, and automatic updates are unsupported. Raw TypeScript, Svelte source, native libraries, plugin dependencies, and automatic updates are unsupported.
## Versioning for plugin authors and agents
Follow the shared [RuneStone versioning policy](../AGENTS.md#versioning). RuneStone and its plugins keep independent version numbers under this policy.
Use `zz.yy.xx` and keep routine implementation work in the current `zz.yy` series.
| Part | When to increase it |
| --- | --- |
| `xx` | Each new completed plugin ZIP build. The number has no two-digit limit. |
| `yy` | A deliberate release ready for build testing, with user direction. Reset `xx` to zero. |
| `zz` | A full release, with user direction. Reset `yy` and `xx` to zero. |
Keep the current version during source edits, fixes, improvements, documentation work, and automated checks.
Set the next version when producing the ZIP. Intermediate compilation output does not count as a new build.
If no build completes, restore the previous version fields. Failed attempts and retries do not consume version numbers.
Report a new version as available only after its ZIP exists. Publishing an existing artifact does not increase its version.
Passing automated checks alone does not authorize a `yy` or `zz` increase.
Use lowercase letters for hotfix release labels, such as `0.2.11a` and `0.2.11b`.
The current plugin packager and installer require numeric versions in `plugin.json`.
Until that contract supports suffixes, use letters only in release labels or tags.
Increase `xx` for each changed hotfix ZIP and record its numeric package version in the release notes.
Keep the package and manifest versions equal. Do not bypass the host validator or overwrite an existing release ZIP.
## Build and release a plugin ## Build and release a plugin
Use the same package contract for in-house and community plugins. Use the same package contract for in-house and community plugins.
@@ -190,7 +213,7 @@ Use Node.js 24 or later for the packaging command. The default output folder is
It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`. It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`.
It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder. It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder.
The output folder must be outside the input folder. The output folder must be outside the input folder.
The command replaces an existing ZIP with the same ID and version. Increase the version for each published release. The command can replace an existing ZIP with the same ID and version. Use the next build version and preserve existing ZIPs.
Repeated runs with unchanged input produce the same archive bytes. Repeated runs with unchanged input produce the same archive bytes.
The native installer checks the package again before installation. The native installer checks the package again before installation.
@@ -231,6 +254,8 @@ The same duplicate-ID, enable, removal, and cleanup rules apply to local and rem
### Release standard for plugin writers and agents ### Release standard for plugin writers and agents
Apply the [shared versioning rules](#versioning-for-plugin-authors-and-agents) before choosing a release version.
Use one plugin repository and one standard plugin ZIP per release for this trial. Use one plugin repository and one standard plugin ZIP per release for this trial.
Keep the package contract above. No repository manifest or special branch layout is required. Keep the package contract above. No repository manifest or special branch layout is required.
@@ -242,8 +267,8 @@ Keep the package contract above. No repository manifest or special branch layout
Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases. Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases.
Keep the manifest version and package version equal. Keep published release files unchanged. Keep the manifest version and package version equal. Keep published release files unchanged.
Increase the version before publishing different package contents as an ordinary release. Increase the version when building a new ZIP, before publication.
A prerelease can use the same numeric manifest version while the installer uses its explicit trial tag. Prerelease builds follow the same build counter. Each new ZIP gets the next numeric version and an explicit trial tag.
The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies. The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies.
Do not attach a source ZIP as the plugin package. Gitea's automatic source archives do not count as release attachments. Do not attach a source ZIP as the plugin package. Gitea's automatic source archives do not count as release attachments.
@@ -279,6 +304,9 @@ Run `node scripts/pluginInstall.smoke.mjs` against the development server for th
## Plugin API ## Plugin API
The current source adds an optional [completion API](completion.md) for local model providers and plugin-owned text fields.
This capability is not present in the existing 0.1.7 installer.
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function. The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
The runtime limits activation and each cleanup callback to five seconds. The runtime limits activation and each cleanup callback to five seconds.
A timeout reports an error and blocks successful cleanup until the app restarts. A timeout reports an error and blocks successful cleanup until the app restarts.
@@ -308,15 +336,24 @@ export function activate(api) {
| `api.id` | The installed plugin ID | | `api.id` | The installed plugin ID |
| `api.signal` | An abort signal triggered before shutdown | | `api.signal` | An abort signal triggered before shutdown |
| `contribute(key, value)` | Register a typed terminal or table formula contribution | | `contribute(key, value)` | Register a typed terminal or table formula contribution |
| `registerCommand({ id, title, run })` | Add a command to the toolbar's plugin menu | | `registerCommand({ id, title, run })` | Add a command to Commands in the toolbar |
| `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view |
| `registerView({ id, title, placement?, mount })` | Add a view in a dialog or the editor area | | `registerView({ id, title, placement?, mount })` | Add a view in a dialog or the editor area |
| `registerView({ settings: true, ... })` | Add a configuration page to Settings |
| `registerView({ launcher: false, ... })` | Keep a dynamic view out of the launch menu |
| `registerView({ navigation: true, icon?, ... })` | Add an icon button to the ribbon left of the navigation pane | | `registerView({ navigation: true, icon?, ... })` | Add an icon button to the ribbon left of the navigation pane |
| `registerDocumentType(type)` | Recognize document content, supply a navigation icon, and mount a document editor | | `registerDocumentType(type)` | Recognize document content, supply a navigation icon, and mount a document editor |
| `openDocument(path)` | Open a recognized document in its own tab | | `openDocument(path)` | Open a recognized document in its own tab |
| `renameDocument({ id, path }, name)` | Rename a recognized document and return its new workspace path. Optional API | | `renameDocument({ id, path }, name)` | Rename a recognized document and return its new workspace path. Optional API |
| `openView(id)` | Open one of the plugin's registered views | | `openView(id)` | Open one of the plugin's registered views |
| `openView(id, { split, relativeTo })` | Open an editor view beside another view. `split` accepts `right` or `down` |
| `closeView(id)` | Close an editor view owned by this plugin. Optional API |
| `registerView({ tabActions, find, pinned, ... })` | Supply tab actions, a Find handler, and the initial pin state |
| `registerView({ tabDragData, ... })` | Supply transfer data for a tab. The callback receives its pin state |
| `registerTabDrop(receive)` | Accept a tab from another window. Optional API |
| `onDispose(callback)` | Register synchronous or asynchronous cleanup | | `onDispose(callback)` | Register synchronous or asynchronous cleanup |
| `workspace.list(path?)` | List a directory in this window's active workspace | | `workspace.list(path?)` | List a directory in this window's active workspace |
| `workspace.listMarkdown()` | Return sorted visible Markdown paths in one native request. Optional API |
| `workspace.read(path)` | Read a workspace text file | | `workspace.read(path)` | Read a workspace text file |
| `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update | | `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update |
| `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 | | `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 |
@@ -324,9 +361,31 @@ export function activate(api) {
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text | | `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
| `workspace.subscribe(listener)` | Receive workspace change notifications. Returns a cleanup function | | `workspace.subscribe(listener)` | Receive workspace change notifications. Returns a cleanup function |
| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit | | `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit |
| `settings.subscribe(listener)` | Receive saved settings changes across windows. Optional API |
| `assets.read(path)` | Read package bytes as a `Uint8Array` | | `assets.read(path)` | Read package bytes as a `Uint8Array` |
Command and view IDs must be unique within their respective plugin collections. Command and view IDs must be unique within their respective plugin collections.
Plugin configuration appears in Settings under the plugin name.
Register a view with `settings: true` to add its configuration page.
The host mounts that view inside Settings and removes it from the launch menu.
Settings loads enabled plugins so their configuration pages remain available in the separate settings window.
The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`.
Older hosts can omit the context argument.
Local Autocomplete keeps temporary reference text in its editor view because that text belongs to one window.
Open Commands → Configure local autocomplete in that window to use reference text.
The Open tab or view menu contains plugin views and commands with `category: "open"`.
Other commands appear in Commands.
Set `launcher: false` on dynamic views that already have tabs.
Existing packages can omit these optional fields.
Plugins can call `settings.subscribe(listener)` to receive notifications when their saved settings change.
The listener must read the new settings with `settings.read()`.
Notifications cross window boundaries and contain only the plugin ID.
The host removes subscriptions when the plugin stops.
Plugins must ignore pending reads after shutdown and prevent older reads from replacing newer settings.
Local Autocomplete uses this subscription so changes in Settings apply to the editor window.
Document type IDs must also be unique within their collection. Document type IDs must also be unique within their collection.
Document types declare file extensions, an `identify` function, and a `mount` function. Document types declare file extensions, an `identify` function, and a `mount` function.
The identify function returns a stable document ID or null. Invalid documents remain available through the text editor. The identify function returns a stable document ID or null. Invalid documents remain available through the text editor.
@@ -388,3 +447,16 @@ Run `scripts/pluginInstall.smoke.mjs`, `scripts/plugins.smoke.mjs`, and `scripts
Native plugin packages and restricted permissions remain future work. Native plugin packages and restricted permissions remain future work.
The core keeps basic Markdown tables, file editing, selection, sorting, and document access when optional features stop. The core keeps basic Markdown tables, file editing, selection, sorting, and document access when optional features stop.
## Browser development plugin
Browser development lives in `../RuneStone_WebViewer/`.
Build `releases/runestone.browser-0.1.0.zip` there with `npm run build:plugin`.
The plugin opens editor tabs, contributes to Settings and Bookmarks, and handles web links when selected by the user.
A fresh browser store contains one User profile. Users can create blank profiles or duplicate an existing profile.
The browser requires the native browser service in this host revision.
Build and stage the runtime from its checkout, then include `src-tauri/tauri.browser.conf.json` when building RuneStone.
The runtime is an optional host resource, similar in purpose to the native service used by Terminal.
Plugin ZIP files still contain JavaScript and assets. They do not install arbitrary native executables.
See the browser checkout's README for build steps and current limits.
+2
View File
@@ -2,6 +2,8 @@
[Back to RuneStone](../README.md) [Back to RuneStone](../README.md)
For experimental Linux builds, use the [Linux readiness guide](linux.md).
## Build the Windows installer ## Build the Windows installer
Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source). Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source).
+1
View File
@@ -0,0 +1 @@
<!doctype html><html><head><meta charset="utf-8"><title>Autocomplete integration test</title></head><body style="background:#20242a;color:#eee;font:16px system-ui"><h1>Autocomplete integration test</h1><div id="writer"></div><div id="source" style="height:180px"></div><div id="plugin"></div><script type="module" src="/src/lib/completion/testHarness.ts"></script></body></html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "runestone", "name": "runestone",
"version": "0.1.7", "version": "0.1.10",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
+44
View File
@@ -0,0 +1,44 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry } from "../src/lib/plugins/registry.ts";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
test("browser contributions and view updates are revoked when the plugin stops", async () => {
const registry = new ContributionRegistry();
let api!: PluginApi;
let disposed = false;
const received: string[] = [];
const session = new ExternalSession("runestone.browser", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, registry);
await session.start({ activate(value) {
api = value;
api.registerView({ id: "tab-test", title: "Browser", placement: "editor", icon: "globe", mount: () => {} });
api.registerTabDrop!(data => { received.push(data); });
api.contribute("browser", { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => true });
api.onDispose(() => { disposed = true; });
} });
assert.ok(registry.get("browser"));
await session.dropTab("live-tab");
assert.deepEqual(received, ["live-tab"]);
api.updateViewTitle!("tab-test", "Example · User");
assert.equal(session.views.get("tab-test")?.title, "Example · User");
const icon = "data:image/png;base64,aW1hZ2U=";
api.updateViewIcon!("tab-test", icon);
assert.equal(session.views.get("tab-test")?.iconImage, icon);
assert.throws(() => api.updateViewIcon!("tab-test", "https://example.com/icon.png"), /Invalid/);
assert.throws(() => api.updateViewIcon!("tab-test", "data:text/html;base64,aW1hZ2U="), /Invalid/);
assert.throws(() => api.updateViewIcon!("tab-test", "data:image/png;base64," + "a".repeat(90_000)), /Invalid/);
api.updateViewIcon!("tab-test", null);
assert.equal(session.views.get("tab-test")?.iconImage, null);
await session.stop();
assert.equal(registry.get("browser"), undefined);
assert.equal(disposed, true);
assert.throws(() => api.updateViewTitle!("tab-test", "Other"), /disabled/);
assert.throws(() => api.updateViewIcon!("tab-test", icon), /disabled/);
await assert.rejects(session.dropTab("closed-tab"), /disabled/);
assert.throws(() => api.registerTabDrop!(() => {}), /disabled/);
assert.deepEqual(received, ["live-tab"]);
});
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { CompletionHub, eligible } from '../src/lib/completion/hub.ts';
import type { CompletionSnapshot } from '../src/lib/completion/contracts.ts';
const snapshot = (): CompletionSnapshot => ({ documentId: 'doc', revision: 1, text: 'The ', caret: 4, selectionEnd: 4, focused: true, kind: 'prose' });
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
test('sensitive fields, composition, selections, code blocks and link targets are excluded', () => {
assert(eligible(snapshot()));
for (const change of [{ sensitive: true }, { composing: true }, { readOnly: true }, { selectionEnd: 0 }, { focused: false }]) assert(!eligible({ ...snapshot(), ...change }));
for (const text of ['```js\nlet ', '[name](http', '| cell ', '`source', '---\nname: ']) assert(!eligible({ ...snapshot(), text, caret: text.length, selectionEnd: text.length }));
assert(eligible({ ...snapshot(), kind: 'code', text: 'let ', caret: 4 }));
});
test('a new revision blocks stale insertion even when the provider ignores cancellation', async () => {
const hub = new CompletionHub(); let state = snapshot(), emit!: (text: string) => void, finish!: (text: string) => void, visible = '', edits = 0;
hub.registerProvider({ id: 'model', complete: (_request, publish) => { emit = publish; return new Promise(resolve => finish = resolve); } });
const field = hub.registerSurface({ id: 'field', snapshot: () => state, preview: text => visible = text || '', insert: () => { edits++; return true; } });
field.request(); emit('harbor'); assert.equal(visible, 'harbor');
state = { ...state, revision: 2, text: 'The old ', caret: 8, selectionEnd: 8 };
assert.equal(field.accept(), false); finish('late'); await tick(); assert.equal(visible, ''); assert.equal(edits, 0); field.dispose();
});
test('acceptance is explicit and provider removal clears all surfaces', async () => {
const hub = new CompletionHub(); let visible = '', inserted = '';
const remove = hub.registerProvider({ id: 'model', complete: async () => 'quiet harbor' });
const field = hub.registerSurface({ id: 'field', snapshot, preview: text => visible = text || '', insert: text => { inserted = text; return true; } });
field.request(); await tick(); assert.equal(inserted, ''); assert.equal(visible, 'quiet harbor');
assert(field.accept(true)); assert.equal(inserted, 'quiet '); assert.equal(visible, '');
field.request(); await tick(); remove(); assert.equal(visible, ''); assert.equal(field.accept(), false); field.dispose();
});
test('moving between fields cancels the previous request', async () => {
const hub = new CompletionHub(); const signals: AbortSignal[] = [];
hub.registerProvider({ id: 'model', complete: request => { signals.push(request.signal); return new Promise(() => {}); } });
const a = hub.registerSurface({ id: 'a', snapshot, preview() {}, insert: () => true });
const b = hub.registerSurface({ id: 'b', snapshot, preview() {}, insert: () => true });
a.request(); b.request(); assert(signals[0].aborted); assert(!signals[1].aborted); a.dispose(); b.dispose();
});
+18
View File
@@ -11,6 +11,24 @@ function fixture() {
}, () => {}, () => {}); }, () => {}, () => {});
return { session, writes: () => writes }; return { session, writes: () => writes };
} }
test("native Markdown discovery remains optional and is revoked on disable", async () => {
let api!: PluginApi;
let scans = 0;
const session = new ExternalSession("org.test.scan", {
workspace: { list: async () => [], listMarkdown: async () => { scans++; return ["Notes/task.md"]; }, read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.deepEqual(await api.workspace.listMarkdown!(), ["Notes/task.md"]);
await session.stop();
assert.throws(() => api.workspace.listMarkdown!(), /disabled/);
assert.equal(scans, 1);
const old = fixture().session;
await old.start({ activate(value) { assert.equal(value.workspace.listMarkdown, undefined); } });
await old.stop();
});
test("external commands run and all host access stops before cleanup", async () => { test("external commands run and all host access stops before cleanup", async () => {
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0; const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
await session.start({ activate(value) { await session.start({ activate(value) {
+112
View File
@@ -0,0 +1,112 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.getByText("smoke-workspace", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click();
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
for (const count of [3, 1000, 5000]) {
const result = await page.evaluate(async count => {
const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js");
const view = window.__CM__;
const source = Array.from({ length: count }, (_, i) => "## Heading " + i + "\n\n**Bold** and *italic*\n\n").join("");
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } });
view.focus();
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", source);
view.contentDOM.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }));
view.dispatch({ selection: { anchor: 0 } });
const { forceParsing, syntaxTree } = await import("/node_modules/.vite/deps/@codemirror_language.js");
forceParsing(view, view.state.doc.length, 5000);
const nodes = [];
syntaxTree(view.state).iterate({ enter(node) { if (node.name === "StrongEmphasis") nodes.push(node.from); } });
const marks = [];
for (const set of view.state.facet(EditorView.decorations)) {
if (typeof set !== "function") set.between(0, view.state.doc.length, (from, to, decoration) => { if (decoration.spec.class === "writer-strong") marks.push(from); });
}
return { correctSource: view.state.sliceDoc() === source, nodes: nodes.length, marks: marks.length };
}, count);
console.log({ count, ...result });
assert.equal(result.correctSource, true);
assert.equal(result.nodes, count);
assert.equal(result.marks, count);
}
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+9 -1
View File
@@ -81,7 +81,15 @@ try {
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } }); await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
await file.waitFor(); await file.waitFor();
assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles"); assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles");
await dismiss(); assert.equal(await item("Show in Explorer").locator("svg.action-icon").count(), 1);
await page.keyboard.press("End");
assert.equal(await item("Show in Explorer").evaluate(node => node === document.activeElement), true);
await page.keyboard.press("Enter");
await file.waitFor({ state: "detached" });
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "", "Pane action opens the workspace root");
await row.click({ button: "right" });
await item("Show in Explorer").click();
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "a.md", "File action reveals the selected file");
await page.locator('[data-tree-rel="notes"]').click({ button: "right" }); await page.locator('[data-tree-rel="notes"]').click({ button: "right" });
assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles"); assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles");
await dismiss(); await dismiss();
+117
View File
@@ -0,0 +1,117 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
const errors = [];
await mkdir(".audit", { recursive: true });
await context.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("runestone.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
api.settings.subscribe?.(() => { window.accessTest.settings++; });
api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) {
window.accessTest.mounts++;
container.innerHTML = '<h2>Local Autocomplete</h2><label>Model<input aria-label="Model"></label><button>Save model</button><p class="mount-context"></p>';
container.querySelector('p').textContent = context?.surface;
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure local autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"runestone.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
"org.example.tasks": `export function activate(api) {
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', mount(container) { container.textContent = 'Task content'; } });
api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } });
}`,
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; }
if (command === 'workspace_last_path') return null;
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) };
if (command === 'plugins_load') return modules[args.id];
if (command === 'plugins_data') {
if (args.value !== null) { localStorage.setItem('settings:' + args.id, args.value); emit('plugin-settings-changed', args.id); }
return localStorage.getItem('settings:' + args.id) || 'null';
}
if (command === 'plugins_set_enabled') { if (!args.enabled) localStorage.setItem('disabled', 'true'); emit('plugins-changed', {}); return; }
if (command === 'plugins_release' || command === 'settings_open_window') return;
if (command.startsWith('plugin:window|')) return false;
throw new Error('Unhandled IPC: ' + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.addEventListener('storage', event => { if (event.key?.startsWith('settings:')) emit('plugin-settings-changed', event.key.slice(9)); if (event.key === 'disabled') emit('plugins-changed', {}); });
});
const main = await context.newPage(), settings = await context.newPage();
for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); }
try {
await main.goto(origin);
const open = main.getByRole('button', { name: 'Open tab or view', exact: true });
await open.click();
const menu = main.getByRole('menu', { name: 'Open tab or view', exact: true });
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem').count(), 3);
assert.equal(await menu.getByText('Local Autocomplete').count(), 0);
await open.click(); await menu.waitFor({ state: 'detached' });
await open.focus(); await main.keyboard.press('Enter'); await main.keyboard.press('End'); await main.keyboard.press('Escape');
assert(await open.evaluate(element => element === document.activeElement));
await open.click(); await menu.getByRole('menuitem', { name: /New browser tab/ }).click();
await main.getByText('Browser content', { exact: true }).waitFor();
await open.click(); assert.equal(await menu.getByRole('menuitem').count(), 3);
await menu.getByRole('menuitem', { name: /Task summary/ }).click();
await main.getByRole('dialog', { name: 'Task summary' }).waitFor();
await main.keyboard.press('Escape');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'light');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu-light.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'dark');
await main.getByRole('button', { name: 'Commands', exact: true }).click();
await main.getByRole('menuitem', { name: /Failed command/ }).click();
await main.getByRole('alert').filter({ hasText: 'Command failed for test' }).waitFor();
await main.getByRole('button', { name: 'Dismiss', exact: true }).click();
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click();
await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model');
assert.equal(await settings.locator('.mount-context').innerText(), 'settings');
await settings.waitForTimeout(5500);
assert.equal(await settings.getByRole('textbox', { name: 'Model', exact: true }).inputValue(), 'unsaved-model');
assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1);
await settings.getByRole('button', { name: 'Save model', exact: true }).click();
await main.waitForFunction(() => window.accessTest.settings === 1);
await settings.screenshot({ path: '.audit/plugin-access-settings.png' });
await settings.getByRole('button', { name: 'General', exact: true }).click();
await settings.waitForFunction(() => window.accessTest.disposed === 1);
await settings.getByRole('textbox', { name: 'Search settings' }).fill('Local');
await settings.getByRole('textbox', { name: 'Model', exact: true }).waitFor();
await settings.getByRole('textbox', { name: 'Search settings' }).fill('');
await settings.getByRole('button', { name: 'Plug-ins', exact: true }).click();
await settings.getByRole('switch', { name: 'Local Autocomplete', exact: true }).uncheck();
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' });
await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' });
assert.deepEqual(errors, []);
console.log('Plugin access smoke passed: launchers, dynamic tabs, keyboard focus, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
} catch (error) {
await settings.screenshot({ path: '.audit/plugin-access-failure.png' });
console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors);
throw error;
} finally { await browser.close(); }
+75
View File
@@ -0,0 +1,75 @@
import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { pluginAccess } from "../src/lib/plugins/access.ts";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi, PluginCommand, PluginView } from "../src/lib/plugins/sdk.ts";
const view = (id: string, extra: Partial<PluginView> = {}): PluginView => ({ id, title: id, mount() {}, ...extra });
const command = (id: string, extra: Partial<PluginCommand> = {}): PluginCommand => ({ id, title: id, run() {}, ...extra });
test("plugin access separates settings, launchers, and commands without reading titles", () => {
const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]);
assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]);
});
test("installed RuneStone packages retain access before their next package update", () => {
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings");
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]);
assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands");
});
test("settings listeners are removable and revoked before plugin cleanup", async () => {
let api!: PluginApi, notify!: () => void;
let received = 0, disposed = 0;
const session = new ExternalSession("org.example.settings", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() },
settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
const off = api.settings.subscribe!(() => { received++; });
notify(); assert.equal(received, 1);
await off(); await off(); assert.equal(disposed, 1);
api.settings.subscribe!(() => { received++; });
await session.stop(); notify();
assert.equal(received, 1); assert.equal(disposed, 2);
assert.throws(() => api.settings.subscribe!(() => {}), /disabled/);
});
test("invalid access metadata fails registration", async () => {
for (const activate of [
(api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })),
(api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })),
(api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })),
]) {
const session = new ExternalSession("org.example.invalid", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await assert.rejects(session.start({ activate }), /category|boolean/);
await session.stop();
}
});
test("settings windows permit model checks and cancellation", () => {
const capability = JSON.parse(readFileSync(new URL("../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission));
});
test("view mount context distinguishes Settings from editor and dialog views", async () => {
const surfaces: string[] = [];
const session = new ExternalSession("org.example.context", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
}, () => {}, () => {});
await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } });
const target = { replaceChildren() {} } as unknown as HTMLElement;
const disposeView = await session.mount("settings", target);
await disposeView();
const disposeSettings = await session.mount("settings", target, undefined, "settings");
await disposeSettings(); await session.stop();
assert.deepEqual(surfaces, ["view", "settings"]);
});
+21 -12
View File
@@ -7,10 +7,15 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' });
const page = await context.newPage(); const page = await context.newPage();
const settingsPage = await context.newPage();
settingsPage.setDefaultTimeout(10000);
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
page.setDefaultTimeout(10000); page.setDefaultTimeout(10000);
const errors = []; const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message)); page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8')); const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8'));
const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n'; const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n';
await page.context().addInitScript(({ manifest, pluginCode }) => { await page.context().addInitScript(({ manifest, pluginCode }) => {
@@ -38,7 +43,10 @@ await page.context().addInitScript(({ manifest, pluginCode }) => {
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id), unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => { invoke: async (command, args = {}) => {
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
return window.settingsHostInvoke(command, args);
calls.push({ command, args }); calls.push({ command, args });
if (command === "settings_open_window") return;
if (command === "plugin:window|is_maximized") return false; if (command === "plugin:window|is_maximized") return false;
if (command.startsWith("plugin:window|")) return null; if (command.startsWith("plugin:window|")) return null;
if (command === "plugins_snapshot") return snapshot(); if (command === "plugins_snapshot") return snapshot();
@@ -117,10 +125,11 @@ async function quickOpen(name) {
} }
const settingsDialog = page.getByRole('dialog', { name: 'Settings', exact: true }); const settingsDialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
async function settings() { async function settings() {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
} }
async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); } async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); }
@@ -131,13 +140,13 @@ try {
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0); assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0);
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0); assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0);
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click(); await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true }); let review = settingsPage.getByRole('dialog', { name: 'Review plugin installation', exact: true });
await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor(); await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor();
await review.getByRole('button', { name: 'Cancel', exact: true }).click(); await review.getByRole('button', { name: 'Cancel', exact: true }).click();
assert.equal(await count('plugins_install'), 0); assert.equal(await count('plugins_install'), 0);
const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true }); const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true });
await gitButton.click(); await gitButton.click();
const gitDialog = page.getByRole('dialog', { name: 'Install from Git link', exact: true }); const gitDialog = settingsPage.getByRole('dialog', { name: 'Install from Git link', exact: true });
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git'); await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing'); await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing');
await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token'); await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token');
@@ -156,8 +165,8 @@ try {
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z'); assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z');
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/); assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await page.screenshot({ path: '.audit/plugin-manager-installed.png' }); await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' });
await page.keyboard.press('Escape'); await settingsPage.keyboard.press('Escape');
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click(); await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
await page.getByRole('button', { name: /Show workspace overview/ }).click(); await page.getByRole('button', { name: /Show workspace overview/ }).click();
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true }); const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
@@ -165,7 +174,7 @@ try {
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click(); await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
await settings(); await settings();
await uninstall(); await uninstall();
const confirmation = page.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true }); const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true });
assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement)); assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement));
assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0); assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0);
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click(); await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click();
@@ -173,27 +182,27 @@ try {
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
await uninstall(); await uninstall();
await confirmation.waitFor(); await confirmation.waitFor();
await page.keyboard.press('Escape'); await settingsPage.keyboard.press('Escape');
assert(await settingsDialog.isVisible()); assert(await settingsDialog.isVisible());
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
assert.equal(await count('plugins_remove'), 0); assert.equal(await count('plugins_remove'), 0);
await uninstall(); await uninstall();
await confirmation.waitFor(); await confirmation.waitFor();
await page.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' }); await settingsPage.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor(); await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor();
assert.equal(await count('plugins_remove'), 1); assert.equal(await count('plugins_remove'), 1);
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true); assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true); assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
await page.keyboard.press('Escape'); await settingsPage.keyboard.press('Escape');
assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0); assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0);
await page.setViewportSize({ width: 590, height: 820 }); await settingsPage.setViewportSize({ width: 590, height: 820 });
await settings(); await settings();
await page.screenshot({ path: '.audit/plugin-manager-narrow.png' }); await settingsPage.screenshot({ path: '.audit/plugin-manager-narrow.png' });
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false); assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitButton.click(); await gitButton.click();
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git'); await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
await page.screenshot({ path: '.audit/plugin-git-narrow.png' }); await settingsPage.screenshot({ path: '.audit/plugin-git-narrow.png' });
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false); assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click(); await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
await review.getByRole('button', { name: 'Install', exact: true }).click(); await review.getByRole('button', { name: 'Install', exact: true }).click();
+255
View File
@@ -0,0 +1,255 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
const page = await context.newPage();
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const pluginCode = `export function activate(api) {
window.tabTest.api = api;
const mount = (id, container) => {
window.tabTest.mounts[id] = (window.tabTest.mounts[id] || 0) + 1;
const input = document.createElement("input");
input.setAttribute("aria-label", id + " state");
container.append(input);
return () => {
window.tabTest.disposals[id] = (window.tabTest.disposals[id] || 0) + 1;
input.remove();
};
};
for (const [id, title, icon] of [["overview", "Overview", "puzzle"], ["browser", "Browser", "globe"]]) {
api.registerView({ id, title, icon, placement: "editor", navigation: true, mount: container => mount(id, container) });
}
api.registerDocumentType({
id: "board", title: "Board", icon: "kanban", extensions: ["board"],
identify: (path, source) => ({ id: source }),
mount: (container, document) => mount(document.id, container),
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 }));
const root = "C:\\plugin-tab-workspace";
const files = new Map(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
files.set("project.board", "project-board");
const callbacks = new Map(), listeners = new Map();
let sequence = 0, enabled = true;
const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, files };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
return window.settingsHostInvoke(command, args);
if (command === "settings_open_window") return;
if (command === "plugin:event|listen") {
const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "plugin:window|is_maximized") return false;
if (command.startsWith("plugin:window|")) return;
if (command === "plugins_snapshot") return { root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
if (command === "plugins_set_enabled") { enabled = args.enabled; emit("plugins-changed"); return; }
if (command === "workspace_last_path") return location.search.includes("no-workspace") ? null : root;
if (command === "workspace_open") return { root, name: "plugin-tab-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") { window.tabTest.prompts++; return window.tabTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
}, { pluginCode });
const tab = name => page.getByRole("tab", { name, exact: true });
const bar = page.getByRole("tablist", { name: "Working tabs" });
const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function openFile(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await settle();
}
async function openView(name) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click();
await tab(name).waitFor();
}
async function drag(from, to, side = "before", cancel) {
const source = await tab(from).boundingBox(), target = await tab(to).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
if (cancel === "escape") await page.keyboard.press("Escape");
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
await page.mouse.up();
await settle();
}
async function menu(name) {
await tab(name).click({ button: "right" });
await page.getByRole("menu", { name: "Tab actions" }).waitFor();
}
try {
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
await page.goto(url);
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
await openFile("a.md");
await openFile("b.md");
await openView("Overview");
await page.getByRole("textbox", { name: "overview state" }).fill("Keep this state");
await openView("Browser");
const siteIcon = "data:image/svg+xml;base64," + Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="3" fill="#e35336"/></svg>').toString('base64');
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
await tab("Browser").locator("img.tab-icon").waitFor();
await page.waitForFunction(() => document.querySelector('.header img.tab-icon')?.naturalWidth === 16);
assert.equal(await tab("Browser").locator("img").getAttribute("alt"), "");
assert.equal(await tab("Browser").locator("img").getAttribute("draggable"), "false");
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await mkdir("output", { recursive: true });
await page.locator(".header").screenshot({ path: `output/tab-site-icon-${theme}.png` });
}
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", "data:image/png;base64,aW1hZ2U="));
await tab("Browser").locator("img").waitFor({ state: "detached" });
assert.equal(await tab("Browser").locator("svg").count(), 1);
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
await tab("Browser").locator("img").waitFor();
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", null));
await tab("Browser").locator("img").waitFor({ state: "detached" });
assert.equal(await tab("Browser").locator("svg").count(), 1);
console.log("PASS: site icons appear in both themes and missing or broken icons use the fallback");
await openFile("project.board");
await tab("project").waitFor();
assert.equal(await page.locator(".header").getByRole("tablist").count(), 1);
assert.deepEqual(await order(), ["a.md", "b.md", "Overview", "Browser", "project"]);
await drag("Overview", "a.md");
await drag("project", "b.md");
await drag("a.md", "Browser", "after");
const mixed = ["Overview", "project", "b.md", "Browser", "a.md"];
assert.deepEqual(await order(), mixed);
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
for (const cancel of ["escape", "outside"]) {
await drag("Browser", "Overview", "before", cancel);
assert.deepEqual(await order(), mixed);
}
await tab("Browser").press("Alt+Shift+Home");
assert.equal((await order())[0], "Browser");
await tab("Browser").press("ArrowRight");
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
assert.equal(await page.getByRole("textbox", { name: "overview state" }).inputValue(), "Keep this state");
await tab("Overview").press("ArrowRight");
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
await page.evaluate(() => window.tabTest.api.updateViewTitle("browser", "Browser page"));
await tab("Browser page").waitFor();
assert.equal((await order())[0], "Browser page");
assert.deepEqual(await page.evaluate(() => window.tabTest.mounts), { overview: 1, browser: 1, "project-board": 1 });
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), {});
assert.equal(await tab("project").getAttribute("aria-controls"), await page.getByRole("tabpanel", { name: "project" }).getAttribute("id"));
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await menu("Browser page");
assert.equal(await page.getByRole("menuitem", { name: "Pin", exact: true }).count(), 1);
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
await page.getByRole("menuitem", { name: "Move tab right", exact: true }).click();
}
console.log("PASS: mixed file, feature, and plugin document tabs move without remounting or changing selection");
await tab("Browser page").press("Alt+Shift+End");
await tab("project").press("Alt+Shift+End");
await tab("a.md").press("Alt+Shift+Home");
await tab("Overview").press("Alt+Shift+Home");
await tab("b.md").press("Alt+Shift+Home");
await menu("b.md");
await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
await tab("a.md").click();
await page.locator(".cm-content").fill("Unsaved text");
await tab("a.md •").waitFor();
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
await menu("Overview");
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
await page.waitForFunction(() => window.tabTest.prompts === 1);
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
await page.evaluate(() => window.tabTest.answer = "Ok");
await menu("Overview");
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
await tab("project").waitFor({ state: "detached" });
assert.deepEqual(await order(), ["b.md", "Overview"]);
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
await menu("Overview");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
await tab("Overview").waitFor({ state: "detached" });
assert.deepEqual(await order(), ["b.md"]);
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), { browser: 1, "project-board": 1, overview: 1 });
console.log("PASS: mixed close actions follow visual order, preserve pins, and respect cancelled discards");
await openView("Overview");
for (let index = 0; index < 14; index++) await openFile(`note-${index}.md`);
await tab("Overview").press("Alt+Shift+Home");
const source = await tab("Overview").boundingBox(), bounds = await bar.boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 });
await page.waitForFunction(() => {
const bar = document.querySelector('[aria-label="Working tabs"]');
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
});
await page.mouse.up();
await settle();
assert.equal((await order()).at(-1), "Overview");
await page.keyboard.press("Control+t");
await tab("New tab").press("Alt+Shift+Home");
await openFile("c.md");
assert.equal((await order())[0], "c.md");
const fileOrder = (await order()).filter(name => name !== "Overview");
await page.keyboard.press("Control+,");
const settingsPage = await context.newPage();
settingsPage.on("pageerror", error => errors.push(error.message));
await settingsPage.goto(url + '/?settingsWindow=true');
await settingsPage.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settingsPage.getByRole("switch", { name: "Tab fixtures", exact: true }).click();
await settingsPage.waitForFunction(() => document.getElementById("external-test.tabs")?.checked === false);
await tab("Overview").waitFor({ state: "detached" });
assert.deepEqual(await order(), fileOrder);
console.log("PASS: plugin drag auto-scroll, empty-tab replacement, and plugin disable preserve the mixed order");
await settingsPage.close();
await page.goto(`${url}?no-workspace`);
await openView("Overview");
await openView("Browser");
await drag("Browser", "Overview");
assert.deepEqual(await order(), ["Browser", "Overview"]);
await page.setViewportSize({ width: 880, height: 700 });
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/plugin-tab-order.png" });
await tab("Browser").click({ button: "middle" });
assert.deepEqual(await order(), ["Overview"]);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
assert.equal(await page.getByRole("tab").count(), 0);
assert.deepEqual(errors, []);
console.log("PASS: plugin tabs reorder and close without an open workspace");
} catch (error) {
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/plugin-tab-order-failure.png" });
console.error("Browser errors:", errors);
throw error;
} finally {
await browser.close();
}
+16 -8
View File
@@ -6,11 +6,15 @@ const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Closed settings</title>' }));
const page = await context.newPage(); const page = await context.newPage();
const settingsPage = await context.newPage();
page.setDefaultTimeout(10000); page.setDefaultTimeout(10000);
settingsPage.setDefaultTimeout(10000);
const errors = []; const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message)); page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
await page.context().addInitScript(() => { await page.context().addInitScript(() => {
window.isTauri = true; window.isTauri = true;
const root = "C:\\smoke-workspace"; const root = "C:\\smoke-workspace";
@@ -32,6 +36,7 @@ await page.context().addInitScript(() => {
unregisterCallback: id => callbacks.delete(id), unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => { invoke: async (command, args = {}) => {
calls.push({ command, args }); calls.push({ command, args });
if (command === "settings_open_window") return;
if (command === "plugin:event|listen") { if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
} }
@@ -83,16 +88,17 @@ async function quickOpen(name) {
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n'; const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table'); const table = page.locator('.live-writer table');
const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }); const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
const switchFor = name => dialog.getByRole('switch', { name, exact: true }); const switchFor = name => dialog.getByRole('switch', { name, exact: true });
async function settings() { async function settings() {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
} }
async function closeSettings() { async function closeSettings() {
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await page.keyboard.press('Escape'); await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/__settings-closed');
await dialog.waitFor({ state: 'hidden' }); await page.bringToFront();
} }
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
try { try {
@@ -137,7 +143,7 @@ try {
await settings(); await settings();
await switchFor('Terminal').uncheck(); await switchFor('Terminal').uncheck();
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close')); await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
await page.screenshot({ path: '.audit/plugins-settings.png' }); await settingsPage.screenshot({ path: '.audit/plugins-settings.png' });
await closeSettings(); await closeSettings();
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
const opened = await count('pty_open'); const opened = await count('pty_open');
@@ -169,9 +175,9 @@ try {
await settings(); await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0); assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
for (const name of ['Terminal', 'Table formulas']) { for (const name of ['Terminal', 'Table formulas']) {
await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await dialog.locator('.card').filter({ has: page.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click(); await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true }); const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
await confirmation.waitFor({ state: 'hidden' }); await confirmation.waitFor({ state: 'hidden' });
await switchFor(name).waitFor({ state: 'detached' }); await switchFor(name).waitFor({ state: 'detached' });
@@ -187,6 +193,8 @@ try {
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.'); console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
} catch (error) { } catch (error) {
await settingsPage.screenshot({ path: ".audit/plugins-settings-failure.png" });
console.log("Settings page:", settingsPage.url(), await settingsPage.locator('body').innerText());
await page.screenshot({ path: ".audit/plugins-failure.png" }); await page.screenshot({ path: ".audit/plugins-failure.png" });
console.log(await page.locator('.md-page').allTextContents()); console.log(await page.locator('.md-page').allTextContents());
console.log(errors); console.log(errors);
+39 -29
View File
@@ -9,8 +9,10 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } }); const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
const page = await context.newPage(); const page = await context.newPage();
const settingsPage = await context.newPage();
const errors = []; const errors = [];
page.on("pageerror", error => errors.push(error.message)); page.on("pageerror", error => errors.push(error.message));
settingsPage.on("pageerror", error => errors.push(error.message));
await context.addInitScript(() => { await context.addInitScript(() => {
window.isTauri = true; window.isTauri = true;
const disk = { "note.txt": "Original note" }; const disk = { "note.txt": "Original note" };
@@ -32,8 +34,18 @@ await context.addInitScript(() => {
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}); });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const settings = page.getByRole("dialog", { name: "Settings", exact: true }); const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }); const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
async function showSettings(shortcut = false) {
if (shortcut) await page.keyboard.press("Control+,");
else await trigger.click();
await settingsPage.goto(`${url}/?settingsWindow=true`);
await settings.waitFor();
}
async function closeSettings() {
await settingsPage.goto("about:blank");
await page.bringToFront();
}
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" }); const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true }); const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
async function changeSeconds(value) { async function changeSeconds(value) {
@@ -51,15 +63,14 @@ try {
await page.clock.install(); await page.clock.install();
await page.goto(url); await page.goto(url);
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor(); await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
await trigger.click(); await showSettings();
assert.equal(await interval.inputValue(), "5"); assert.equal(await interval.inputValue(), "5");
assert(await enabled.isChecked()); assert(await enabled.isChecked());
await changeSeconds(2); await changeSeconds(2);
await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor(); await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor();
await page.keyboard.press("Escape"); await closeSettings();
assert(await trigger.evaluate(element => element === document.activeElement), "Closing restores focus");
await page.reload(); await page.reload();
await trigger.click(); await showSettings();
assert.equal(await interval.inputValue(), "2", "Interval survives reload"); assert.equal(await interval.inputValue(), "2", "Interval survives reload");
await changeSeconds(0); await changeSeconds(0);
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor(); await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
@@ -71,17 +82,17 @@ try {
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting"); await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
await settings.getByText("No settings found", { exact: true }).waitFor(); await settings.getByText("No settings found", { exact: true }).waitFor();
await settings.getByRole("button", { name: "Clear search" }).click(); await settings.getByRole("button", { name: "Clear search" }).click();
await page.screenshot({ path: ".audit/settings-general.png" }); await settingsPage.screenshot({ path: ".audit/settings-general.png" });
await page.keyboard.press("Escape"); await closeSettings();
await page.keyboard.press("Control+p"); await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt"); await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click(); await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
await page.locator(".monaco-editor textarea").waitFor(); await page.locator(".monaco-editor textarea").waitFor();
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000)); await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
await trigger.click(); await showSettings();
await changeSeconds(3); await changeSeconds(3);
await page.keyboard.press("Escape"); await closeSettings();
await edit("Saved at three seconds"); await edit("Saved at three seconds");
const before = await writes(); const before = await writes();
await page.clock.runFor(2100); await page.clock.runFor(2100);
@@ -90,53 +101,52 @@ try {
assert.equal(await writes(), before + 1, "New interval saves the dirty buffer"); assert.equal(await writes(), before + 1, "New interval saves the dirty buffer");
await page.clock.runFor(3100); await page.clock.runFor(3100);
assert.equal(await writes(), before + 1, "Clean files are not rewritten"); assert.equal(await writes(), before + 1, "Clean files are not rewritten");
await trigger.click(); await showSettings();
await enabled.uncheck(); await enabled.uncheck();
assert(await interval.isDisabled()); assert(await interval.isDisabled());
await page.keyboard.press("Escape"); await closeSettings();
await edit("Manual save while auto-save is disabled"); await edit("Manual save while auto-save is disabled");
await page.clock.runFor(10000); await page.clock.runFor(10000);
assert.equal(await writes(), before + 1); assert.equal(await writes(), before + 1);
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2); await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2);
await page.locator(".monaco-editor textarea").focus(); await page.locator(".monaco-editor textarea").focus();
await page.keyboard.press("Control+,"); await showSettings(true);
await settings.waitFor(); await settings.waitFor();
await page.keyboard.press("Escape"); await closeSettings();
await page.locator(".monaco-editor textarea").focus(); await page.locator(".monaco-editor textarea").focus();
await page.keyboard.press("F1"); await page.keyboard.press("F1");
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor(); await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
const other = await context.newPage(); const other = await context.newPage();
await other.goto(url); await other.goto(`${url}/?settingsWindow=true`);
await other.getByRole("button", { name: "Settings (Ctrl+,)" }).click();
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3"); assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false); assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
await other.getByRole("button", { name: "Restore defaults" }).click(); await other.getByRole("button", { name: "Restore defaults" }).click();
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled); await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled);
await trigger.click(); await showSettings();
await enabled.waitFor(); await enabled.waitFor();
assert(await enabled.isChecked(), "Other windows receive changes"); assert(await enabled.isChecked(), "Other windows receive changes");
assert.equal(await interval.inputValue(), "5"); assert.equal(await interval.inputValue(), "5");
await page.keyboard.press("Escape"); await closeSettings();
await edit("Auto-save enabled from another window"); await edit("Auto-save enabled from another window");
await page.clock.runFor(5100); await page.clock.runFor(5100);
assert.equal(await writes(), before + 3); assert.equal(await writes(), before + 3);
await other.close(); await other.close();
await trigger.click(); await showSettings();
await page.evaluate(() => { await settingsPage.evaluate(() => {
window.__SET_ITEM__ = Storage.prototype.setItem; window.__SET_ITEM__ = Storage.prototype.setItem;
Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); }; Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); };
}); });
await changeSeconds(7); await changeSeconds(7);
await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor(); await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor();
await page.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; }); await settingsPage.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; });
await page.keyboard.press("Escape"); await closeSettings();
await trigger.click(); await showSettings();
assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings"); assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings");
await page.keyboard.press("Escape"); await closeSettings();
await page.getByRole("button", { name: "Help and about (F1)" }).click(); await page.getByRole("button", { name: "Help and about (F1)" }).click();
const help = page.getByRole("dialog", { name: "Help and about", exact: true }); const help = page.getByRole("dialog", { name: "Help and about", exact: true });
@@ -145,19 +155,19 @@ try {
await page.screenshot({ path: ".audit/settings-help.png" }); await page.screenshot({ path: ".audit/settings-help.png" });
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await page.keyboard.press("Control+b"); await page.keyboard.press("Control+b");
await page.keyboard.press("Control+,"); await showSettings(true);
await settings.waitFor(); await settings.waitFor();
await page.keyboard.press("Escape"); await closeSettings();
await page.keyboard.press("F1"); await page.keyboard.press("F1");
await help.waitFor(); await help.waitFor();
await page.keyboard.press("Escape"); await page.keyboard.press("Escape");
await page.setViewportSize({ width: 420, height: 650 }); await settingsPage.setViewportSize({ width: 540, height: 420 });
await page.keyboard.press("Control+,"); await showSettings(true);
await settings.waitFor(); await settings.waitFor();
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits"); assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
await page.screenshot({ path: ".audit/settings-narrow.png" }); await settingsPage.screenshot({ path: ".audit/settings-narrow.png" });
for (let i = 0; i < 12; i++) { for (let i = 0; i < 12; i++) {
await page.keyboard.press("Tab"); await settingsPage.keyboard.press("Tab");
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal"); assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
} }
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
+91
View File
@@ -0,0 +1,91 @@
// Run against pnpm dev. Native IPC is mocked; this does not test the operating system title bar.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
const watch = page => page.on("pageerror", error => errors.push(error.message));
try {
const main = await context.newPage(); watch(main);
await main.goto(origin);
await main.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
assert.equal(await main.locator("dialog:modal").count(), 1, "Browser preview retains the settings dialog");
const settings = await context.newPage(); watch(settings);
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
assert.equal(await settings.locator(".workbench").count(), 0);
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
await interval.fill("17"); await interval.press("Tab");
await main.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "17");
await main.getByRole("spinbutton", { name: "Auto-save interval" }).fill("29");
await main.getByRole("spinbutton", { name: "Auto-save interval" }).press("Tab");
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
await settings.reload();
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
await interval.fill("301"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Choose a whole number" }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
await settings.evaluate(() => { Storage.prototype.setItem = () => { throw new Error("Storage full"); }; });
await interval.fill("40"); await interval.press("Tab");
await settings.getByRole("alert").filter({ hasText: "Could not save these settings" }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
await settings.reload();
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("heading", { name: "Plug-ins", exact: true }).waitFor();
await settings.getByRole("button", { name: "General", exact: true }).click();
await mkdir(".audit", { recursive: true });
await settings.screenshot({ path: ".audit/settings-window.png" });
await settings.setViewportSize({ width: 540, height: 420 });
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
await settings.keyboard.press("Escape");
await settings.waitForURL(`${origin}/`);
const desktop = await context.newPage(); watch(desktop);
await desktop.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map();
let sequence = 0;
window.settingsTest = { opens: 0, fail: false, closes: 0 };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "settings_open_window") {
window.settingsTest.opens++;
if (window.settingsTest.fail) throw new Error("Native window creation failed");
await new Promise(resolve => setTimeout(resolve, 150));
return;
}
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|close") { window.settingsTest.closes++; return; }
throw new Error(`Unexpected IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
await desktop.goto(origin);
await desktop.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).dblclick();
assert.equal(await desktop.evaluate(() => window.settingsTest.opens), 1, "Rapid requests share the pending native open");
assert.equal(await desktop.locator("dialog:modal").count(), 0, "Native open does not block the workbench");
await desktop.waitForTimeout(180);
await desktop.keyboard.press("Control+,");
await desktop.waitForFunction(() => window.settingsTest.opens === 2);
await desktop.waitForTimeout(180);
await desktop.evaluate(() => { window.settingsTest.fail = true; });
await desktop.keyboard.press("Control+,");
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
await desktop.goto(`${origin}/?settingsWindow=true`);
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
await desktop.getByRole("button", { name: "Close settings", exact: true }).click();
assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1);
assert.deepEqual(errors, []);
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
} finally { await browser.close(); }
+18
View File
@@ -0,0 +1,18 @@
import test from "node:test";
import assert from "node:assert/strict";
import { splitPane, removePane, paneBounds, containsPane } from "../src/lib/workspace/splitLayout.ts";
test("nested splits preserve the source and divide the requested pane", () => {
const right = splitPane("a", "a", "b", "right");
const nested = splitPane(right, "b", "c", "down");
assert.deepEqual(paneBounds(nested), {
a: { left: 0, top: 0, width: 50, height: 100 },
b: { left: 50, top: 0, width: 50, height: 50 },
c: { left: 50, top: 50, width: 50, height: 50 },
});
assert.equal(containsPane(nested, "c"), true);
const closed = removePane(nested, "b")!;
assert.deepEqual(paneBounds(closed).c, { left: 50, top: 0, width: 50, height: 100 });
assert.equal(removePane(closed, "a"), "c");
assert.equal(removePane("c", "c"), null);
});
+3 -3
View File
@@ -34,7 +34,7 @@ await page.addInitScript(() => {
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}); });
const tab = name => page.getByRole("tab", { name, exact: true }); const tab = name => page.getByRole("tab", { name, exact: true });
const order = () => page.getByRole("tablist", { name: "Open files" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)); const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function open(name) { async function open(name) {
await page.keyboard.press("Control+p"); await page.keyboard.press("Control+p");
@@ -100,7 +100,7 @@ try {
console.log("PASS: empty tabs and middle-click close after reorder"); console.log("PASS: empty tabs and middle-click close after reorder");
for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`); for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`);
const bar = page.getByRole("tablist", { name: "Open files" }); const bar = page.getByRole("tablist", { name: "Working tabs" });
assert.ok(await bar.evaluate(node => node.scrollLeft > 0)); assert.ok(await bar.evaluate(node => node.scrollLeft > 0));
await tab("note-15.md").press("Alt+Shift+Home"); await tab("note-15.md").press("Alt+Shift+Home");
assert.equal((await order())[0], "note-15.md"); assert.equal((await order())[0], "note-15.md");
@@ -111,7 +111,7 @@ try {
await page.mouse.down(); await page.mouse.down();
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 }); await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 });
await page.waitForFunction(() => { await page.waitForFunction(() => {
const bar = document.querySelector('[aria-label="Open files"]'); const bar = document.querySelector('[aria-label="Working tabs"]');
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2; return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
}); });
await page.mouse.up(); await page.mouse.up();
+38
View File
@@ -0,0 +1,38 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { orderWorkbenchTabs } from "../src/lib/workspace/workbenchTabs.ts";
import { tabsToClose } from "../src/lib/workspace/tabActions.ts";
import { Documents } from "../src/lib/workspace/documents.ts";
test("mixed tabs retain their positions through title changes, closes, and new tabs", () => {
const tabs = [
{ id: "a", relPath: "a.md", name: "a.md", pinned: true },
{ id: "b", relPath: "renamed.md", name: "renamed.md" },
{ id: "plugin-a", relPath: "plugin:a", name: "New page title" },
{ id: "plugin-b", relPath: "plugin:b", name: "Board" },
];
const ordered = orderWorkbenchTabs(tabs, ["plugin-a", "b", "a", "closed", "plugin-a"]);
assert.deepEqual(ordered.map(tab => tab.id), ["plugin-a", "b", "a", "plugin-b"]);
assert.equal(ordered[0].name, "New page title");
assert.deepEqual(tabsToClose(ordered, "plugin:a", "after").map(tab => tab.id), ["b", "plugin-b"]);
assert.deepEqual(tabsToClose(ordered, "renamed.md", "others").map(tab => tab.id), ["plugin-a", "plugin-b"]);
assert.deepEqual(tabsToClose(ordered, "plugin:b", "all").map(tab => tab.id), ["plugin-a", "b", "plugin-b"]);
});
test("replacing an empty or current document retains its tab position and creates a new buffer", async () => {
const docs = new Documents({
read: async path => path, write: async () => {}, image: async () => "",
kind: () => "text", chrome: () => "Writing",
}, () => {});
docs.newTab();
const emptyId = docs.active!.id;
const order = ["plugin-a", emptyId, "plugin-b"];
for (const rel_path of ["a.md", "b.md"]) {
const previousBuffer = docs.active!.id;
await docs.open({ rel_path, name: rel_path, kind: "file" }, "current");
assert.notEqual(docs.active!.id, previousBuffer);
assert.equal(docs.active!.tabId, emptyId);
const tabs = [{ id: "plugin-a" }, { id: "plugin-b" }, { id: docs.active!.tabId! }];
assert.deepEqual(orderWorkbenchTabs(tabs, order).map(tab => tab.id), order);
}
});
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]] [[package]]
name = "runestone" name = "runestone"
version = "0.1.7" version = "0.1.10"
dependencies = [ dependencies = [
"base64 0.23.1", "base64 0.23.1",
"dunce", "dunce",
+4 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "runestone" name = "runestone"
version = "0.1.7" version = "0.1.10"
description = "Writing workspace plus script editor" description = "Writing workspace plus script editor"
authors = ["you"] authors = ["you"]
edition = "2021" edition = "2021"
@@ -22,7 +22,6 @@ notify = "8.2.0"
ignore = "0.4.33" ignore = "0.4.33"
dunce = "1.0.5" dunce = "1.0.5"
tauri-plugin-dialog = "2.7.3" tauri-plugin-dialog = "2.7.3"
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
base64 = "0.23.1" base64 = "0.23.1"
portable-pty = "0.9.0" portable-pty = "0.9.0"
zip = { version = "8.6.0", default-features = false, features = ["deflate"] } zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
@@ -30,6 +29,9 @@ sha2 = "0.10"
uuid = { version = "1", features = ["v4"] } uuid = { version = "1", features = ["v4"] }
reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] } reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
[profile.release] [profile.release]
+6
View File
@@ -2,12 +2,18 @@ fn main() {
tauri_build::try_build( tauri_build::try_build(
tauri_build::Attributes::new().app_manifest( tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[ tauri_build::AppManifest::new().commands(&[
"settings_open_window",
"completion_request",
"completion_cancel",
"browser_request",
"browser_stop",
"workspace_open", "workspace_open",
"workspace_open_window", "workspace_open_window",
"workspace_last_path", "workspace_last_path",
"workspace_recent", "workspace_recent",
"workspace_new", "workspace_new",
"workspace_list", "workspace_list",
"workspace_list_markdown",
"workspace_read", "workspace_read",
"workspace_read_bytes", "workspace_read_bytes",
"workspace_write", "workspace_write",
+7 -1
View File
@@ -2,8 +2,13 @@
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Capability for the main window", "description": "Capability for the main window",
"windows": ["main", "workspace-*", "terminal-*"], "windows": ["main", "workspace-*", "terminal-*", "browser-*"],
"permissions": [ "permissions": [
"allow-settings-open-window",
"allow-completion-request",
"allow-completion-cancel",
"allow-browser-request",
"allow-browser-stop",
"core:default", "core:default",
"core:window:allow-destroy", "core:window:allow-destroy",
"core:window:allow-close", "core:window:allow-close",
@@ -18,6 +23,7 @@
"allow-workspace-recent", "allow-workspace-recent",
"allow-workspace-new", "allow-workspace-new",
"allow-workspace-list", "allow-workspace-list",
"allow-workspace-list-markdown",
"allow-workspace-read", "allow-workspace-read",
"allow-workspace-read-bytes", "allow-workspace-read-bytes",
"allow-workspace-write", "allow-workspace-write",
+29
View File
@@ -0,0 +1,29 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "settings",
"description": "Settings windows and their plugin settings",
"windows": ["settings-main", "settings-workspace-*"],
"permissions": [
"core:default",
"core:window:allow-close",
"dialog:default",
"allow-plugins-snapshot",
"allow-plugins-choose",
"allow-plugins-from-git",
"allow-plugins-cancel",
"allow-plugins-install",
"allow-plugins-set-enabled",
"allow-plugins-load",
"allow-plugins-release",
"allow-plugins-prepare-remove",
"allow-plugins-remove",
"allow-plugins-retry-remove",
"allow-plugins-reveal",
"allow-plugins-data",
"allow-plugins-asset",
"allow-browser-request",
"allow-browser-stop",
"allow-completion-request",
"allow-completion-cancel"
]
}
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-browser-request"
description = "Enables the browser_request command without any pre-configured scope."
commands.allow = ["browser_request"]
[[permission]]
identifier = "deny-browser-request"
description = "Denies the browser_request command without any pre-configured scope."
commands.deny = ["browser_request"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-browser-stop"
description = "Enables the browser_stop command without any pre-configured scope."
commands.allow = ["browser_stop"]
[[permission]]
identifier = "deny-browser-stop"
description = "Denies the browser_stop command without any pre-configured scope."
commands.deny = ["browser_stop"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-completion-cancel"
description = "Enables the completion_cancel command without any pre-configured scope."
commands.allow = ["completion_cancel"]
[[permission]]
identifier = "deny-completion-cancel"
description = "Denies the completion_cancel command without any pre-configured scope."
commands.deny = ["completion_cancel"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-completion-request"
description = "Enables the completion_request command without any pre-configured scope."
commands.allow = ["completion_request"]
[[permission]]
identifier = "deny-completion-request"
description = "Denies the completion_request command without any pre-configured scope."
commands.deny = ["completion_request"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-settings-open-window"
description = "Enables the settings_open_window command without any pre-configured scope."
commands.allow = ["settings_open_window"]
[[permission]]
identifier = "deny-settings-open-window"
description = "Denies the settings_open_window command without any pre-configured scope."
commands.deny = ["settings_open_window"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-list-markdown"
description = "Enables the workspace_list_markdown command without any pre-configured scope."
commands.allow = ["workspace_list_markdown"]
[[permission]]
identifier = "deny-workspace-list-markdown"
description = "Denies the workspace_list_markdown command without any pre-configured scope."
commands.deny = ["workspace_list_markdown"]
+639
View File
@@ -0,0 +1,639 @@
use serde_json::{json, Value};
use std::{
collections::{HashMap, HashSet},
fs,
io::{BufRead, BufReader, Read, Write},
net::TcpStream,
path::{Path, PathBuf},
process::{Child, Command, Stdio},
sync::{mpsc, Arc, Mutex},
time::{Duration, Instant},
};
use tauri::{AppHandle, Emitter, Manager, State};
type Result<T> = std::result::Result<T, String>;
const PLUGIN: &str = "runestone.browser";
const COMMANDS: &[&str] = &[
"state",
"newTab",
"closeTab",
"navigate",
"back",
"forward",
"reload",
"stop",
"find",
"stopFind",
"openExternal",
"moveToWindow",
"adoptTab",
"resize",
"visible",
"input",
"createProfile",
"renameProfile",
"duplicateProfile",
"bookmark",
"removeBookmark",
"settings",
"clearData",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
}
#[derive(Default)]
struct WindowTabs {
windows: HashSet<String>,
owners: HashMap<String, String>,
pending: HashMap<String, String>,
transfer_tokens: HashMap<String, String>,
}
impl WindowTabs {
fn snapshot(&self, mut value: Value, owner: &str) -> Value {
if let Some(tabs) = value.get_mut("tabs").and_then(Value::as_array_mut) {
tabs.retain(|tab| tab["id"].as_str().and_then(|id| self.owners.get(id)).is_some_and(|window| window == owner));
for tab in tabs {
if let Some(token) = tab["id"].as_str().and_then(|id| self.transfer_tokens.get(id)) {
tab["transferToken"] = json!(token);
}
}
}
value
}
fn close(&mut self, owner: &str) -> Vec<String> {
self.windows.remove(owner);
self.pending.retain(|_, target| target != owner);
let closed: Vec<String> = self.owners.iter().filter(|(id, window)| !self.windows.contains(*window) && !self.pending.contains_key(*id)).map(|(id, _)| id.clone()).collect();
for id in &closed { self.owners.remove(id); self.transfer_tokens.remove(id); }
closed
}
fn assign(&mut self, id: &str, owner: &str) {
self.owners.insert(id.into(), owner.into());
self.transfer_tokens.insert(id.into(), uuid::Uuid::new_v4().to_string());
}
fn adopt(&mut self, id: &str, owner: &str, token: Option<&str>) -> Result<String> {
let source = self.owners.get(id).cloned().ok_or("Unknown browser tab.")?;
if source == owner { return Err("This browser tab already belongs to this window.".into()); }
let pending = self.pending.get(id).map(String::as_str);
let dragged = pending.is_none() && token.is_some() && self.transfer_tokens.get(id).map(String::as_str) == token;
if pending != Some(owner) && !dragged { return Err("This browser tab has no valid transfer to this window.".into()); }
self.assign(id, owner);
self.pending.remove(id);
Ok(source)
}
}
struct Worker {
child: Child,
input: Box<dyn Write + Send>,
replies: mpsc::Receiver<Value>,
routing: Arc<Mutex<WindowTabs>>,
sequence: u64,
healthy: bool,
}
fn fail(error: impl std::fmt::Display) -> String {
error.to_string()
}
fn root(app: &AppHandle) -> Result<PathBuf> {
Ok(app.path().app_data_dir().map_err(fail)?.join("browser"))
}
fn executable(app: &AppHandle) -> Result<PathBuf> {
let name = if cfg!(windows) {
"RuneStone-Browser.exe"
} else {
"RuneStone-Browser"
};
let packaged = app
.path()
.resource_dir()
.map_err(fail)?
.join("browser-engine")
.join(name);
if packaged.is_file() {
return Ok(packaged);
}
#[cfg(debug_assertions)]
{
let development = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("browser-engine")
.join(name);
if development.is_file() {
return Ok(development);
}
}
Err("The browser runtime is missing. Build RuneStone with its browser runtime.".into())
}
fn authenticate_connection(
stream: TcpStream,
token: &str,
) -> Result<Option<(TcpStream, BufReader<TcpStream>)>> {
stream.set_nonblocking(false).map_err(fail)?;
stream.set_nodelay(true).map_err(fail)?;
stream.set_read_timeout(Some(Duration::from_secs(1))).map_err(fail)?;
let mut reader = BufReader::new(stream.try_clone().map_err(fail)?);
let mut bytes = Vec::new();
let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes);
let received = serde_json::from_slice::<Value>(&bytes)
.ok()
.and_then(|value| value["token"].as_str().map(str::to_string));
if read.is_err() || received.as_deref() != Some(token) {
return Ok(None);
}
// Windows keeps the timeout on the cloned socket after the original changes.
reader.get_ref().set_read_timeout(None).map_err(fail)?;
stream.set_read_timeout(None).map_err(fail)?;
Ok(Some((stream, reader)))
}
impl Worker {
fn start(app: &AppHandle, routing: Arc<Mutex<WindowTabs>>) -> Result<Self> {
let directory = root(app)?;
fs::create_dir_all(&directory).map_err(fail)?;
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(fail)?;
listener.set_nonblocking(true).map_err(fail)?;
let port = listener.local_addr().map_err(fail)?.port();
let token = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
);
let mut command = Command::new(executable(app)?);
command
.arg(format!("--rs-connect={port}"))
.arg(format!("--rs-browser-root={}", directory.display()))
.env("RUNESTONE_BROWSER_TOKEN", &token)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
command
.env_remove("ELECTRON_RUN_AS_NODE")
.env_remove("NODE_OPTIONS")
.env_remove("ELECTRON_DISABLE_SANDBOX");
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
}
let mut child = command.spawn().map_err(fail)?;
let deadline = Instant::now() + Duration::from_secs(30);
let (input, output): (Box<dyn Write + Send>, Box<dyn Read + Send>) = loop {
if let Ok((stream, _)) = listener.accept() {
if let Some((stream, reader)) = authenticate_connection(stream, &token)? {
break (Box::new(stream), Box::new(reader));
}
}
if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() {
let _ = child.kill();
let _ = child.wait();
return Err("The browser runtime did not start.".into());
}
std::thread::sleep(Duration::from_millis(20));
};
drop(listener);
let (send, replies) = mpsc::sync_channel(16);
let handle = app.clone();
let routes = routing.clone();
std::thread::spawn(move || {
let mut reader = BufReader::new(output);
loop {
let mut bytes = Vec::new();
match reader
.by_ref()
.take(6_000_001)
.read_until(b'\n', &mut bytes)
{
Ok(0) | Err(_) => break,
Ok(_) if bytes.len() > 6_000_000 || !bytes.ends_with(b"\n") => break,
_ => {}
}
let Ok(value) = serde_json::from_slice::<Value>(&bytes) else {
continue;
};
match value.get("event").and_then(Value::as_str) {
Some("frame") => {
if let Ok(routes) = routes.lock() {
if let Some(target) = value["tabId"].as_str().and_then(|id| routes.owners.get(id)) {
let _ = handle.emit_to(target, "browser-frame", &value);
}
}
}
Some("state") | Some("error") => {
if let Ok(routes) = routes.lock() {
for target in &routes.windows {
if let Some(id) = value["tabId"].as_str() {
if routes.owners.get(id) != Some(target) { continue; }
}
let mut payload = value.clone();
if value.get("state").is_some() { payload["state"] = routes.snapshot(value["state"].clone(), target); }
let _ = handle.emit_to(target, "browser-state", &payload);
}
}
}
_ => {
if send.try_send(value).is_err() {
break;
}
}
}
}
});
let mut worker = Self {
child,
input,
replies,
routing,
sequence: 0,
healthy: true,
};
match worker.replies.recv_timeout(Duration::from_secs(30)) {
Ok(value) if value["event"] == "ready" => Ok(worker),
_ => {
let _ = worker.child.kill();
let _ = worker.child.wait();
Err("The browser runtime did not start.".into())
}
}
}
fn request(&mut self, command: &str, args: Value) -> Result<Value> {
let response = match self.exchange(command, args) {
Ok(response) => response,
Err(error) => {
self.healthy = false;
return Err(error);
}
};
if let Some(error) = response["error"].as_str() {
return Err(error.into());
}
Ok(response["result"].clone())
}
fn exchange(&mut self, command: &str, args: Value) -> Result<Value> {
self.sequence += 1;
let message = json!({ "id": self.sequence, "command": command, "args": args });
writeln!(self.input, "{}", message).map_err(fail)?;
self.input.flush().map_err(fail)?;
let response = self
.replies
.recv_timeout(Duration::from_secs(30))
.map_err(|_| {
"The browser stopped responding. Open a new browser tab to restart it.".to_string()
})?;
if response["id"].as_u64() != Some(self.sequence) {
return Err("The browser response did not match the request.".into());
}
Ok(response)
}
fn stop(&mut self) -> Result<()> {
if !self.healthy {
let _ = self.child.kill();
let _ = self.child.wait();
return Ok(());
}
let requested = self.request("shutdown", json!({}));
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if self.child.try_wait().map_err(fail)?.is_some() {
return requested.map(|_| ());
}
std::thread::sleep(Duration::from_millis(20));
}
let _ = self.child.kill();
let _ = self.child.wait();
Err("The browser did not stop cleanly. Profile duplication was cancelled.".into())
}
}
impl Drop for Worker {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
fn profile_id(value: &str) -> bool {
!value.is_empty()
&& value.len() <= 64
&& value
.bytes()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
}
fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> {
if !source.exists() {
fs::create_dir_all(target).map_err(fail)?;
return Ok(());
}
let metadata = fs::symlink_metadata(source).map_err(fail)?;
if metadata.file_type().is_symlink() {
return Err("Profile links cannot be duplicated.".into());
}
if metadata.is_dir() {
fs::create_dir_all(target).map_err(fail)?;
for entry in fs::read_dir(source).map_err(fail)? {
let entry = entry.map_err(fail)?;
copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?;
}
} else if metadata.is_file() {
*files += 1;
*bytes += metadata.len();
if *files > 50_000 || *bytes > 2_000_000_000 {
return Err("This profile exceeds the duplication limit.".into());
}
fs::copy(source, target).map_err(fail)?;
} else {
return Err("Unsupported profile entry.".into());
}
Ok(())
}
impl BrowserState {
pub fn close_window(&self, owner: &str) {
if let Ok(mut guard) = self.inner.lock() {
let Some(worker) = guard.as_mut() else { return; };
let (closed, empty) = match worker.routing.lock() {
Ok(mut routes) => { let closed = routes.close(owner); (closed, routes.windows.is_empty()) },
Err(_) => return,
};
for id in closed { let _ = worker.request("closeTab", json!({ "tabId": id })); }
if empty {
if let Some(mut worker) = guard.take() { let _ = worker.stop(); }
}
}
}
pub fn close_all(&self) {
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
}
}
}
fn request(&self, app: &AppHandle, owner: &str, command: &str, args: Value) -> Result<Value> {
if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() {
return Err("Invalid browser request.".into());
}
let mut guard = self.inner.lock().map_err(fail)?;
if guard.as_ref().is_some_and(|worker| !worker.healthy) {
guard.take();
}
if guard.is_none() {
*guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?);
}
let worker = guard.as_mut().unwrap();
worker.routing.lock().map_err(fail)?.windows.insert(owner.to_string());
if command == "adoptTab" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let result = worker.request("state", json!({}))?;
if !result["tabs"].as_array().is_some_and(|tabs| tabs.iter().any(|tab| tab["id"] == id)) {
return Err("Unknown browser tab.".into());
}
let source = {
let mut routes = worker.routing.lock().map_err(fail)?;
routes.adopt(id, owner, args["transferToken"].as_str())?
};
let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id }));
return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner));
}
if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "bookmark", "agentSnapshot"].contains(&command) {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
match worker.routing.lock().map_err(fail)?.owners.get(id) {
Some(window) if window == owner => {},
Some(_) => return Err("This browser tab belongs to another window.".into()),
None => return Err("Unknown browser tab.".into()),
}
}
if command == "moveToWindow" {
let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?;
let label = format!("browser-{}", uuid::Uuid::new_v4());
{
let mut routes = worker.routing.lock().map_err(fail)?;
if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); }
routes.pending.insert(id.into(), label.clone());
routes.windows.insert(label.clone());
}
let mut url = tauri::Url::parse("http://localhost/").map_err(fail)?;
url.query_pairs_mut().append_pair("browserWindow", "true");
url.query_pairs_mut().append_pair("browserTab", id);
if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); }
let result = tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into()))
.title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).decorations(false).drag_and_drop(false).build();
if let Err(error) = result {
worker.routing.lock().map_err(fail)?.close(&label);
return Err(fail(error));
}
return Ok(json!({ "windowLabel": label }));
}
if command != "duplicateProfile" {
let result = worker.request(command, args.clone())?;
let mut routes = worker.routing.lock().map_err(fail)?;
if command == "newTab" {
if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); }
} else if command == "closeTab" {
if let Some(id) = args["tabId"].as_str() { routes.owners.remove(id); routes.pending.remove(id); routes.transfer_tokens.remove(id); }
}
return Ok(routes.snapshot(result, owner));
}
let plan = guard.as_mut().unwrap().request("prepareDuplicate", args)?;
let source_id = plan["sourceId"]
.as_str()
.filter(|id| profile_id(id))
.ok_or("Invalid source profile.")?;
let target_id = plan["id"]
.as_str()
.filter(|id| uuid::Uuid::parse_str(id).is_ok())
.ok_or("Invalid destination profile.")?;
let mut worker = guard.take().unwrap();
let routing = worker.routing.clone();
worker.stop()?;
drop(worker);
// Chromium is fully stopped before its databases are copied.
let partitions = root(app)?.join("Partitions");
let source = partitions.join(format!("runestone-{source_id}"));
let destination = partitions.join(format!("runestone-{target_id}"));
if destination.exists() {
return Err("The destination profile already exists.".into());
}
copy_profile(&source, &destination, &mut 0, &mut 0)?;
*guard = Some(Worker::start(app, routing.clone())?);
let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?;
let snapshot = routing.lock().map_err(fail)?.snapshot(result, owner);
Ok(snapshot)
}
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
) -> Result<Value> {
let owner = window.label().to_string();
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
tauri::async_runtime::spawn_blocking(move || {
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
})
.await
.map_err(fail)?
}
#[tauri::command]
pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> {
state.close_window(window.label());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.assign("a", "browser-other");
let snapshot = json!({ "tabs": [{ "id": "a" }] });
let token = routes.snapshot(snapshot.clone(), "browser-other")["tabs"][0]["transferToken"].as_str().unwrap().to_string();
assert!(routes.snapshot(snapshot, "main")["tabs"].as_array().unwrap().is_empty());
assert!(routes.adopt("a", "main", None).is_err());
assert!(routes.adopt("a", "main", Some("wrong-token")).is_err());
assert_eq!(routes.owners["a"], "browser-other");
assert_eq!(routes.adopt("a", "main", Some(&token)).unwrap(), "browser-other");
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners["a"], "main");
assert_ne!(routes.transfer_tokens["a"], token);
assert_eq!(routes.close("main"), vec!["a"]);
assert!(routes.transfer_tokens.is_empty());
}
#[test]
fn a_pending_window_move_cannot_be_taken_by_a_drag() {
let mut routes = WindowTabs::default();
routes.assign("a", "main");
let token = routes.transfer_tokens["a"].clone();
routes.pending.insert("a".into(), "browser-target".into());
assert!(routes.adopt("a", "browser-other", Some(&token)).is_err());
assert_eq!(routes.adopt("a", "browser-target", None).unwrap(), "main");
assert!(routes.pending.is_empty());
}
#[test]
fn window_routing_preserves_moved_tabs_and_filters_snapshots() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.owners.insert("b".into(), "browser-other".into());
let snapshot = json!({ "tabs": [{ "id": "a" }, { "id": "b" }], "profiles": [{ "id": "user" }] });
assert_eq!(routes.snapshot(snapshot.clone(), "main")["tabs"], json!([{ "id": "a" }]));
assert_eq!(routes.snapshot(snapshot, "browser-other")["tabs"], json!([{ "id": "b" }]));
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("main").is_empty());
assert!(routes.owners.contains_key("a"));
let mut closed = routes.close("browser-other");
closed.sort();
assert_eq!(closed, vec!["a", "b"]);
assert!(routes.owners.is_empty());
}
#[test]
fn cancelled_window_move_keeps_the_source_tab() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
routes.owners.insert("a".into(), "main".into());
routes.pending.insert("a".into(), "browser-other".into());
assert!(routes.close("browser-other").is_empty());
assert_eq!(routes.owners.get("a").map(String::as_str), Some("main"));
assert!(routes.pending.is_empty());
}
#[test]
fn authenticated_connection_survives_idle_period() {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
writeln!(stream, "{}", json!({ "token": "test-token" })).unwrap();
std::thread::sleep(Duration::from_millis(1500));
writeln!(stream, "{}", json!({ "id": 1, "result": { "tabs": [] } })).unwrap();
});
let (stream, _) = listener.accept().unwrap();
let (input, mut reader) = authenticate_connection(stream, "test-token").unwrap().unwrap();
assert_eq!(input.read_timeout().unwrap(), None);
assert_eq!(reader.get_ref().read_timeout().unwrap(), None);
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], 1);
sender.join().unwrap();
}
#[test]
fn authentication_preserves_buffered_messages_and_rejects_other_tokens() {
for accepted in [false, true] {
let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
let address = listener.local_addr().unwrap();
let sender = std::thread::spawn(move || {
let mut stream = TcpStream::connect(address).unwrap();
stream.write_all(b"{\"token\":\"test-token\"}\n{\"event\":\"ready\"}\n").unwrap();
});
let (stream, _) = listener.accept().unwrap();
let connection = authenticate_connection(stream, if accepted { "test-token" } else { "other-token" }).unwrap();
if accepted {
let (_, mut reader) = connection.unwrap();
let mut line = String::new();
reader.read_line(&mut line).unwrap();
assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["event"], "ready");
} else {
assert!(connection.is_none());
}
sender.join().unwrap();
}
}
fn test_worker(replies: mpsc::Receiver<Value>) -> Worker {
Worker {
child: Command::new(std::env::current_exe().unwrap())
.arg("--list")
.stdout(Stdio::null())
.spawn()
.unwrap(),
input: Box::new(Vec::<u8>::new()),
replies,
routing: Arc::new(Mutex::new(WindowTabs::default())),
sequence: 0,
healthy: true,
}
}
#[test]
fn broken_transport_requires_a_fresh_worker() {
let (send, replies) = mpsc::channel();
drop(send);
let mut worker = test_worker(replies);
assert!(worker.request("state", json!({})).is_err());
assert!(!worker.healthy);
assert!(worker.stop().is_ok());
}
#[test]
fn invalid_settings_do_not_discard_the_worker() {
let (send, replies) = mpsc::channel();
send.send(json!({ "id": 1, "error": "Invalid browser settings." })).unwrap();
send.send(json!({ "id": 2, "result": { "tabs": [] } })).unwrap();
let mut worker = test_worker(replies);
assert!(worker.request("settings", json!({})).is_err());
assert!(worker.healthy);
assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] }));
}
#[test]
fn profile_names_cannot_escape_storage() {
for value in ["../other", "a/b", "a\\b", "C:", "", "."] {
assert!(!profile_id(value));
}
assert!(profile_id("user"));
assert!(profile_id("a-b-123"));
}
#[test]
fn protocol_does_not_expose_raw_execution_or_copy_commands() {
for name in [
"executeJavaScript",
"shell",
"prepareDuplicate",
"commitDuplicate",
"shutdown",
] {
assert!(!COMMANDS.contains(&name));
}
}
}
+81
View File
@@ -0,0 +1,81 @@
use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration};
use reqwest::{blocking::Client, Url};
use serde::Deserialize;
use tauri::{ipc::Channel, State, WebviewWindow};
#[derive(Default)]
pub struct CompletionState { requests: Mutex<HashMap<String, Arc<AtomicBool>>> }
impl CompletionState {
pub fn close_window(&self, window: &str) {
if let Ok(mut requests) = self.requests.lock() {
requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } });
}
}
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletionRequest { endpoint: String, route: String, body: Option<String>, timeout_ms: Option<u64> }
fn target(endpoint: &str, route: &str) -> Result<Url, String> {
let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?;
if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
|| !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some()
|| !matches!(url.path(), "" | "/" | "/v1" | "/v1/") {
return Err("This trial connects only to a loopback model server.".into());
}
if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); }
if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; }
url.set_path(route); Ok(url)
}
#[tauri::command]
pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) {
if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } }
}
#[tauri::command]
pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel<String>) -> Result<(), String> {
if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); }
let url = target(&request.endpoint, &request.route)?;
let flag = Arc::new(AtomicBool::new(false));
let key = format!("{}:{id}", window.label());
{
let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?;
if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); }
requests.insert(key.clone(), flag.clone());
}
let result = tauri::async_runtime::spawn_blocking(move || {
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none())
.connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000)))
.build().map_err(|_| "Could not create a local connection.".to_string())?;
if flag.load(Ordering::Relaxed) { return Ok(()); }
let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) };
let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." }.to_string())?;
if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); }
let mut reader = BufReader::new(response);
let mut total = 0;
loop {
if flag.load(Ordering::Relaxed) { return Ok(()); }
let mut bytes = Vec::new();
let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.".to_string())?;
if count == 0 { break; }
total += count;
if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); }
if flag.load(Ordering::Relaxed) { return Ok(()); }
let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.".to_string())?;
if on_line.send(line).is_err() { break; }
}
Ok(())
}).await.map_err(|_| "Local completion task stopped.".to_string());
if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); }
result?
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_loopback_and_fixed_routes() {
assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models");
for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] {
assert!(target(address, "/v1/models").is_err(), "{address}");
}
assert!(target("http://127.0.0.1:8080", "/shutdown").is_err());
}
}
+16
View File
@@ -2,6 +2,9 @@ mod pty;
mod plugins; mod plugins;
mod plugin_sources; mod plugin_sources;
mod workspace; mod workspace;
mod browser;
mod completion;
mod settings;
use pty::PtyState; use pty::PtyState;
use tauri::Manager; use tauri::Manager;
@@ -15,13 +18,22 @@ pub fn run() {
.manage(WorkspaceState::new()) .manage(WorkspaceState::new())
.manage(PtyState::new()) .manage(PtyState::new())
.manage(plugins::PluginState::default()) .manage(plugins::PluginState::default())
.manage(browser::BrowserState::default())
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![ .invoke_handler(tauri::generate_handler![
settings::settings_open_window,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
browser::browser_stop,
workspace::workspace_open, workspace::workspace_open,
workspace::workspace_open_window, workspace::workspace_open_window,
workspace::workspace_last_path, workspace::workspace_last_path,
workspace::workspace_recent, workspace::workspace_recent,
workspace::workspace_new, workspace::workspace_new,
workspace::workspace_list, workspace::workspace_list,
workspace::workspace_list_markdown,
workspace::workspace_read, workspace::workspace_read,
workspace::workspace_read_bytes, workspace::workspace_read_bytes,
workspace::workspace_write, workspace::workspace_write,
@@ -60,12 +72,16 @@ pub fn run() {
.expect("error while building tauri application") .expect("error while building tauri application")
.run(|app, event| { .run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event { if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
settings::close_owned_window(app, label);
app.state::<PtyState>().close_window(label); app.state::<PtyState>().close_window(label);
app.state::<completion::CompletionState>().close_window(label);
app.state::<browser::BrowserState>().close_window(label);
app.state::<plugins::PluginState>().close_window(label); app.state::<plugins::PluginState>().close_window(label);
app.state::<WorkspaceState>().close_window(label); app.state::<WorkspaceState>().close_window(label);
} }
if matches!(event, tauri::RunEvent::Exit) { if matches!(event, tauri::RunEvent::Exit) {
app.state::<PtyState>().close_all(); app.state::<PtyState>().close_all();
app.state::<browser::BrowserState>().close_all();
} }
}); });
} }
+16 -2
View File
@@ -861,6 +861,13 @@ impl Service {
} }
} }
impl PluginState { impl PluginState {
pub fn require_lease(&self, app: &AppHandle, owner: &str, id: &str) -> Result<()> {
self.with(app, |service| {
let enabled = service.catalog.plugins.get(id).is_some_and(|record| record.enabled && record.removal.is_none());
let leased = service.leases.get(id).is_some_and(|windows| windows.contains(owner));
if enabled && leased { Ok(()) } else { Err("The browser plugin is not enabled in this window.".into()) }
})
}
fn with<T>( fn with<T>(
&self, &self,
app: &AppHandle, app: &AppHandle,
@@ -1019,6 +1026,7 @@ pub async fn plugins_set_enabled(
enabled: bool, enabled: bool,
hash: Option<String>, hash: Option<String>,
) -> Result<()> { ) -> Result<()> {
let stop_browser = id == "runestone.browser" && !enabled;
state.with(&app, |service| { state.with(&app, |service| {
if service.removing.contains_key(&id) { if service.removing.contains_key(&id) {
return Err("Wait for plugin removal to finish.".into()); return Err("Wait for plugin removal to finish.".into());
@@ -1047,6 +1055,7 @@ pub async fn plugins_set_enabled(
} }
Ok(()) Ok(())
})?; })?;
if stop_browser { app.state::<crate::browser::BrowserState>().close_all(); }
changed(&app); changed(&app);
Ok(()) Ok(())
} }
@@ -1183,7 +1192,8 @@ pub async fn plugins_data(
id: String, id: String,
value: Option<String>, value: Option<String>,
) -> Result<String> { ) -> Result<String> {
state.with(&app, |service| { let changed = value.is_some();
let result = state.with(&app, |service| {
if !service.row(&id)?.enabled { if !service.row(&id)?.enabled {
return Err("The plugin is disabled.".into()); return Err("The plugin is disabled.".into());
} }
@@ -1211,7 +1221,11 @@ pub async fn plugins_data(
} else { } else {
Ok("null".into()) Ok("null".into())
} }
}) })?;
if changed {
let _ = app.emit("plugin-settings-changed", &id);
}
Ok(result)
} }
#[tauri::command] #[tauri::command]
pub async fn plugins_asset( pub async fn plugins_asset(
+222
View File
@@ -0,0 +1,222 @@
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}};
use tauri::{AppHandle, Manager, State};
use crate::workspace::{current_root_path, WorkspaceState};
#[derive(Default)]
pub struct SettingsState(Mutex<HashMap<String, Arc<AtomicBool>>>);
struct PendingOpen<'a> {
state: &'a SettingsState,
label: String,
cancelled: Arc<AtomicBool>,
}
impl SettingsState {
fn reserve(&self, label: &str) -> Result<Option<PendingOpen<'_>>, String> {
let mut pending = self.0.lock().map_err(|_| "Settings window lock failed.")?;
if let Some(cancelled) = pending.get(label) {
return if cancelled.load(Ordering::SeqCst) {
Err("The workspace changed while settings opened. Try again.".into())
} else { Ok(None) };
}
let cancelled = Arc::new(AtomicBool::new(false));
pending.insert(label.into(), cancelled.clone());
Ok(Some(PendingOpen { state: self, label: label.into(), cancelled }))
}
fn cancel(&self, label: &str) {
if let Ok(pending) = self.0.lock() {
if let Some(cancelled) = pending.get(label) { cancelled.store(true, Ordering::SeqCst); }
}
}
}
impl PendingOpen<'_> {
fn can_publish(&self, owner_exists: bool, expected: &Option<PathBuf>, current: &Option<PathBuf>) -> bool {
!self.cancelled.load(Ordering::SeqCst) && owner_exists && expected == current
}
}
impl Drop for PendingOpen<'_> {
fn drop(&mut self) {
if let Ok(mut pending) = self.state.0.lock() { pending.remove(&self.label); }
}
}
fn settings_label(owner: &str) -> Result<String, String> {
if owner == "main" || owner.starts_with("workspace-") {
Ok(format!("settings-{owner}"))
} else {
Err("Open settings from a workspace window.".into())
}
}
fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<(), String> {
if let Ok(root) = current_root_path(workspace, owner) {
workspace.bind_terminal(label, root).map_err(|error| error.to_string())?;
} else {
workspace.close_window(label);
}
Ok(())
}
#[tauri::command]
pub async fn settings_open_window(
app: AppHandle,
window: tauri::Window,
state: State<'_, SettingsState>,
workspace: State<'_, WorkspaceState>,
) -> Result<(), String> {
let label = settings_label(window.label())?;
// The reservation survives native calls, but its mutex guard never does.
let Some(pending) = state.reserve(&label)? else { return Ok(()); };
let root = current_root_path(&workspace, window.label()).ok();
let valid = || pending.can_publish(
app.get_webview_window(window.label()).is_some(),
&root, &current_root_path(&workspace, window.label()).ok(),
);
if !valid() { return Err("The workspace closed while settings opened.".into()); }
bind_workspace(&workspace, window.label(), &label)?;
let settings = if let Some(existing) = app.get_webview_window(&label) {
existing
} else {
let title = root.as_ref()
.and_then(|root| root.file_name().map(|name| format!("Settings — {} — RuneStone", name.to_string_lossy())))
.unwrap_or_else(|| "Settings — RuneStone".into());
match tauri::WebviewWindowBuilder::new(
&app, &label, tauri::WebviewUrl::App("?settingsWindow=true".into()),
)
.title(title)
.inner_size(920.0, 650.0)
.min_inner_size(540.0, 420.0)
.decorations(true)
.resizable(true)
.visible(false)
.disable_drag_drop_handler()
.build() {
Ok(settings) => settings,
Err(error) => { workspace.close_window(&label); return Err(error.to_string()); }
}
};
let result = (|| {
if !valid() { return Err("The workspace changed while settings opened.".into()); }
settings.unminimize().map_err(|error| error.to_string())?;
settings.show().map_err(|error| error.to_string())?;
settings.set_focus().map_err(|error| error.to_string())?;
if !valid() { return Err("The workspace changed while settings opened.".into()); }
Ok(())
})();
if result.is_err() {
let _ = settings.destroy();
workspace.close_window(&label);
}
result
}
pub fn close_owned_window(app: &AppHandle, owner: &str) {
if let Ok(label) = settings_label(owner) {
app.state::<SettingsState>().cancel(&label);
if let Some(window) = app.get_webview_window(&label) { let _ = window.destroy(); }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pending_opens_deduplicate_without_holding_the_state_lock() {
let state = SettingsState::default();
let first = state.reserve("settings-main").unwrap().unwrap();
assert!(state.0.try_lock().is_ok());
assert!(state.reserve("settings-main").unwrap().is_none());
assert!(state.reserve("settings-workspace-2").unwrap().is_some());
drop(first);
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn lifecycle_cancellation_does_not_wait_for_an_inflight_build() {
let state = Arc::new(SettingsState::default());
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (resume_tx, resume_rx) = std::sync::mpsc::channel();
let worker_state = state.clone();
let worker = std::thread::spawn(move || {
let pending = worker_state.reserve("settings-main").unwrap().unwrap();
started_tx.send(()).unwrap();
// Stand in for a native build waiting for the UI thread.
resume_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
assert!(!pending.can_publish(true, &None, &None));
});
started_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap();
state.cancel("settings-main");
assert!(state.reserve("settings-main").is_err());
resume_tx.send(()).unwrap();
worker.join().unwrap();
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn completed_build_rejects_closed_owners_and_changed_workspaces() {
let state = SettingsState::default();
let pending = state.reserve("settings-main").unwrap().unwrap();
let root = Some(PathBuf::from("/one"));
assert!(pending.can_publish(true, &root, &root));
assert!(!pending.can_publish(false, &root, &root));
assert!(!pending.can_publish(true, &None, &root));
assert!(!pending.can_publish(true, &root, &Some(PathBuf::from("/two"))));
state.cancel("settings-main");
assert!(!pending.can_publish(true, &root, &root));
}
#[test]
fn failed_build_releases_its_reservation_for_retry() {
let state = SettingsState::default();
let failed = || -> Result<(), String> {
let _pending = state.reserve("settings-main")?.unwrap();
Err("Native build failed".into())
};
assert!(failed().is_err());
assert!(state.reserve("settings-main").unwrap().is_some());
}
#[test]
fn each_workspace_reuses_its_own_settings_label() {
assert_eq!(settings_label("main").unwrap(), "settings-main");
assert_eq!(settings_label("workspace-12").unwrap(), "settings-workspace-12");
assert_ne!(settings_label("main").unwrap(), settings_label("workspace-12").unwrap());
}
#[test]
fn auxiliary_windows_cannot_create_settings_windows() {
for owner in ["settings-main", "terminal-123", "browser-123", "external"] {
assert!(settings_label(owner).is_err());
}
}
#[test]
fn settings_use_only_the_owners_workspace_and_release_it_on_close() {
let workspace = WorkspaceState::new();
workspace.bind_terminal("workspace-1", "/one".into()).unwrap();
workspace.bind_terminal("workspace-2", "/two".into()).unwrap();
bind_workspace(&workspace, "workspace-1", "settings-workspace-1").unwrap();
bind_workspace(&workspace, "workspace-2", "settings-workspace-2").unwrap();
assert_eq!(current_root_path(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one"));
assert_eq!(current_root_path(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two"));
workspace.close_window("settings-workspace-1");
assert!(current_root_path(&workspace, "settings-workspace-1").is_err());
assert!(current_root_path(&workspace, "workspace-1").is_ok());
}
#[test]
fn settings_without_a_workspace_never_use_the_recent_workspace() {
let workspace = WorkspaceState::new();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert!(current_root_path(&workspace, "settings-main").is_err());
workspace.bind_terminal("main", "/opened-later".into()).unwrap();
bind_workspace(&workspace, "main", "settings-main").unwrap();
assert_eq!(current_root_path(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later"));
}
}
+64
View File
@@ -450,6 +450,8 @@ pub fn workspace_open(
}); });
} }
let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name)); let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name));
// A settings session opened before this workspace must start with its new context.
crate::settings::close_owned_window(&app, window.label());
Ok(workspace_info(&root)) Ok(workspace_info(&root))
} }
@@ -510,6 +512,39 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
Ok(entries) Ok(entries)
} }
#[tauri::command]
pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> WsResult<Vec<String>> {
let root = current_root_path(&state, window.label())?;
tauri::async_runtime::spawn_blocking(move || markdown_paths(&root))
.await.map_err(|error| err(format!("Markdown scan failed: {error}")))?
}
fn markdown_paths(root: &Path) -> WsResult<Vec<String>> {
let mut folders = vec![root.to_path_buf()];
let mut paths = Vec::new();
while let Some(folder) = folders.pop() {
for entry in fs::read_dir(folder)? {
let entry = entry?;
let name = entry.file_name();
// Match PM discovery without a desktop request for every directory.
if name.to_string_lossy().starts_with('.') { continue; }
let kind = entry.file_type()?;
if kind.is_symlink() { continue; }
let path = entry.path();
if kind.is_dir() {
folders.push(path);
} else if kind.is_file() {
let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase();
if matches!(extension.as_str(), "md" | "markdown" | "mdown") {
if let Some(rel) = to_rel(root, &path) { paths.push(rel); }
}
}
}
}
paths.sort();
Ok(paths)
}
#[tauri::command] #[tauri::command]
pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> WsResult<Option<String>> { pub fn workspace_read(window: tauri::Window, state: State<WorkspaceState>, rel: String, missing_ok: Option<bool>) -> WsResult<Option<String>> {
let root = current_root(&state, window.label())?; let root = current_root(&state, window.label())?;
@@ -812,6 +847,11 @@ pub fn workspace_abs_path(window: tauri::Window, state: State<WorkspaceState>, r
pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> { pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
let root = current_root(&state, window.label())?; let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?; let path = resolve_existing(&root, &rel)?;
if rel.is_empty() {
return app.opener()
.open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>)
.map_err(|e| err(e.to_string()));
}
if app.opener().reveal_item_in_dir(&path).is_ok() { if app.opener().reveal_item_in_dir(&path).is_ok() {
return Ok(()); return Ok(());
} }
@@ -936,6 +976,30 @@ mod tests {
use super::*; use super::*;
use std::path::PathBuf; use std::path::PathBuf;
#[test]
fn markdown_listing_preserves_discovery_and_excludes_hidden_storage() {
let root = std::env::temp_dir().join(format!("rs-markdown-list-{}", uuid::Uuid::new_v4()));
for rel in ["Notes", "target/deep", ".runestone/pm/cards", "Notes/.hidden", ".git"] {
fs::create_dir_all(root.join(rel)).unwrap();
}
for rel in ["Board.MD", "Notes/one.markdown", "target/deep/two.mdown", ".runestone/pm/cards/private.md", "Notes/.hidden/secret.md", ".git/hidden.md", "Notes/.hidden.md", "Notes/plain.txt"] {
fs::write(root.join(rel), "text").unwrap();
}
fs::write(root.join(".gitignore"), "Notes/\ntarget/\n").unwrap();
assert_eq!(markdown_paths(&root).unwrap(), vec!["Board.MD", "Notes/one.markdown", "target/deep/two.mdown"]);
fs::remove_dir_all(&root).unwrap();
assert!(markdown_paths(&root).is_err());
}
#[test]
#[ignore = "Set RUNESTONE_SCAN_BENCH_ROOT to an existing workspace."]
fn markdown_listing_workspace_benchmark() {
let root = dunce::canonicalize(std::env::var("RUNESTONE_SCAN_BENCH_ROOT").unwrap()).unwrap();
let start = std::time::Instant::now();
let paths = markdown_paths(&root).unwrap();
println!("Native Markdown discovery: {} paths, {:?}", paths.len(), start.elapsed());
}
#[test] #[test]
fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() { fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() {
let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id())); let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id()));
+7
View File
@@ -0,0 +1,7 @@
{
"bundle": {
"resources": {
"browser-engine/": "browser-engine/"
}
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone", "productName": "RuneStone",
"version": "0.1.7", "version": "0.1.10",
"identifier": "com.runestone.app", "identifier": "com.runestone.app",
"build": { "build": {
"beforeDevCommand": "pnpm dev", "beforeDevCommand": "pnpm dev",
+62
View File
@@ -0,0 +1,62 @@
import { Prec, StateEffect, StateField } from "@codemirror/state";
import { Decoration, EditorView, keymap, ViewPlugin, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { completionHub } from "./hub";
import type { CompletionHandle } from "./contracts";
class Ghost extends WidgetType {
constructor(readonly text: string) { super(); }
eq(other: Ghost) { return other.text === this.text; }
toDOM() { const span = document.createElement("span"); span.className = "rs-completion-ghost"; span.textContent = this.text; span.setAttribute("aria-hidden", "true"); return span; }
}
const preview = StateEffect.define<{ text: string; caret: number } | null>();
const ghosts = StateField.define({
create: () => Decoration.none,
update(value, transaction) {
if (transaction.docChanged || transaction.selection) value = Decoration.none;
for (const effect of transaction.effects) if (effect.is(preview)) value = effect.value
? Decoration.set([Decoration.widget({ widget: new Ghost(effect.value.text), side: 1 }).range(effect.value.caret)]) : Decoration.none;
return value;
},
provide: field => EditorView.decorations.from(field),
});
const handles = new WeakMap<EditorView, CompletionHandle>();
export function completionExtension(documentId: string) {
return [ghosts, EditorView.baseTheme({ ".rs-completion-ghost": { opacity: "0.65", fontStyle: "italic", pointerEvents: "none" } }),
ViewPlugin.fromClass(class {
handle: CompletionHandle;
disposed = false;
sequence = 0;
revision = 0;
constructor(readonly view: EditorView) {
this.handle = completionHub.registerSurface({
id: `writer:${documentId}:${crypto.randomUUID()}`,
snapshot: () => ({ documentId, revision: this.revision, text: view.state.doc.toString(), caret: view.state.selection.main.head,
selectionEnd: view.state.selection.ranges.length > 1 ? -1 : view.state.selection.main.anchor,
focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, kind: "prose", language: "markdown" }),
preview: text => {
const sequence = ++this.sequence, caret = view.state.selection.main.head;
queueMicrotask(() => { if (!this.disposed && this.sequence === sequence) view.dispatch({ effects: preview.of(text ? { text, caret } : null) }); });
},
insert: (text, expected) => {
if (this.revision !== expected.revision || view.state.selection.main.head !== expected.caret) return false;
view.dispatch({ changes: { from: expected.caret, insert: text }, selection: { anchor: expected.caret + text.length }, userEvent: "input.complete", annotations: isolateHistory.of("full") });
return true;
},
});
handles.set(view, this.handle);
}
update(update: import("@codemirror/view").ViewUpdate) {
if (update.docChanged) this.revision++;
if (update.docChanged || update.selectionSet || update.focusChanged) this.handle.changed();
}
destroy() { this.disposed = true; this.handle.dispose(); handles.delete(this.view); }
}),
Prec.high(keymap.of([
{ key: "Tab", run: view => !view.composing && !!handles.get(view)?.accept() },
{ key: "Escape", run: view => !!handles.get(view)?.dismiss() },
{ key: "Mod-Alt-Space", run: view => { handles.get(view)?.request(); return true; } },
{ key: "Mod-Alt-ArrowRight", run: view => !!handles.get(view)?.accept(true) },
])),
EditorView.domEventHandlers({ compositionstart: (_event, view) => { handles.get(view)?.dismiss(); } }),
];
}
+58
View File
@@ -0,0 +1,58 @@
export type CompletionDispose = () => void;
export interface CompletionSnapshot {
documentId: string;
revision: string | number;
text: string;
caret: number;
selectionEnd: number;
focused: boolean;
composing?: boolean;
sensitive?: boolean;
readOnly?: boolean;
kind: "prose" | "code";
language?: string;
}
export interface CompletionRequest {
surfaceId: string;
documentId: string;
revision: string | number;
prefix: string;
suffix: string;
kind: "prose" | "code";
language: string;
manual: boolean;
signal: AbortSignal;
}
export interface CompletionProvider {
id: string;
delayMs?: number;
timeoutMs?: number;
complete(request: CompletionRequest, publish: (text: string) => void): Promise<string | null>;
}
export interface CompletionSurface {
id: string;
snapshot(): CompletionSnapshot;
preview(text: string | null): void;
insert(text: string, expected: CompletionSnapshot): boolean;
}
export interface CompletionHandle {
changed(): void;
request(): void;
accept(word?: boolean): boolean;
dismiss(): boolean;
dispose(): void;
}
export interface CompletionTransportRequest {
endpoint: string;
route: "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate";
body?: string;
timeoutMs?: number;
}
export interface CompletionApi {
version: 1;
registerProvider(provider: CompletionProvider): CompletionDispose;
registerSurface(surface: CompletionSurface): CompletionHandle;
registerInput(element: HTMLInputElement | HTMLTextAreaElement, options: { id: string; kind?: "prose" | "code"; sensitive?: boolean }): CompletionHandle;
invalidate(): void;
transport?(request: CompletionTransportRequest, signal: AbortSignal, onLine: (line: string) => void): Promise<void>;
}
+89
View File
@@ -0,0 +1,89 @@
import type { CompletionHandle, CompletionProvider, CompletionSnapshot, CompletionSurface } from "./contracts.ts";
export function eligible(s: CompletionSnapshot): boolean {
if (!s.focused || s.composing || s.sensitive || s.readOnly || s.caret !== s.selectionEnd || s.caret < 0 || s.caret > s.text.length) return false;
if (s.kind === "code") return true;
const before = s.text.slice(0, s.caret), line = before.slice(before.lastIndexOf("\n") + 1);
if (/^\s*\|/.test(line) || /\]\([^)]*$/.test(line) || /<[^>]*$/.test(line)) return false;
if ((line.match(/`/g)?.length ?? 0) % 2) return false;
if (/^---\r?\n/.test(s.text) && !/^---\r?$/m.test(before.slice(before.indexOf("\n") + 1))) return false;
let fence = "";
for (const part of before.split("\n")) {
const match = /^\s{0,3}(`{3,}|~{3,})/.exec(part);
if (match) { if (!fence) fence = match[1]; else if (match[1][0] === fence[0] && match[1].length >= fence.length) fence = ""; }
}
return !fence;
}
function same(a: CompletionSnapshot, b: CompletionSnapshot) {
return a.documentId === b.documentId && a.revision === b.revision && a.caret === b.caret && a.selectionEnd === b.selectionEnd && eligible(b);
}
export class CompletionHub {
private provider?: CompletionProvider;
private surfaces = new Map<string, CompletionHandle>();
private cancelActive?: () => void;
registerProvider(provider: CompletionProvider): () => void {
if (this.provider) throw new Error("Another autocomplete provider is active.");
if (!provider.id || typeof provider.complete !== "function") throw new Error("Invalid autocomplete provider.");
this.provider = provider;
return () => { if (this.provider === provider) { this.provider = undefined; this.invalidate(); } };
}
invalidate() { for (const handle of this.surfaces.values()) handle.dismiss(); }
registerSurface(surface: CompletionSurface): CompletionHandle {
if (!surface.id || this.surfaces.has(surface.id)) throw new Error("Duplicate completion field.");
let timer: ReturnType<typeof setTimeout> | undefined;
let timeout: ReturnType<typeof setTimeout> | undefined;
let controller: AbortController | undefined;
let expected: CompletionSnapshot | undefined;
let candidate = "", disposed = false, serial = 0;
const dismiss = () => {
const visible = !!candidate;
serial++; clearTimeout(timer); clearTimeout(timeout); controller?.abort(); controller = undefined;
candidate = ""; expected = undefined; surface.preview(null);
return visible;
};
const run = async (manual: boolean) => {
if (disposed || !this.provider) return;
const snapshot = surface.snapshot(), provider = this.provider;
if (!eligible(snapshot) || !snapshot.text.slice(0, snapshot.caret).trim()) return;
this.cancelActive?.(); dismiss(); this.cancelActive = dismiss;
const version = serial, abort = new AbortController(); controller = abort; expected = snapshot;
timeout = setTimeout(() => {
if (serial !== version) return;
if (candidate && same(snapshot, surface.snapshot())) abort.abort();
else dismiss();
}, manual ? 10000 : Math.max(300, Math.min(provider.timeoutMs ?? 1000, 5000)));
const publish = (text: string) => {
if (disposed || serial !== version || abort.signal.aborted || this.provider !== provider || !same(snapshot, surface.snapshot())) return;
if (typeof text !== "string" || text.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) return;
candidate = text; surface.preview(text || null);
};
try {
const result = await provider.complete({ surfaceId: surface.id, documentId: snapshot.documentId, revision: snapshot.revision,
prefix: snapshot.text.slice(Math.max(0, snapshot.caret - 3000), snapshot.caret), suffix: snapshot.text.slice(snapshot.caret, snapshot.caret + 600),
kind: snapshot.kind, language: snapshot.language ?? "", manual, signal: abort.signal }, publish);
if (result) publish(result);
} catch { if (serial === version) dismiss(); }
finally { if (serial === version) { clearTimeout(timeout); controller = undefined; } }
};
const handle: CompletionHandle = {
changed: () => {
dismiss();
if (disposed || !this.provider || !eligible(surface.snapshot())) return;
timer = setTimeout(() => { void run(false); }, Math.max(100, Math.min(this.provider.delayMs ?? 200, 1000)));
},
request: () => { dismiss(); void run(true); },
dismiss,
accept: (word = false) => {
if (!candidate || !expected || !same(expected, surface.snapshot())) { dismiss(); return false; }
const text = word ? (candidate.match(/^\s*\S+\s*/u)?.[0] ?? candidate) : candidate;
const snapshot = expected;
dismiss();
return surface.insert(text, snapshot);
},
dispose: () => { if (disposed) return; disposed = true; dismiss(); this.surfaces.delete(surface.id); if (this.cancelActive === dismiss) this.cancelActive = undefined; },
};
this.surfaces.set(surface.id, handle);
return handle;
}
}
export const completionHub = new CompletionHub();
+47
View File
@@ -0,0 +1,47 @@
import { completionHub } from "./hub.ts";
import type { CompletionApi, CompletionHandle } from "./contracts.ts";
export const registerCompletionInput: CompletionApi["registerInput"] = (element, options) => {
let revision = 0, composing = false;
const hint = document.createElement("div");
hint.className = "rs-completion-hint";
hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius,6px);background:var(--rs-bg,#20242a);color:var(--rs-text,#eee);border:1px solid currentColor;font:inherit;white-space:pre-wrap";
hint.hidden = true;
hint.setAttribute("aria-hidden", "true");
document.body.append(hint);
const handle = completionHub.registerSurface({
id: options.id,
snapshot: () => ({ documentId: options.id, revision, text: element.value, caret: element.selectionStart ?? 0, selectionEnd: element.selectionEnd ?? 0,
focused: document.activeElement === element, composing, readOnly: element.readOnly || element.disabled,
sensitive: options.sensitive || element instanceof HTMLInputElement && !["text", "search"].includes(element.type), kind: options.kind ?? "prose" }),
preview: text => { hint.hidden = !text; hint.textContent = text ? `${text}\nTab to accept · Escape to dismiss` : ""; const r = element.getBoundingClientRect(); hint.style.left = `${Math.max(0, Math.min(r.left, innerWidth - 350))}px`; hint.style.top = `${Math.min(r.bottom + 4, innerHeight - 100)}px`; },
insert: (text, expected) => {
if (element.value !== expected.text || element.selectionStart !== expected.caret || element.selectionEnd !== expected.caret) return false;
// The native edit command keeps input and textarea undo history intact.
element.focus();
return document.execCommand("insertText", false, text);
},
});
const changed = () => { revision++; handle.changed(); };
const select = () => handle.dismiss();
const start = () => { composing = true; handle.dismiss(); };
const end = () => { composing = false; changed(); };
const key: EventListener = raw => {
const event = raw as KeyboardEvent;
if (event.isComposing || composing) return;
if (event.key === "Tab" && !event.shiftKey && !event.altKey && !event.ctrlKey && handle.accept()) { event.preventDefault(); event.stopPropagation(); }
else if (event.key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === " ") { event.preventDefault(); handle.request(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === "ArrowRight" && handle.accept(true)) event.preventDefault();
};
element.addEventListener("input", changed); element.addEventListener("keydown", key); element.addEventListener("blur", select);
element.addEventListener("pointerdown", select); element.addEventListener("select", select);
element.addEventListener("compositionstart", start); element.addEventListener("compositionend", end);
const dispose = () => {
handle.dispose(); hint.remove();
element.removeEventListener("input", changed); element.removeEventListener("keydown", key); element.removeEventListener("blur", select);
element.removeEventListener("pointerdown", select); element.removeEventListener("select", select);
element.removeEventListener("compositionstart", start); element.removeEventListener("compositionend", end);
};
return { ...handle, dispose } satisfies CompletionHandle;
};
+51
View File
@@ -0,0 +1,51 @@
import type * as Monaco from "monaco-editor";
import { completionHub } from "./hub";
export function connectMonacoCompletion(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, documentId: string, prose: boolean) {
const model = view.getModel()!;
let composing = false;
const decoration = view.createDecorationsCollection();
if (!document.getElementById("rs-completion-style")) {
const style = document.createElement("style"); style.id = "rs-completion-style";
style.textContent = ".rs-completion-ghost{opacity:.65;font-style:italic;pointer-events:none}";
document.head.append(style);
}
const handle = completionHub.registerSurface({
id: `source:${documentId}:${crypto.randomUUID()}`,
snapshot: () => {
const selection = view.getSelection(), position = view.getPosition();
return { documentId, revision: model.getVersionId(), text: model.getValue(), caret: position ? model.getOffsetAt(position) : 0,
selectionEnd: (view.getSelections()?.length === 1 && selection?.isEmpty()) && position ? model.getOffsetAt(position) : -1,
focused: view.hasTextFocus(), composing, readOnly: view.getOption(monaco.editor.EditorOption.readOnly), kind: prose ? "prose" : "code", language: model.getLanguageId() };
},
preview: text => {
const p = view.getPosition();
decoration.set(text && p ? [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), options: {
after: { content: text.replace(/\r?\n/g, " ↵ "), inlineClassName: "rs-completion-ghost", cursorStops: monaco.editor.InjectedTextCursorStops.None },
showIfCollapsed: true,
} }] : []);
},
insert: (text, expected) => {
if (model.getVersionId() !== expected.revision || !view.getSelection()?.isEmpty()) return false;
const p = model.getPositionAt(expected.caret);
view.pushUndoStop();
const done = view.executeEdits("autocomplete", [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), text }]);
view.setPosition(model.getPositionAt(expected.caret + text.length)); view.pushUndoStop(); return done;
},
});
const listeners = [model.onDidChangeContent(() => handle.changed()), view.onDidChangeCursorSelection(() => handle.changed()),
view.onDidFocusEditorText(() => handle.changed()), view.onDidBlurEditorText(() => handle.dismiss()),
view.onDidCompositionStart(() => { composing = true; handle.dismiss(); }), view.onDidCompositionEnd(() => { composing = false; handle.changed(); }),
view.onKeyDown(event => {
if (composing) return;
const key = event.browserEvent.key;
if (key === "Tab" && !event.shiftKey && !event.ctrlKey && !event.altKey) {
if (view.getDomNode()?.querySelector(".suggest-widget.visible")) { handle.dismiss(); return; }
if (handle.accept()) { event.preventDefault(); event.stopPropagation(); }
} else if (key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === " ") { event.preventDefault(); event.stopPropagation(); handle.request(); }
else if ((event.ctrlKey || event.metaKey) && event.altKey && key === "ArrowRight" && handle.accept(true)) { event.preventDefault(); event.stopPropagation(); }
}),
];
return () => { handle.dispose(); decoration.clear(); listeners.forEach(item => item.dispose()); };
}
+33
View File
@@ -0,0 +1,33 @@
import { EditorState } from '@codemirror/state';
import { EditorView, keymap } from '@codemirror/view';
import { history, historyKeymap, defaultKeymap } from '@codemirror/commands';
import { completionExtension } from './codemirror';
import { connectMonacoCompletion } from './monaco';
import { completionHub } from './hub';
import { ExternalSession } from '../plugins/externalSession';
import { monaco } from '../editor/monacoEnv';
const writer = new EditorView({ parent: document.querySelector('#writer')!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension('fixture')] }) });
const model = monaco.editor.createModel('The ', 'markdown');
const source = monaco.editor.create(document.querySelector('#source') as HTMLElement, { model, theme: 'vs-dark', automaticLayout: true });
const stopSource = connectMonacoCompletion(monaco, source, 'fixture-source', true);
source.setPosition({ lineNumber: 1, column: 5 });
let stopProvider = completionHub.registerProvider({ id: 'fixture', delayMs: 100, complete: async () => 'quiet harbor.' });
Object.assign(window, { completionTest: { writer, source, model, completionHub, stopProvider,
async plugin(code: string) {
stopProvider();
const session = new ExternalSession('test.autocomplete', {
settings: { read: async () => ({ enabled: true, endpoint: 'http://127.0.0.1:8012' }), write: async () => {} },
workspace: { list: async () => [], read: async () => '', write: async () => {} }, assets: { read: async () => new Uint8Array() },
completionTransport: async (request, signal, onLine) => {
if (request.route === '/v1/models') { onLine('{"data":[{"id":"fixture-model"}]}'); return; }
await new Promise(resolve => setTimeout(resolve, 25));
if (!signal.aborted) onLine('data: {"choices":[{"delta":{"content":"quiet harbor."}}]}\n');
},
}, () => {}, () => {});
const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
try { await session.start(await import(/* @vite-ignore */ url)); } finally { URL.revokeObjectURL(url); }
await session.mount('settings', document.querySelector('#plugin') as HTMLElement);
return session;
},
destroy() { stopProvider(); stopSource(); writer.destroy(); source.dispose(); model.dispose(); },
} });
+16
View File
@@ -0,0 +1,16 @@
import { Channel, invoke } from "@tauri-apps/api/core";
import type { CompletionApi } from "./contracts.ts";
export const completionTransport: NonNullable<CompletionApi["transport"]> = async (request, signal, onLine) => {
if (signal.aborted) throw new DOMException("Cancelled", "AbortError");
const id = crypto.randomUUID();
let parseError: unknown;
const channel = new Channel<string>();
channel.onmessage = line => {
if (signal.aborted || parseError) return;
try { onLine(line); } catch (error) { parseError = error; cancel(); }
};
const cancel = () => { void invoke("completion_cancel", { id }).catch(() => {}); };
signal.addEventListener("abort", cancel, { once: true });
try { await invoke("completion_request", { id, request, onLine: channel }); if (parseError) throw parseError; }
finally { signal.removeEventListener("abort", cancel); }
};
+4
View File
@@ -6,6 +6,7 @@
import { editorSession } from "./sessions"; import { editorSession } from "./sessions";
import { registerSelection } from "./selection"; import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome"; import { monacoChrome } from "./monacoChrome";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu"; import { markdownMenu } from "./markdownMenu";
import type { TableContextActions } from "./tableCellActions"; import type { TableContextActions } from "./tableCellActions";
@@ -85,6 +86,7 @@
let releaseSelection: (() => void) | undefined; let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined; let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined; let releaseDrop: (() => void) | undefined;
let releaseCompletion: (() => void) | undefined;
const listeners: { dispose(): void }[] = []; const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco }) => { void import("./monacoEnv").then(({ monaco }) => {
if (cancelled || !el.isConnected) { if (cancelled || !el.isConnected) {
@@ -144,6 +146,7 @@
listeners.push(model.onDidChangeContent(() => menu?.close(false))); listeners.push(model.onDidChangeContent(() => menu?.close(false)));
} }
const documentId = untrack(() => buffer.id); const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || ""); releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view); if (session.view) view.restoreViewState(session.view);
ready += 1; ready += 1;
@@ -160,6 +163,7 @@
const view = editor; const view = editor;
if (view && session) session.view = view.saveViewState(); if (view && session) session.view = view.saveViewState();
contentListener?.dispose(); contentListener?.dispose();
releaseCompletion?.();
releaseSelection?.(); releaseSelection?.();
menu?.destroy(); menu?.destroy();
releaseDrop?.(); releaseDrop?.();
+2
View File
@@ -24,6 +24,7 @@
import type { TableContextActions } from "./tableCellActions"; import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu"; import { markdownMenu } from "./markdownMenu";
import { tableNavigation } from "./tableNavigation"; import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
type Props = { type Props = {
buffer: OpenBuffer; buffer: OpenBuffer;
@@ -138,6 +139,7 @@
if (model.getValue() !== lastValue) model.setValue(lastValue); if (model.getValue() !== lastValue) model.setValue(lastValue);
model.pushStackElement(); model.pushStackElement();
const extensions = [ const extensions = [
completionExtension(current.id),
EditorState.lineSeparator.of(model.getEOL()), EditorState.lineSeparator.of(model.getEOL()),
markdown({ base: markdownLanguage, extensions: [noteFormats] }), markdown({ base: markdownLanguage, extensions: [noteFormats] }),
// Rich cell serialization can change delimiters away from the caret. // Rich cell serialization can change delimiters away from the caret.
+4 -1
View File
@@ -208,7 +208,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
return [imageSource, StateField.define<DecorationSet>({ return [imageSource, StateField.define<DecorationSet>({
create: build, create: build,
update(value, transaction) { update(value, transaction) {
return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state, value.map(transaction.changes)) : value; return transaction.docChanged || transaction.selection
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource))
? build(transaction.state, value.map(transaction.changes)) : value;
}, },
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({ provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
filter: (_from, _to, decoration) => decoration.spec.atomic === true, filter: (_from, _to, decoration) => decoration.spec.atomic === true,
+2
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { loadMarks } from "$lib/workspace/marks"; import { loadMarks } from "$lib/workspace/marks";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import type { TreeEntry } from "$lib/workspace/types"; import type { TreeEntry } from "$lib/workspace/types";
type Props = { type Props = {
@@ -20,6 +21,7 @@
<div class="pane"> <div class="pane">
<div class="pane-label">Bookmarks</div> <div class="pane-label">Bookmarks</div>
<BrowserSlot kind="bookmarks" />
{#if bookmarks.length === 0} {#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p> <p class="placeholder">Right-click a file and choose Bookmark.</p>
{:else} {:else}
+121
View File
@@ -0,0 +1,121 @@
<script lang="ts">
import { tick, untrack } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { pluginHost } from "$lib/plugins/registry";
import { pluginEditors, pluginView, pluginSplits, externalErrors, pluginServiceError, selectPluginEditor, closePluginEditor, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
import TabBar from "./TabBar.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import WindowControls from "$lib/ui/WindowControls.svelte";
let error = $state("");
let opening = $state(false);
let hadTabs = false;
const browser = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
const tabs = $derived<WorkbenchTab[]>($pluginEditors.map(view => ({
id: view.key, relPath: view.key, name: view.title, title: view.title,
pinned: !!view.pinned, draggable: view.draggable, icon: "globe", iconImage: view.iconImage, panelId: `plugin-editor-${view.key}`,
})));
const active = $derived($pluginView?.key ?? null);
const split = $derived($pluginSplits.find(tree => active && containsPane(tree, active)));
const bounds = $derived(split ? paneBounds(split) : active ? paneBounds(active) : {});
const message = $derived(error || $externalErrors["runestone.browser"] || $pluginServiceError);
$effect(() => {
if (tabs.length) hadTabs = true;
else if (hadTabs) void tick().then(() => {
if (!untrack(() => $pluginEditors.length)) void getCurrentWindow().destroy().catch(reason => error = String(reason));
});
});
function select(path: string) {
const view = $pluginEditors.find(view => view.key === path);
if (view) selectPluginEditor(view);
}
function move(path: string, index: number) {
pluginEditors.update(views => {
const from = views.findIndex(view => view.key === path);
if (from < 0) return views;
const ordered = [...views], [view] = ordered.splice(from, 1);
ordered.splice(Math.max(0, Math.min(index, ordered.length)), 0, view);
return ordered;
});
}
function close(path: string, scope: TabCloseScope = "one") {
for (const tab of tabsToClose(tabs, path, scope)) closePluginEditor(tab.id);
}
function actions(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabActions(view) : [];
}
function dragData(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabDragData(view) : undefined;
}
async function receive(data: string, index: number) {
try { await dropPluginTab(data); if ($pluginView) move($pluginView.key, index); error = ""; }
catch (reason) { error = String(reason); }
}
async function newTab() {
if (opening || !browser?.newTab) return;
opening = true;
try { await browser.newTab(); error = ""; } catch (reason) { error = String(reason); }
finally { opening = false; }
}
function keydown(event: KeyboardEvent) {
if (event.defaultPrevented || !(event.ctrlKey || event.metaKey) || event.shiftKey || event.altKey) return;
if (event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
if (event.key.toLowerCase() === "t") { event.preventDefault(); void newTab(); }
if (event.key.toLowerCase() === "w" && active) { event.preventDefault(); close(active); }
if (event.key.toLowerCase() === "f" && $pluginView && findPluginEditor($pluginView)) event.preventDefault();
}
</script>
<svelte:window onkeydown={keydown} />
<div class="browser-window" role="application" aria-label="RuneStone browser">
<header class="header" data-tauri-drag-region>
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
<IconButton icon="plus" label="New browser tab (Ctrl T)" disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<div class="window-drag-space" data-tauri-drag-region></div>
<WindowControls onError={message => error = message} />
</header>
{#if message}<p class="error" role="alert">{message}</p>{/if}
<main class="pages">
{#each $pluginEditors as view (view.key)}
{@const position = bounds[view.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Input selects its browser pane.) -->
<div class="pane" class:inactive={!position} class:split={!!split} class:focused={active === view.key}
style:left={`${position?.left ?? 0}%`} style:top={`${position?.top ?? 0}%`}
style:width={`${position?.width ?? 100}%`} style:height={`${position?.height ?? 100}%`}
onfocusin={() => { if (active !== view.key) select(view.key); }}
onpointerdown={() => { if (active !== view.key) select(view.key); }}>
{#if split && position}
<TabBar tabs={tabs.filter(tab => tab.id === view.key)} activePath={active}
onSelect={select} onClose={close} onCloseTabs={close} onMove={move} onPin={pinPluginEditor}
fileActions={() => []} tabActions={actions} tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
{/if}
<PluginEditor {view} />
</div>
{/each}
{#if !tabs.length}<p class="placeholder">{browser ? "Open a browser tab with the + button." : "Loading browser…"}</p>{/if}
</main>
</div>
<style>
.browser-window { height: 100vh; display: flex; flex-direction: column; background: var(--rs-bg); }
.header { display: flex; align-items: center; height: 36px; flex-shrink: 0; background: var(--rs-bg-elevated); border-bottom: 1px solid var(--rs-border); }
.header :global(.tabs) { flex: 0 1 auto; min-width: 80px; height: 100%; border-bottom: 0; }
.window-drag-space { flex: 1; min-width: 40px; align-self: stretch; }
.pages { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
.pane.inactive { display: none; }
.pane.split { border: 1px solid var(--rs-border); }
.pane.split.focused { border-color: var(--rs-accent); }
.placeholder { padding: 24px; color: var(--rs-text-dim); }
.error { margin: 0; padding: 8px; color: var(--rs-error); }
</style>
+4 -1
View File
@@ -26,11 +26,13 @@
onOpenWorkspace: () => void; onOpenWorkspace: () => void;
onNewFile: () => void; onNewFile: () => void;
onQuickOpen: () => void; onQuickOpen: () => void;
onOpenBrowser?: () => void;
browserOpening?: boolean;
hasWorkspace: boolean; hasWorkspace: boolean;
tableActions?: TableContextActions; tableActions?: TableContextActions;
}; };
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props(); let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
let previewMode = $state<"split" | "preview">("split"); let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>(); let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null); let titleFocusId = $state<string | null>(null);
@@ -94,6 +96,7 @@
<h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1> <h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1>
<p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p> <p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p>
<div class="welcome-actions"> <div class="welcome-actions">
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button> <button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if hasWorkspace} {#if hasWorkspace}
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button> <button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
+14 -1
View File
@@ -559,7 +559,20 @@
function menuItems(entry: TreeEntry | null): MenuItem[] { function menuItems(entry: TreeEntry | null): MenuItem[] {
if (!entry) { if (!entry) {
return paneMenuItems(""); return [
...paneMenuItems(""),
{ kind: "sep" },
{
kind: "action",
label: "Show in Explorer",
icon: "folder",
run: () => {
void workspaceReveal("").catch((err) => {
error = err instanceof Error ? err.message : String(err);
});
},
},
];
} }
const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry); const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry);
const multiple = entries.length > 1; const multiple = entries.length > 1;
+25 -6
View File
@@ -1,22 +1,28 @@
<script lang="ts"> <script lang="ts">
import PluginManager from "$lib/plugins/PluginManager.svelte"; import PluginManager from "$lib/plugins/PluginManager.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import PluginSettings from "$lib/plugins/PluginSettings.svelte";
import { installedPlugins, pluginTools } from "$lib/plugins/external";
import { pluginHost } from "$lib/plugins/registry";
import { onMount, untrack } from "svelte"; import { onMount, untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte"; import Icon from "$lib/ui/Icon.svelte";
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte"; import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings"; import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
import { version, license } from "../../../package.json"; import { version, license } from "../../../package.json";
let { settings, help = false, onSave, onClose }: { let { settings, help = false, standalone = false, windowError = "", onSave, onClose }: {
settings: AppSettings; settings: AppSettings;
help?: boolean; help?: boolean;
standalone?: boolean;
windowError?: string;
onSave: (value: AppSettings) => void; onSave: (value: AppSettings) => void;
onClose: () => void; onClose: () => void;
} = $props(); } = $props();
type Section = "general" | "plugins" | "about"; type Section = string;
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [ const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" }, { id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" }, { id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
]; ];
let section = $state<Section>(untrack(() => help ? "about" : "general")); let section = $state<Section>(untrack(() => help ? "about" : "general"));
let query = $state(""); let query = $state("");
@@ -24,8 +30,15 @@
let message = $state(""); let message = $state("");
let error = $state(""); let error = $state("");
let dialog: HTMLDialogElement; let dialog: HTMLDialogElement;
const matches = $derived(sections.filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase()))); const browserEnabled = $derived.by(() => { void $pluginHost; return !!pluginHost.get("browser"); });
const pluginSections = $derived($pluginTools.filter(tool => tool.surface === "settings").map(tool => ({
id: `plugin:${tool.owner}:${tool.id}`, owner: tool.owner, view: tool.id,
label: tool.title, icon: "settings" as const,
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
})));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: "Browser", icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]); const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
$effect(() => { seconds = settings.autosaveSeconds; }); $effect(() => { seconds = settings.autosaveSeconds; });
onMount(() => { onMount(() => {
@@ -54,7 +67,7 @@
function trapFocus(event: KeyboardEvent) { function trapFocus(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest("dialog") !== dialog) return; if (event.target instanceof Element && event.target.closest("dialog") !== dialog) return;
if (event.key !== "Tab") return; if (event.key !== "Tab") return;
const controls = [...dialog.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), summary")] const controls = [...dialog.querySelectorAll<HTMLElement>("button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), a[href], summary, [tabindex]:not([tabindex='-1'])")]
.filter(element => element.getClientRects().length > 0); .filter(element => element.getClientRects().length > 0);
const first = controls[0], last = controls.at(-1); const first = controls[0], last = controls.at(-1);
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); } if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); }
@@ -62,7 +75,7 @@
} }
</script> </script>
<dialog bind:this={dialog} class:help aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}> <dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
<header> <header>
<h1 id="settings-title">{help ? "Help and about" : "Settings"}</h1> <h1 id="settings-title">{help ? "Help and about" : "Settings"}</h1>
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} /> <IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
@@ -81,6 +94,7 @@
</aside> </aside>
{/if} {/if}
<div class="content"> <div class="content">
{#if windowError}<p class="error" role="alert">{windowError}</p>{/if}
{#if !selected} {#if !selected}
<h2>No settings found</h2> <h2>No settings found</h2>
<p>Try “save”, “plug-ins”, or “help”.</p> <p>Try “save”, “plug-ins”, or “help”.</p>
@@ -105,6 +119,10 @@
<p class="saved" role="status">{message}</p> <p class="saved" role="status">{message}</p>
{:else if selected.id === "plugins"} {:else if selected.id === "plugins"}
<PluginManager /> <PluginManager />
{:else if selected.id === "browser"}
<BrowserSlot kind="settings" />
{:else if selectedPlugin}
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
{:else} {:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div> <div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div>
<div class="card help-card"> <div class="card help-card">
@@ -121,6 +139,7 @@
<style> <style>
dialog { width: min(920px, calc(100vw - 32px)); height: min(650px, calc(100dvh - 32px)); max-width: none; max-height: none; padding: 0; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 12px; box-shadow: 0 24px 80px #0008; overflow: hidden; } dialog { width: min(920px, calc(100vw - 32px)); height: min(650px, calc(100dvh - 32px)); max-width: none; max-height: none; padding: 0; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 12px; box-shadow: 0 24px 80px #0008; overflow: hidden; }
dialog::backdrop { background: #0008; } dialog::backdrop { background: #0008; }
dialog.standalone { width: 100vw; height: 100dvh; margin: 0; border: 0; border-radius: 0; box-shadow: none; }
dialog.help { width: min(650px, calc(100vw - 32px)); } dialog.help { width: min(650px, calc(100vw - 32px)); }
header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); } header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
h1 { font-size: 14px; font-weight: 600; margin: 0; } h1 { font-size: 14px; font-weight: 600; margin: 0; }
+35
View File
@@ -0,0 +1,35 @@
<script lang="ts">
import { onMount } from "svelte";
import { isTauri } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window";
import SettingsDialog from "./SettingsDialog.svelte";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
let error = $state("");
function read() {
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
}
onMount(() => {
read();
const sync = (event: StorageEvent) => {
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) read();
};
window.addEventListener("storage", sync);
window.addEventListener("focus", read);
return () => { window.removeEventListener("storage", sync); window.removeEventListener("focus", read); };
});
function save(next: AppSettings) {
saveSettings(localStorage, next);
settings = { ...next };
error = "";
}
async function close() {
if (!isTauri()) { window.location.assign("/"); return; }
try { await getCurrentWindow().close(); }
catch (reason) { error = `Could not close settings: ${String(reason)}`; }
}
</script>
<SettingsDialog {settings} standalone windowError={error} onSave={save} onClose={() => void close()} />
+76 -13
View File
@@ -2,21 +2,26 @@
import { onDestroy, tick } from "svelte"; import { onDestroy, tick } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu"; import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons"; import { actionIcons } from "$lib/ui/actionIcons";
import TabIcon from "$lib/ui/TabIcon.svelte";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions"; import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { OpenBuffer } from "$lib/workspace/types"; import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
type Props = { type Props = {
tabs: OpenBuffer[]; tabs: WorkbenchTab[];
activePath: string | null; activePath: string | null;
onSelect: (relPath: string) => void; onSelect: (relPath: string) => void;
onClose: (relPath: string) => void; onClose: (relPath: string) => void;
onMove: (relPath: string, index: number) => void; onMove: (relPath: string, index: number) => void;
onCloseTabs: (relPath: string, scope: TabCloseScope) => void; onCloseTabs: (relPath: string, scope: TabCloseScope) => void;
onPin: (relPath: string) => void; onPin: (relPath: string) => void;
fileActions: (tab: OpenBuffer) => ActionMenuItem[]; fileActions: (tab: WorkbenchTab) => ActionMenuItem[];
tabActions?: (tab: WorkbenchTab) => ActionMenuItem[];
tabDragData?: (tab: WorkbenchTab) => string | undefined;
onDropTab?: (data: string, index: number) => void;
}; };
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions }: Props = $props(); let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab }: Props = $props();
const transferType = "application/x-runestone-tab";
let bar: HTMLDivElement; let bar: HTMLDivElement;
let dragged = $state<string | null>(null); let dragged = $state<string | null>(null);
let dropBefore = $state<string | null>(null); let dropBefore = $state<string | null>(null);
@@ -27,6 +32,48 @@
let menu: HTMLElement | undefined; let menu: HTMLElement | undefined;
let menuAnchor: HTMLButtonElement | undefined; let menuAnchor: HTMLButtonElement | undefined;
let menuPath = $state<string | null>(null); let menuPath = $state<string | null>(null);
let receiving = $state(false);
function startTabTransfer(event: DragEvent, tab: WorkbenchTab) {
const data = tabDragData(tab);
if (!data || !event.dataTransfer) { event.preventDefault(); return; }
cancelDrag(); closeMenu();
dragged = tab.relPath;
suppressClick = true;
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData(transferType, data);
}
function transferIndex(x: number) {
const others = [...bar.querySelectorAll<HTMLElement>(".tab")].filter(row => row.dataset.path !== dragged);
const before = others.findIndex(row => { const bounds = row.getBoundingClientRect(); return x < bounds.left + bounds.width / 2; });
dropBefore = before < 0 ? null : others[before].dataset.path!;
dropAfter = before < 0 ? others.at(-1)?.dataset.path ?? null : null;
return before < 0 ? others.length : before;
}
function dragOver(event: DragEvent) {
if (!event.dataTransfer?.types.includes(transferType) || (!dragged && !onDropTab)) return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
receiving = true;
const bounds = bar.getBoundingClientRect();
if (event.clientX < bounds.left + 28) bar.scrollLeft -= 10;
else if (event.clientX > bounds.right - 28) bar.scrollLeft += 10;
transferIndex(event.clientX);
}
function finishTabTransfer() { dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; }
function dropTab(event: DragEvent) {
const data = event.dataTransfer?.getData(transferType);
if (!data) return;
event.preventDefault(); event.stopPropagation();
const path = dragged, index = transferIndex(event.clientX);
finishTabTransfer();
if (path) void move(path, index);
else onDropTab?.(data, index);
}
$effect(() => { $effect(() => {
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu(); if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
@@ -78,8 +125,11 @@
closing("Close others", "others"), closing("Close others", "others"),
closing("Close tabs after", "after"), closing("Close tabs after", "after"),
closing("Close all", "all"), closing("Close all", "all"),
{ separator: true }, ...(tabs[index].pinned !== undefined ? [
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin", run: run(() => onPin(path)) }, { separator: true as const },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin" as const, run: run(() => onPin(path)) },
] : []),
...wrapActions(tabActions(tabs[index])),
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []), ...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
{ separator: true }, { separator: true },
{ label: "Move tab", icon: "swap", children: [ { label: "Move tab", icon: "swap", children: [
@@ -197,8 +247,10 @@
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} /> <svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<div bind:this={bar} class="tabs" role="tablist" aria-label="Open files"> <div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label="Working tabs" tabindex="-1"
{#each tabs as tab (tab.relPath)} ondragover={dragOver} ondrop={dropTab}
ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}>
{#each tabs as tab (tab.id)}
<div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath} <div class="tab" data-path={tab.relPath} class:active={tab.relPath === activePath} class:dragging={dragged === tab.relPath}
class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}> class:drop-before={dropBefore === tab.relPath} class:drop-after={dropAfter === tab.relPath}>
<button <button
@@ -207,19 +259,23 @@
data-path={tab.relPath} data-path={tab.relPath}
tabindex={tab.relPath === activePath ? 0 : -1} tabindex={tab.relPath === activePath ? 0 : -1}
aria-selected={tab.relPath === activePath} aria-selected={tab.relPath === activePath}
aria-controls={tab.panelId}
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined} aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight" aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.kind === "empty" ? tab.name : tab.relPath}\nDrag to reorder. Right-click for tab actions.`} title={`${tab.title}\n${tab.draggable ? "Drag to reorder or move to another RuneStone window." : "Drag to reorder."} Right-click for tab actions.`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }} onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => startDrag(event, tab.relPath)} onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
ondragstart={(event) => event.preventDefault()} draggable={!!tab.draggable}
ondragstart={(event) => startTabTransfer(event, tab)}
ondragend={finishTabTransfer}
onkeydown={(event) => onKey(event, tab.relPath)} onkeydown={(event) => onKey(event, tab.relPath)}
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }} oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
onmousedown={onMiddleDown} onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)} onmouseup={(event) => onMiddleUp(event, tab.relPath)}
> >
{#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if} {#if tab.pinned}<svg class="pin" viewBox="0 0 24 24" aria-hidden="true">{@html actionIcons.pin}</svg>{/if}
{tab.name}{tab.contents !== tab.saved ? " •" : ""} <TabIcon image={tab.iconImage} icon={tab.icon} />
<span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span>
</button> </button>
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if} {#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if}
<button <button
@@ -246,6 +302,8 @@
background: var(--rs-bg-elevated); background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border); border-bottom: 1px solid var(--rs-border);
} }
.tabs:empty { min-width: 80px; }
.tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); }
.tab { .tab {
position: relative; position: relative;
@@ -281,6 +339,9 @@
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); } .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.tab > button:first-child { .tab > button:first-child {
display: flex;
align-items: center;
gap: 7px;
border-radius: var(--rs-control-radius); border-radius: var(--rs-control-radius);
touch-action: none; touch-action: none;
user-select: none; user-select: none;
@@ -302,7 +363,9 @@
color: var(--rs-text-strong); color: var(--rs-text-strong);
} }
.pin { width: 14px; height: 14px; margin-right: 6px; vertical-align: -2px; fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; } .tab-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tab :global(svg) { width: 16px; height: 16px; flex-shrink: 0; }
.pin { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; }
.close { .close {
border: 0; border: 0;
+164 -20
View File
@@ -1,25 +1,29 @@
<script lang="ts"> <script lang="ts">
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import PluginTools from "$lib/plugins/PluginTools.svelte"; import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
import PluginEditor from "$lib/plugins/PluginEditor.svelte"; import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import PluginEditorTab from "$lib/plugins/PluginEditorTab.svelte"; import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen } from "$lib/plugins/external"; import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, tick } from "svelte"; import { onMount, tick } from "svelte";
import { selectedEditorText } from "$lib/editor/selection"; import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts"; import type { Contributions } from "$lib/plugins/contracts";
import { isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import { confirm } from "@tauri-apps/plugin-dialog"; import { confirm } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener"; import { openUrl } from "@tauri-apps/plugin-opener";
import { Documents } from "$lib/workspace/documents"; import { Documents } from "$lib/workspace/documents";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions"; import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import { orderWorkbenchTabs, type WorkbenchTab } from "$lib/workspace/workbenchTabs";
import type { ActionMenuItem } from "$lib/ui/actionMenu"; import type { ActionMenuItem } from "$lib/ui/actionMenu";
import { requestText } from "$lib/workspace/dialogs.svelte"; import { requestText } from "$lib/workspace/dialogs.svelte";
import TextDialog from "./TextDialog.svelte"; import TextDialog from "./TextDialog.svelte";
import QuickOpen from "./QuickOpen.svelte"; import QuickOpen from "./QuickOpen.svelte";
import WorkspacePicker from "./WorkspacePicker.svelte"; import WorkspacePicker from "./WorkspacePicker.svelte";
import SettingsDialog from "./SettingsDialog.svelte"; import SettingsDialog from "./SettingsDialog.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
import FileTree from "./FileTree.svelte"; import FileTree from "./FileTree.svelte";
import EditorPane from "./EditorPane.svelte"; import EditorPane from "./EditorPane.svelte";
@@ -55,6 +59,15 @@
let workspace = $state<WorkspaceInfo | null>(null); let workspace = $state<WorkspaceInfo | null>(null);
let workspacePicker: WorkspacePicker; let workspacePicker: WorkspacePicker;
let preferences = $state<"settings" | "help" | null>(null); let preferences = $state<"settings" | "help" | null>(null);
let openingSettings = false;
async function openSettings() {
if (!desktop) { preferences = "settings"; return; }
if (openingSettings) return;
openingSettings = true;
try { await invoke("settings_open_window"); }
catch (reason) { error = `Could not open settings: ${String(reason)}`; }
finally { openingSettings = false; }
}
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS }); let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
let settingsReady = $state(false); let settingsReady = $state(false);
let workspaceAnchor: HTMLDivElement | undefined = $state(); let workspaceAnchor: HTMLDivElement | undefined = $state();
@@ -81,6 +94,28 @@
let terminalDock: TerminalSlot | undefined = $state(); let terminalDock: TerminalSlot | undefined = $state();
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
const terminalEnabled = $derived(!!terminalContribution); const terminalEnabled = $derived(!!terminalContribution);
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
let browserOpening = $state(false);
async function openBrowser() {
if (browserOpening || !browserContribution?.newTab) return;
browserOpening = true;
const current = documents;
const empty = !editorPluginVisible && buffer?.kind === "empty" ? buffer : null;
const existing = new Set($pluginEditors.map(view => view.key));
try {
await browserContribution.newTab();
const opened = $pluginView;
if (empty && documents === current && current?.buffers.some(tab => tab.id === empty.id && tab.kind === "empty")
&& opened?.placement === "editor" && !existing.has(opened.key)) {
tabOrder = workingTabs.map(tab => tab.id === (empty.tabId ?? empty.id) ? opened.key : tab.id).filter((id, index, order) => order.indexOf(id) === index);
if (empty.pinned && !opened.pinned) pinPluginEditor(opened.key);
current.close(empty.relPath);
}
error = null;
}
catch (reason) { error = String(reason); }
finally { browserOpening = false; }
}
$effect(() => { $effect(() => {
if (!terminalEnabled) { if (!terminalEnabled) {
@@ -113,6 +148,41 @@
let centerStack: HTMLElement | undefined = $state(); let centerStack: HTMLElement | undefined = $state();
const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive); const editorPluginVisible = $derived($pluginView?.placement === "editor" && $pluginEditorActive);
type EditorTab = WorkbenchTab & ({ buffer: OpenBuffer } | { plugin: OpenPluginView });
let tabOrder = $state<string[]>([]);
const availableTabs = $derived<EditorTab[]>([
...tabs.map(tab => ({
id: tab.tabId ?? tab.id, relPath: tab.relPath, name: tab.name,
title: tab.kind === "empty" ? tab.name : tab.relPath,
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, buffer: tab,
})),
...$pluginEditors.map(plugin => ({
id: plugin.key, relPath: `plugin:${plugin.key}`, name: plugin.title,
title: plugin.document?.path ?? plugin.title,
icon: plugin.icon === "file" ? "files" as const : plugin.icon ?? "puzzle" as const,
iconImage: plugin.iconImage,
panelId: `plugin-editor-${plugin.key}`, pinned: !!plugin.pinned, draggable: plugin.draggable, plugin,
})),
]);
const workingTabs = $derived(orderWorkbenchTabs(availableTabs, tabOrder));
function workingTabDragData(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabDragData(view) : undefined;
}
async function receiveTab(data: string, index: number) {
try {
await dropPluginTab(data);
if ($pluginView?.placement === "editor") moveWorkingTab(`plugin:${$pluginView.key}`, index);
error = null;
} catch (reason) { error = String(reason); }
}
const activeTabPath = $derived(editorPluginVisible && $pluginView ? `plugin:${$pluginView.key}` : activePath);
const activeSplit = $derived($pluginSplits.find(tree => $pluginView && containsPane(tree, $pluginView.key)));
const pluginBounds = $derived(activeSplit ? paneBounds(activeSplit) : $pluginView ? paneBounds($pluginView.key) : {});
$effect(() => {
const order = workingTabs.map(tab => tab.id);
if (order.length !== tabOrder.length || order.some((id, index) => id !== tabOrder[index])) tabOrder = order;
});
const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved); const dirty = $derived(buffer !== null && buffer.contents !== buffer.saved);
const isIde = $derived(view === "Ide"); const isIde = $derived(view === "Ide");
const outlineItems = $derived( const outlineItems = $derived(
@@ -213,6 +283,38 @@
status = documents?.active?.kind === "empty" ? "New tab" : relPath; status = documents?.active?.kind === "empty" ? "New tab" : relPath;
} }
function selectWorkingTab(path: string) {
const tab = workingTabs.find(tab => tab.relPath === path);
if (!tab) return;
if ("plugin" in tab) selectPluginEditor(tab.plugin);
else selectTab(path);
}
function moveWorkingTab(path: string, index: number) {
const from = workingTabs.findIndex(tab => tab.relPath === path);
if (from < 0 || !Number.isInteger(index)) return;
const ordered = [...workingTabs];
const [tab] = ordered.splice(from, 1);
const destination = Math.max(0, Math.min(index, ordered.length));
ordered.splice(destination, 0, tab);
tabOrder = ordered.map(tab => tab.id);
if ("buffer" in tab) documents?.move(path, ordered.slice(0, destination).filter(tab => "buffer" in tab).length);
}
function workingTabFileActions(item: WorkbenchTab): ActionMenuItem[] {
const tab = workingTabs.find(tab => tab.id === item.id);
return tab && "buffer" in tab ? tabFileActions(tab.buffer) : [];
}
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
const tab = workingTabs.find(tab => tab.id === item.id);
return tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
}
function pinWorkingTab(path: string) {
const tab = workingTabs.find(tab => tab.relPath === path);
if (tab && "plugin" in tab) pinPluginEditor(tab.plugin.key);
else documents?.togglePin(path);
}
function newTab() { function newTab() {
cancelPluginDocumentOpen(); cancelPluginDocumentOpen();
if (switching) return; if (switching) return;
@@ -231,19 +333,27 @@
async function closeTabs(path: string, scope: TabCloseScope) { async function closeTabs(path: string, scope: TabCloseScope) {
const current = documents; const current = documents;
if (!current || closingTabs || switching) return; if (closingTabs || switching) return;
closingTabs = true; closingTabs = true;
try { try {
const targets = tabsToClose(current.buffers, path, scope); const targets = tabsToClose(workingTabs, path, scope);
for (const target of targets) { for (const target of targets) {
if (documents !== current || switching) break; if (documents !== current || switching) break;
const tab = current.buffers.find(item => item.id === target.id); const tab = "buffer" in target ? current?.buffers.find(item => item.id === target.buffer.id) : undefined;
if ("buffer" in target) {
if (!tab || (scope !== "one" && tab.pinned)) continue; if (!tab || (scope !== "one" && tab.pinned)) continue;
const contents = tab.contents; const contents = tab.contents;
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break; if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break;
if (documents !== current || switching || tab.contents !== contents) break; if (documents !== current || switching || tab.contents !== contents) break;
if (scope !== "one" && tab.pinned) continue; if (scope !== "one" && tab.pinned) continue;
current.close(tab.relPath); }
const index = workingTabs.findIndex(item => item.id === target.id);
if (index < 0) continue;
const selected = workingTabs[index].relPath === activeTabPath
? (workingTabs[index + 1] ?? workingTabs[index - 1])?.relPath : activeTabPath;
if ("plugin" in target) closePluginEditor(target.plugin.key);
else if (tab) current?.close(tab.relPath);
if (selected && selected !== activeTabPath) selectWorkingTab(selected);
} }
} catch (err) { error = String(err); } } catch (err) { error = String(err); }
finally { closingTabs = false; } finally { closingTabs = false; }
@@ -437,7 +547,7 @@
function onPreferencesKeydown(event: KeyboardEvent) { function onPreferencesKeydown(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return; if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") { if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") {
event.preventDefault(); event.stopPropagation(); preferences = "settings"; event.preventDefault(); event.stopPropagation(); void openSettings();
} }
if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) { if (event.key === "F1" && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
event.preventDefault(); event.stopPropagation(); preferences = "help"; event.preventDefault(); event.stopPropagation(); preferences = "help";
@@ -445,7 +555,11 @@
} }
function onKeydown(event: KeyboardEvent) { function onKeydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return; if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f" && editorPluginVisible && $pluginView) {
if (findPluginEditor($pluginView)) { event.preventDefault(); return; }
}
const action = pluginHost.get("terminal")?.shortcut(event); const action = pluginHost.get("terminal")?.shortcut(event);
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock"); const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) { if (action && (["toggle", "new", "split", "window"].includes(action) || terminalTarget)) {
@@ -488,7 +602,7 @@
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") { if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "w") {
event.preventDefault(); event.preventDefault();
if (editorPluginVisible) { if (editorPluginVisible) {
if ($pluginView) closePluginEditor($pluginView.key); if (activeTabPath) void closeTab(activeTabPath);
} else if (activePath) { } else if (activePath) {
closeTab(activePath); closeTab(activePath);
} }
@@ -561,7 +675,10 @@
async function openLink(kind: "md" | "wiki", target: string) { async function openLink(kind: "md" | "wiki", target: string) {
if (/^(https?:\/\/|mailto:)/i.test(target)) { if (/^(https?:\/\/|mailto:)/i.test(target)) {
try { await openUrl(target); } catch (err) { error = String(err); } try {
if (/^https?:\/\//i.test(target) && await pluginHost.get("browser")?.open(target)) return;
await openUrl(target);
} catch (err) { error = String(err); }
return; return;
} }
const rels = linkCandidates(activePath ?? "", target, kind); const rels = linkCandidates(activePath ?? "", target, kind);
@@ -718,17 +835,17 @@
/> />
</div> </div>
<div class="header-center" data-tauri-drag-region> <div class="header-center" data-tauri-drag-region>
{#if tabs.length > 0} <TabBar tabs={workingTabs} activePath={activeTabPath} onSelect={selectWorkingTab} onClose={closeTab}
<TabBar {tabs} activePath={editorPluginVisible ? null : activePath} onSelect={selectTab} onClose={closeTab} onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={pinWorkingTab}
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={(path) => documents?.togglePin(path)} fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
fileActions={tabFileActions} onMove={(path, index) => documents?.move(path, index)} /> tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
{/if}
<PluginEditorTab />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} /> <IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
<PluginAccessMenu surface="open" />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if} {#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div> </div>
<div class="header-right" data-tauri-drag-region> <div class="header-right" data-tauri-drag-region>
<PluginTools /> <PluginTools />
<PluginAccessMenu surface="commands" />
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} /> <IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if} {#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
<IconButton <IconButton
@@ -744,7 +861,7 @@
<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={$pluginNavigation.length === 0}> <nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={$pluginNavigation.length === 0}>
{#each $pluginNavigation as item (`${item.owner}:${item.id}`)} {#each $pluginNavigation as item (`${item.owner}:${item.id}`)}
<IconButton <IconButton
icon={item.icon === "list" || item.icon === "kanban" ? item.icon : "puzzle"} icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" ? item.icon : "puzzle"}
label={item.title} label={item.title}
side="right" side="right"
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)} active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
@@ -757,7 +874,7 @@
<aside class="left"> <aside class="left">
<div class="left-body"> <div class="left-body">
{#if !workspace} {#if !workspace}
<p class="placeholder">No folder is open.</p> {#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">No folder is open.</p>{/if}
{:else} {:else}
<div class="left-stack"> <div class="left-stack">
<div class="left-layer" class:shown={leftView === "files"}> <div class="left-layer" class:shown={leftView === "files"}>
@@ -793,7 +910,7 @@
</div> </div>
<div class="footer-actions"> <div class="footer-actions">
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} /> <IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => preferences = "settings"} /> <IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => void openSettings()} />
</div> </div>
</div> </div>
</aside> </aside>
@@ -807,7 +924,25 @@
<div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}> <div class="center-stack" class:terminal-maximized={terminalOpen && terminalMaximized} bind:this={centerStack}>
<main class="center"> <main class="center">
{#each $pluginEditors as view (view.key)}<PluginEditor {view} />{/each} <div class="plugin-panes" class:inactive={!editorPluginVisible}>
{#each $pluginEditors as pane (pane.key)}
{@const bounds = pluginBounds[pane.key]}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus selects the pane that owns the input.) -->
<div class="plugin-pane" class:inactive={!bounds} class:split={!!activeSplit} class:focused={$pluginView?.key === pane.key}
style:left={`${bounds?.left ?? 0}%`} style:top={`${bounds?.top ?? 0}%`}
style:width={`${bounds?.width ?? 100}%`} style:height={`${bounds?.height ?? 100}%`}
onfocusin={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}
onpointerdown={() => { if ($pluginView?.key !== pane.key) selectPluginEditor(pane); }}>
{#if activeSplit && bounds}
<TabBar tabs={workingTabs.filter(tab => tab.id === pane.key)} activePath={activeTabPath}
onSelect={selectWorkingTab} onClose={closeTab} onMove={moveWorkingTab} onPin={pinWorkingTab}
onCloseTabs={(path, scope) => void closeTabs(path, scope)} fileActions={workingTabFileActions} tabActions={workingTabActions}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
{/if}
<PluginEditor view={pane} />
</div>
{/each}
</div>
<div class="editor-host" class:plugin-covered={editorPluginVisible}> <div class="editor-host" class:plugin-covered={editorPluginVisible}>
{#if buffer?.diskError} {#if buffer?.diskError}
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div> <div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
@@ -827,6 +962,8 @@
onOpenWorkspace={() => void chooseWorkspace()} onOpenWorkspace={() => void chooseWorkspace()}
onNewFile={() => void newFile()} onNewFile={() => void newFile()}
onQuickOpen={() => quickOpen = true} onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{browserOpening}
{buffer} {buffer}
chrome={view} chrome={view}
{reading} {reading}
@@ -997,6 +1134,7 @@
background: transparent; background: transparent;
border-bottom: 0; border-bottom: 0;
} }
.header-center :global(.tabs:empty) { min-width: 80px; }
.header-center :global(.tab) { .header-center :global(.tab) {
max-width: 180px; max-width: 180px;
@@ -1047,6 +1185,12 @@
} }
.editor-host.plugin-covered { display: none; } .editor-host.plugin-covered { display: none; }
.center { position: relative; }
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
.plugin-pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; box-sizing: border-box; }
.plugin-pane.split { border: 1px solid var(--rs-border); }
.plugin-pane.split.focused { border-color: var(--rs-accent); }
.plugin-panes.inactive, .plugin-pane.inactive { display: none; }
.left, .left,
.right { .right {
+22
View File
@@ -0,0 +1,22 @@
<script lang="ts">
import { untrack } from "svelte";
import { pluginHost } from "./registry";
let { kind }: { kind: "settings" | "bookmarks" } = $props();
let element: HTMLDivElement | undefined = $state();
let error = $state("");
$effect(() => {
void $pluginHost;
const browser = pluginHost.get("browser"), target = element;
if (!browser || !target) return;
let disposed = false;
let cleanup: (() => void | Promise<void>) | undefined;
error = "";
void Promise.resolve(untrack(() => kind === "settings" ? browser.mountSettings(target) : browser.mountBookmarks(target)))
.then(value => { if (disposed) void value(); else cleanup = value; })
.catch(reason => { error = String(reason); });
return () => { disposed = true; void cleanup?.(); };
});
</script>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div bind:this={element}></div>
<style>.error { color: var(--rs-error); padding: 10px; }</style>
+42
View File
@@ -0,0 +1,42 @@
<script lang="ts">
import { untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, pluginTools, openPluginView, runPluginCommand } from "./external";
let { surface }: { surface: "commands" | "open" } = $props();
let anchor = $state<HTMLButtonElement>();
let position = $state<{ x: number; y: number } | null>(null);
let error = $state("");
let pointerWasOpen = false;
const label = $derived(surface === "open" ? "Open tab or view" : "Commands");
const tools = $derived($pluginTools.filter(tool => tool.surface === surface));
const signature = $derived(JSON.stringify([tools, $installedPlugins.plugins.map(row => [row.manifest.id, row.manifest.name])]));
const items: MenuItem[] = $derived.by(() => { void signature; return untrack(() => tools.map(tool => ({
kind: "action" as const,
label: `${tool.title} · ${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner}`,
icon: tool.icon === "list" ? "bullet" as const : tool.icon ?? (tool.owner === "runestone.browser" && tool.id === "new-tab" ? "globe" as const : tool.kind === "command" && surface === "commands" ? "code" as const : "plus" as const),
run: () => {
error = "";
if (tool.kind === "view") openPluginView(tool.owner, tool.id);
else void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason));
},
}))); });
</script>
{#if tools.length}
<button class="access-button" bind:this={anchor} aria-haspopup="menu" aria-expanded={position !== null} title={label}
onpointerdown={() => pointerWasOpen = position !== null}
onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}>
<Icon icon={surface === "open" ? "chevron-down" : "code"} /><span>{label}</span>
</button>
{/if}
{#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if}
{#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
<style>
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
.access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
.error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
</style>
+2 -3
View File
@@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { untrack } from "svelte"; import { untrack } from "svelte";
import { pluginView, pluginEditorActive, mountPluginView, type OpenPluginView } from "./external"; import { mountPluginView, type OpenPluginView } from "./external";
let { view }: { view: OpenPluginView } = $props(); let { view }: { view: OpenPluginView } = $props();
let host: HTMLDivElement | undefined = $state(); let host: HTMLDivElement | undefined = $state();
let error = $state(""); let error = $state("");
@@ -22,7 +22,7 @@
}); });
</script> </script>
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane" class:inactive={!$pluginEditorActive || $pluginView?.key !== view.key} <div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
role="tabpanel" aria-label={view.title} tabindex="-1"> role="tabpanel" aria-label={view.title} tabindex="-1">
{#if error}<p class="error" role="alert">{error}</p>{/if} {#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="plugin-editor-content" bind:this={host}></div> <div class="plugin-editor-content" bind:this={host}></div>
@@ -30,7 +30,6 @@
<style> <style>
.plugin-editor-pane { display: flex; flex: 1; min-height: 0; min-width: 0; flex-direction: column; overflow: hidden; } .plugin-editor-pane { display: flex; flex: 1; min-height: 0; min-width: 0; flex-direction: column; overflow: hidden; }
.plugin-editor-pane.inactive { display: none; }
.plugin-editor-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; } .plugin-editor-content { flex: 1; min-height: 0; min-width: 0; overflow: auto; }
.error { color: var(--rs-error); padding: 12px; } .error { color: var(--rs-error); padding: 12px; }
</style> </style>
-31
View File
@@ -1,31 +0,0 @@
<script lang="ts">
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor } from "./external";
</script>
{#if $pluginEditors.length}
<div class="plugin-tabs" role="tablist" aria-label="Plugin views">
{#each $pluginEditors as view (view.key)}
<div class="plugin-tab" class:active={$pluginEditorActive && $pluginView?.key === view.key}>
<button role="tab" aria-selected={$pluginEditorActive && $pluginView?.key === view.key} aria-controls={`plugin-editor-${view.key}`}
title={view.document?.path ?? view.title} onclick={() => selectPluginEditor(view)}
onauxclick={event => { if (event.button === 1) { event.preventDefault(); closePluginEditor(view.key); } }}>
<Icon icon={view.icon === "file" ? "files" : view.icon ?? "puzzle"} /><span>{view.title}</span>
</button>
<IconButton icon="close" label={`Close ${view.title}`} onclick={() => closePluginEditor(view.key)} />
</div>
{/each}
</div>
{/if}
<style>
.plugin-tabs { display: flex; flex-shrink: 1; min-width: 0; max-width: 70%; overflow-x: auto; }
.plugin-tab { display: flex; align-items: center; min-width: 0; border: 1px solid transparent; border-radius: var(--rs-control-radius); }
.plugin-tab.active { background: var(--rs-item-selection-bg); border-color: var(--rs-item-selection-border); }
.plugin-tab:hover { background: var(--rs-bg-active); }
button[role="tab"] { display: flex; align-items: center; gap: 7px; min-width: 0; height: 32px; padding: 0 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
button[role="tab"]:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
:global(.plugin-tab svg) { width: 16px; height: 16px; flex-shrink: 0; }
</style>
+23
View File
@@ -0,0 +1,23 @@
<script lang="ts">
import { untrack } from "svelte";
import { mountPluginView } from "./external";
let { owner, id }: { owner: string; id: string } = $props();
const pluginOwner = $derived(owner);
const viewId = $derived(id);
let element: HTMLDivElement | undefined = $state();
let error = $state("");
$effect(() => {
const target = element, plugin = pluginOwner, view = viewId;
if (!target) return;
let disposed = false;
let cleanup: (() => void | Promise<void>) | undefined;
error = "";
void untrack(() => mountPluginView(plugin, view, target, undefined, "settings")).then(value => {
if (disposed) void Promise.resolve(value()).catch(() => {}); else cleanup = value;
}).catch(reason => { if (!disposed) error = String(reason); });
return () => { disposed = true; void Promise.resolve(cleanup?.()).catch(() => {}); };
});
</script>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div bind:this={element}></div>
<style>.error { color: var(--rs-error); }</style>
+2 -26
View File
@@ -1,9 +1,7 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte"; import IconButton from "$lib/ui/IconButton.svelte";
import { pluginTools, pluginView, openPluginView, runPluginCommand, mountPluginView } from "./external"; import { pluginView, mountPluginView } from "./external";
let menu = $state(false);
let error = $state(""); let error = $state("");
let dialog: HTMLDialogElement | undefined = $state(); let dialog: HTMLDialogElement | undefined = $state();
let host: HTMLDivElement | undefined = $state(); let host: HTMLDivElement | undefined = $state();
@@ -22,25 +20,8 @@
}).catch(reason => { if (!cancelled) error = String(reason); }); }).catch(reason => { if (!cancelled) error = String(reason); });
return () => { cancelled = true; void Promise.resolve(cleanup?.()).catch(reason => error = String(reason)); modal.close(); previous?.focus(); }; return () => { cancelled = true; void Promise.resolve(cleanup?.()).catch(reason => error = String(reason)); modal.close(); previous?.focus(); };
}); });
onMount(() => {
const close = (event: PointerEvent) => { if (!(event.target as Element)?.closest(".plugin-tools")) menu = false; };
window.addEventListener("pointerdown", close);
return () => window.removeEventListener("pointerdown", close);
});
</script> </script>
{#if $pluginTools.length}
<div class="plugin-tools">
<IconButton icon="puzzle" label="Plugin commands and views" active={menu} onclick={() => menu = !menu} />
{#if menu}
<div class="tools" role="group" aria-label="Plugin commands and views">
{#each $pluginTools as tool (`${tool.owner}:${tool.kind}:${tool.id}`)}
<button onkeydown={event => { if (event.key === "Escape") menu = false; }} onclick={() => { menu = false; if (tool.kind === "view") openPluginView(tool.owner, tool.id); else void runPluginCommand(tool.owner, tool.id).catch(reason => error = String(reason)); }}><Icon icon={tool.kind === "view" ? "panel-right" : "code"} /><span>{tool.title}<small>{tool.owner}</small></span></button>
{/each}
</div>
{/if}
</div>
{/if}
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if} {#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
{#if $pluginView?.placement === "dialog"} {#if $pluginView?.placement === "dialog"}
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}> <dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
@@ -50,11 +31,6 @@
</dialog> </dialog>
{/if} {/if}
<style> <style>
.plugin-tools { position: relative; }
.tools { position: absolute; right: 0; top: 38px; width: 280px; max-height: 60vh; overflow: auto; z-index: 50; padding: 6px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 8px 24px #0008; }
.tools button { display: flex; gap: 10px; align-items: center; text-align: left; width: 100%; padding: 9px; border: 0; border-radius: var(--rs-control-radius); background: transparent; }
.tools button:hover { background: var(--rs-bg-active); }
small { display: block; color: var(--rs-text-dim); margin-top: 4px; }
dialog { width: min(800px, 90vw); max-height: 85vh; padding: 20px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); } dialog { width: min(800px, 90vw); max-height: 85vh; padding: 20px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
dialog::backdrop { background: #0008; } dialog::backdrop { background: #0008; }
header { display: flex; justify-content: space-between; align-items: center; } header { display: flex; justify-content: space-between; align-items: center; }
+21
View File
@@ -0,0 +1,21 @@
import type { PluginCommand, PluginView } from "./sdk.ts";
export type PluginTool = {
owner: string; id: string; title: string; kind: "command" | "view";
surface: "commands" | "open" | "settings";
icon?: PluginView["icon"];
};
export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): PluginTool[] {
const result: PluginTool[] = [];
for (const command of commands) {
const legacyOpen = owner === "runestone.browser" && command.id === "new-tab";
result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" || (command.category === undefined && legacyOpen) ? "open" : "commands" });
}
for (const view of views) {
const settings = view.settings ?? (owner === "runestone.local-autocomplete" && view.id === "settings");
if (!settings && (view.launcher === false || (view.launcher === undefined && owner === "runestone.browser"))) continue;
result.push({ owner, id: view.id, title: view.title, kind: "view", surface: settings ? "settings" : "open", icon: view.icon });
}
return result;
}
+6
View File
@@ -15,6 +15,12 @@ export interface TerminalMount {
export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!"; export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!";
export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode }; export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode };
export interface Contributions { export interface Contributions {
browser: {
newTab?(): Promise<void>;
mountSettings(container: HTMLElement): Dispose | Promise<Dispose>;
mountBookmarks(container: HTMLElement): Dispose | Promise<Dispose>;
open(url: string): Promise<boolean>;
};
terminal: { terminal: {
mount(container: HTMLElement, props: TerminalProps): TerminalMount; mount(container: HTMLElement, props: TerminalProps): TerminalMount;
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null; shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
+62 -14
View File
@@ -1,16 +1,42 @@
import { get, writable } from "svelte/store"; import { get, writable } from "svelte/store";
import { completionTransport } from "../completion/transport";
import { invoke, isTauri } from "@tauri-apps/api/core"; import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event"; import { listen } from "@tauri-apps/api/event";
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api"; import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
import { ExternalSession, deadline } from "./externalSession"; import { ExternalSession, deadline } from "./externalSession";
import { pluginAccess, type PluginTool } from "./access";
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
import type { PluginViewOpenOptions } from "./sdk";
import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk"; import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView, PluginDocumentContext, PluginDocumentType } from "./sdk";
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] }); export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
export const externalErrors = writable<Record<string, string>>({}); export const externalErrors = writable<Record<string, string>>({});
export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]); export const pluginTools = writable<PluginTool[]>([]);
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" } export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
export const pluginView = writable<OpenPluginView | null>(null); export const pluginView = writable<OpenPluginView | null>(null);
export const pluginEditors = writable<OpenPluginView[]>([]); export const pluginEditors = writable<OpenPluginView[]>([]);
export const pluginSplits = writable<SplitLayout[]>([]);
export function pinPluginEditor(key: string) {
pluginEditors.update(views => views.map(view => view.key === key ? { ...view, pinned: !view.pinned } : view));
}
export function pluginTabActions(view: OpenPluginView) { return sessions.get(view.owner)?.session.views.get(view.id)?.tabActions?.({ pinned: !!view.pinned }) ?? []; }
export function pluginTabDragData(view: OpenPluginView): string | undefined {
const data = sessions.get(view.owner)?.session.views.get(view.id)?.tabDragData?.({ pinned: !!view.pinned });
return data === undefined ? undefined : JSON.stringify({ owner: view.owner, data });
}
export async function dropPluginTab(data: string) {
if (data.length > 8192) throw new Error("Invalid tab transfer.");
const payload = JSON.parse(data);
if (!payload || typeof payload.owner !== "string" || typeof payload.data !== "string") throw new Error("Invalid tab transfer.");
const session = sessions.get(payload.owner)?.session;
if (!session) throw new Error("Enable this tab's plugin before moving it to this window.");
await session.dropTab(payload.data);
}
export function findPluginEditor(view: OpenPluginView): boolean {
const find = sessions.get(view.owner)?.session.views.get(view.id)?.find;
if (!find) return false;
find(); return true;
}
export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]); export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]);
export const pluginDocuments = writable<Record<string, { icon: "kanban" | "file"; title: string }>>({}); export const pluginDocuments = writable<Record<string, { icon: "kanban" | "file"; title: string }>>({});
export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]); export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]);
@@ -23,6 +49,7 @@ const errors: Record<string, string> = {};
const restarted = new Set<string>(); const restarted = new Set<string>();
let queue: Promise<void> = Promise.resolve(); let queue: Promise<void> = Promise.resolve();
let started = false; let started = false;
let allowedPlugins: string[] | undefined;
let generation = 0; let generation = 0;
let documentOpenVersion = 0; let documentOpenVersion = 0;
export function cancelPluginDocumentOpen() { documentOpenVersion++; } export function cancelPluginDocumentOpen() { documentOpenVersion++; }
@@ -41,10 +68,12 @@ export function notifyPluginWorkspace() { for (const listener of workspaceListen
export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); } export function selectPluginEditor(view: OpenPluginView) { cancelPluginDocumentOpen(); pluginView.set(view); pluginEditorActive.set(true); }
export function closePluginEditor(key: string) { export function closePluginEditor(key: string) {
cancelPluginDocumentOpen(); cancelPluginDocumentOpen();
const group = get(pluginSplits).find(tree => containsPane(tree, key));
const remaining = get(pluginEditors).filter(view => view.key !== key); const remaining = get(pluginEditors).filter(view => view.key !== key);
pluginSplits.update(trees => trees.flatMap(tree => { const next = removePane(tree, key); return next === null || typeof next === "string" ? [] : [next]; }));
pluginEditors.set(remaining); pluginEditors.set(remaining);
if (get(pluginView)?.key === key) { if (get(pluginView)?.key === key) {
pluginView.set(remaining.at(-1) ?? null); pluginView.set(remaining.find(view => group && containsPane(group, view.key)) ?? remaining.at(-1) ?? null);
pluginEditorActive.set(remaining.length > 0); pluginEditorActive.set(remaining.length > 0);
} }
} }
@@ -114,12 +143,10 @@ export async function createPluginDocument(owner: string, id: string, path: stri
} }
function publish() { function publish() {
pluginEditors.update(views => views.map(view => view.document ? view : { ...view, title: sessions.get(view.owner)?.session.views.get(view.id)?.title ?? view.title, iconImage: sessions.get(view.owner)?.session.views.get(view.id)?.iconImage }));
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon })))); pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon }))));
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type })))); pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
pluginTools.set([...sessions].flatMap(([owner, { session }]) => [ pluginTools.set([...sessions].flatMap(([owner, { session }]) => pluginAccess(owner, session.commands.values(), session.views.values())));
...[...session.commands.values()].map(({ id, title }) => ({ owner, id, title, kind: "command" as const })),
...[...session.views.values()].map(({ id, title }) => ({ owner, id, title, kind: "view" as const })),
]));
externalErrors.set({ ...errors }); externalErrors.set({ ...errors });
} }
function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); } function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); }
@@ -138,13 +165,22 @@ async function stop(id: string) {
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); } try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
await release(id, error); publish(); await release(id, error); publish();
} }
function show(owner: string, id: string) { function show(owner: string, id: string, options?: PluginViewOpenOptions) {
const view = sessions.get(owner)?.session.views.get(id); const view = sessions.get(owner)?.session.views.get(id);
if (view) { if (view) {
const placement = view.placement ?? "dialog"; const placement = view.placement ?? "dialog";
if (placement === "editor") { if (placement === "editor") {
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document); const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement }; const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(view.icon === "globe" ? { icon: "globe" as const } : {}) };
if (!existing && options) {
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
pluginSplits.update(trees => {
const index = trees.findIndex(tree => containsPane(tree, source.key));
if (index < 0) return [...trees, splitPane(source.key, source.key, editor.key, options.split)];
return trees.map((tree, i) => i === index ? splitPane(tree, source.key, editor.key, options.split) : tree);
});
}
if (!existing) pluginEditors.update(views => [...views, editor]); if (!existing) pluginEditors.update(views => [...views, editor]);
selectPluginEditor(editor); return; selectPluginEditor(editor); return;
} }
@@ -159,8 +195,10 @@ async function activate(row: InstalledPlugin) {
const id = row.manifest.id; const id = row.manifest.id;
let leased = false; let leased = false;
const session = new ExternalSession(id, { const session = new ExternalSession(id, {
completionTransport,
workspace: { workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead, list: path => workspaceList(path ?? ""), read: workspaceRead,
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
readBytes: workspaceReadBytes, readBytes: workspaceReadBytes,
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); }, write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; }, subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
@@ -168,11 +206,19 @@ async function activate(row: InstalledPlugin) {
create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); }, create: async (rel, contents) => { await invoke<void>("workspace_create", { rel, kind: "file", contents }); notifyPluginWorkspace(); },
}, },
settings: { settings: {
subscribe: listener => {
let disposed = false;
let off: (() => void) | undefined;
void listen<string>("plugin-settings-changed", event => { if (!disposed && event.payload === id) listener(); })
.then(unlisten => { if (disposed) unlisten(); else off = unlisten; })
.catch(reason => report(id, reason));
return () => { disposed = true; off?.(); };
},
read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })), read: async () => JSON.parse(await invoke<string>("plugins_data", { id, value: null })),
write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); }, write: async value => { const json = JSON.stringify(value); if (json === undefined) throw new Error("Plugin settings must be JSON data."); await invoke("plugins_data", { id, value: json }); },
}, },
assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) }, assets: { read: async path => Uint8Array.from(atob(await invoke<string>("plugins_asset", { id, path })), char => char.charCodeAt(0)) },
}, publish, view => show(id, view), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => { }, publish, (view, options) => show(id, view, options), undefined, async path => { if (!await openPluginDocument(path)) throw new Error("No enabled plugin recognizes this document."); }, async (document, name) => {
const match = await identifyDocument(document.path); const match = await identifyDocument(document.path);
if (session.controller.signal.aborted) throw new Error("This plugin is disabled."); if (session.controller.signal.aborted) throw new Error("This plugin is disabled.");
if (!match || match.owner !== id || match.document.id !== document.id) if (!match || match.owner !== id || match.document.id !== document.id)
@@ -180,7 +226,7 @@ async function activate(row: InstalledPlugin) {
if (!renameDocument) throw new Error("Document renaming is unavailable."); if (!renameDocument) throw new Error("Document renaming is unavailable.");
canWrite(document.path); canWrite(document.path);
return renameDocument(document.path, name); return renameDocument(document.path, name);
}); }, viewId => { for (const view of get(pluginEditors)) if (view.owner === id && view.id === viewId) closePluginEditor(view.key); });
try { try {
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true; const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
@@ -214,6 +260,7 @@ export function refreshPlugins(): Promise<void> {
} }
for (const row of snapshot.plugins) { for (const row of snapshot.plugins) {
const id = row.manifest.id; const id = row.manifest.id;
if (allowedPlugins && !allowedPlugins.includes(id)) continue;
if (!row.enabled) { failures.delete(id); continue; } if (!row.enabled) { failures.delete(id); continue; }
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row); if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
} }
@@ -230,14 +277,15 @@ export async function runPluginCommand(owner: string, id: string) {
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; } try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
} }
export function openPluginView(owner: string, id: string) { show(owner, id); } export function openPluginView(owner: string, id: string) { show(owner, id); }
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> { export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
const session = sessions.get(owner)?.session; const session = sessions.get(owner)?.session;
if (!session) throw new Error("The plugin is disabled."); if (!session) throw new Error("The plugin is disabled.");
return session.mount(id, element, document); return session.mount(id, element, document, surface);
} }
export function startExternalPlugins(): () => void { export function startExternalPlugins(allowed?: string[]): () => void {
if (!isTauri() || started) return () => {}; if (!isTauri() || started) return () => {};
started = true; started = true;
allowedPlugins = allowed;
let disposed = false; let disposed = false;
let off: (() => void) | undefined; let off: (() => void) | undefined;
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason))); void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
+49 -9
View File
@@ -1,4 +1,6 @@
import { pluginHost, type ContributionRegistry } from "./registry.ts"; import { pluginHost, type ContributionRegistry } from "./registry.ts";
import { completionHub } from "../completion/hub.ts";
import { registerCompletionInput } from "../completion/input.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts"; import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> { export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -21,14 +23,17 @@ export class ExternalSession {
private contributions: Dispose[] = []; private contributions: Dispose[] = [];
private registry: ContributionRegistry; private registry: ContributionRegistry;
readonly id: string; readonly id: string;
private services: Pick<PluginApi, "workspace" | "settings" | "assets">; private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private changed: () => void; private changed: () => void;
private show: (id: string) => void; private show: PluginApi["openView"];
private close?: PluginApi["closeView"];
private receiveTab?: (data: string) => void | Promise<void>;
private openDocument: (path: string) => Promise<void>; private openDocument: (path: string) => Promise<void>;
private renameDocument?: PluginApi["renameDocument"]; private renameDocument?: PluginApi["renameDocument"];
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets">, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"]) { constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { 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"]) {
this.openDocument = openDocument; this.openDocument = openDocument;
this.renameDocument = renameDocument; this.renameDocument = renameDocument;
this.close = close;
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show; this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
} }
private check() { if (this.stopped) throw new Error("This plugin is disabled."); } private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
@@ -40,9 +45,30 @@ export class ExternalSession {
}; };
const api: PluginApi = { const api: PluginApi = {
id: this.id, signal: this.controller.signal, id: this.id, signal: this.controller.signal,
completion: {
version: 1,
registerProvider: provider => { this.check(); const off = completionHub.registerProvider({ ...provider, id: this.id + ":" + provider.id }); this.contributions.push(off); return off; },
registerSurface: surface => { this.check(); const handle = completionHub.registerSurface({ ...surface, id: this.id + ":" + surface.id }); this.contributions.push(handle.dispose); return handle; },
registerInput: (element, options) => { this.check(); const handle = registerCompletionInput(element, { ...options, id: this.id + ":" + options.id }); this.contributions.push(handle.dispose); return handle; },
invalidate: () => { this.check(); completionHub.invalidate(); },
...(this.services.completionTransport ? { transport: (request, signal, onLine) => {
this.check(); return this.services.completionTransport!(request, AbortSignal.any([signal, this.controller.signal]), onLine);
} } : {}),
},
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); }, contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
registerCommand: item => { if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); }, registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
registerView: item => { if (item.placement !== undefined && !["dialog", "editor"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); }, registerView: item => { if ([item.settings, item.launcher].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
updateViewTitle: (id, title) => {
this.check(); const view = this.views.get(id);
if (!view || typeof title !== "string" || !title.trim() || title.length > 200) throw new Error("Invalid view title.");
if (view.title !== title) { view.title = title; this.changed(); }
},
updateViewIcon: (id, image) => {
this.check(); const view = this.views.get(id);
if (!view || (image !== null && (typeof image !== "string" || image.length > 90_000 || !/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/.test(image)))) throw new Error("Invalid view icon.");
if (view.iconImage !== image) { view.iconImage = image; this.changed(); }
},
registerDocumentType: item => { registerDocumentType: item => {
if (item.content !== undefined && !["text", "binary"].includes(item.content)) throw new Error("Invalid document content type."); if (item.content !== undefined && !["text", "binary"].includes(item.content)) throw new Error("Invalid document content type.");
if (typeof item.identify !== "function" || typeof item.mount !== "function" || !Array.isArray(item.extensions) || !item.extensions.length || item.extensions.some(ext => !/^[a-z0-9]+$/.test(ext)) || (item.icon && !["kanban", "file"].includes(item.icon))) throw new Error("Invalid document type."); if (typeof item.identify !== "function" || typeof item.mount !== "function" || !Array.isArray(item.extensions) || !item.extensions.length || item.extensions.some(ext => !/^[a-z0-9]+$/.test(ext)) || (item.icon && !["kanban", "file"].includes(item.icon))) throw new Error("Invalid document type.");
@@ -51,7 +77,8 @@ export class ExternalSession {
}, },
openDocument: path => { this.check(); return this.openDocument(path); }, openDocument: path => { this.check(); return this.openDocument(path); },
...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}), ...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}),
openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); }, openView: (id, options) => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id, options); },
...(this.close ? { closeView: (id: string) => { this.check(); this.close!(id); } } : {}),
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); }, onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
workspace: { workspace: {
...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => { ...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => {
@@ -65,6 +92,7 @@ export class ExternalSession {
this.cleanups.push(cleanup); return cleanup; this.cleanups.push(cleanup); return cleanup;
} } : {}), } } : {}),
list: path => { this.check(); return this.services.workspace.list(path); }, list: path => { this.check(); return this.services.workspace.list(path); },
...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}),
read: path => { this.check(); return this.services.workspace.read(path); }, read: path => { this.check(); return this.services.workspace.read(path); },
...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}), ...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}),
...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}), ...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}),
@@ -72,6 +100,13 @@ export class ExternalSession {
write: (path, value, expected) => { this.check(); if (typeof expected !== "string") throw new Error("Supply the original file text before writing."); return this.services.workspace.write(path, value, expected); }, write: (path, value, expected) => { this.check(); if (typeof expected !== "string") throw new Error("Supply the original file text before writing."); return this.services.workspace.write(path, value, expected); },
}, },
settings: { settings: {
...(this.services.settings.subscribe ? { subscribe: (listener: () => void) => {
this.check();
const off = this.services.settings.subscribe!(() => { if (!this.stopped) listener(); });
let active = true;
const cleanup: Dispose = () => { if (!active) return; active = false; this.cleanups = this.cleanups.filter(item => item !== cleanup); return off(); };
this.cleanups.push(cleanup); return cleanup;
} } : {}),
read: () => { this.check(); return this.services.settings.read(); }, read: () => { this.check(); return this.services.settings.read(); },
write: value => { this.check(); return this.services.settings.write(value); }, write: value => { this.check(); return this.services.settings.write(value); },
}, },
@@ -88,10 +123,15 @@ export class ExternalSession {
await deadline(this.activation); await deadline(this.activation);
} }
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); } async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext): Promise<Dispose> { async dropTab(data: string) {
this.check();
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
await this.receiveTab(data);
}
async mount(id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
this.check(); const view = document ? this.documentTypes.get(id) : this.views.get(id); if (!view) throw new Error("Unknown plugin view."); this.check(); const view = document ? this.documentTypes.get(id) : this.views.get(id); if (!view) throw new Error("Unknown plugin view.");
let cleaning: Promise<void> | undefined; let cleaning: Promise<void> | undefined;
const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element); }); const pending = Promise.resolve().then(() => { this.check(); return document ? (view as PluginDocumentType).mount(element, document) : (view as PluginView).mount(element, { surface }); });
const cleanup = () => { const cleanup = () => {
cleaning ??= (async () => { cleaning ??= (async () => {
const dispose = await pending; const dispose = await pending;
@@ -107,7 +147,7 @@ export class ExternalSession {
} }
stop(): Promise<void> { stop(): Promise<void> {
if (this.stopping) return this.stopping; if (this.stopping) return this.stopping;
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.changed(); this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
for (const remove of this.contributions.splice(0)) remove(); for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => { this.stopping = (async () => {
const errors: unknown[] = []; const errors: unknown[] = [];
+1 -1
View File
@@ -9,7 +9,7 @@ export class ContributionRegistry {
return this.entries.get(key)?.value as Contributions[K] | undefined; return this.entries.get(key)?.value as Contributions[K] | undefined;
} }
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void { register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
if (key !== "terminal" && key !== "tableFormulas") throw new Error("Unknown plugin contribution."); if (key !== "terminal" && key !== "tableFormulas" && key !== "browser") throw new Error("Unknown plugin contribution.");
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`); if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
const entry = { owner, value }; const entry = { owner, value };
this.entries.set(key, entry); this.emit(); this.entries.set(key, entry); this.emit();
+13 -4
View File
@@ -1,8 +1,11 @@
import type { Contributions } from "./contracts.ts"; import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts";
/** Package API v1. Compiled plugins export activate(api). */ /** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>; export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; run: () => void | Promise<void> } export interface PluginCommand { id: string; title: string; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; placement?: "dialog" | "editor"; navigation?: boolean; icon?: "list" | "kanban" | "puzzle"; mount: (container: HTMLElement) => void | Dispose | Promise<void | Dispose> } export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor"; navigation?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string } export interface PluginDocumentContext { id: string; path: string }
export interface PluginDocumentType { export interface PluginDocumentType {
id: string; id: string;
@@ -15,18 +18,24 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>; mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
} }
export interface PluginApi { export interface PluginApi {
completion?: CompletionApi;
readonly id: string; readonly id: string;
readonly signal: AbortSignal; readonly signal: AbortSignal;
contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void; contribute<K extends keyof Contributions>(key: K, value: Contributions[K]): void;
registerCommand(command: PluginCommand): void; registerCommand(command: PluginCommand): void;
registerView(view: PluginView): void; registerView(view: PluginView): void;
registerTabDrop?(receive: (data: string) => void | Promise<void>): void;
updateViewTitle?(id: string, title: string): void;
updateViewIcon?(id: string, image: string | null): void;
registerDocumentType(type: PluginDocumentType): void; registerDocumentType(type: PluginDocumentType): void;
openDocument(path: string): Promise<void>; openDocument(path: string): Promise<void>;
renameDocument?(document: PluginDocumentContext, name: string): Promise<string>; renameDocument?(document: PluginDocumentContext, name: string): Promise<string>;
openView(id: string): void; openView(id: string, options?: PluginViewOpenOptions): void;
closeView?(id: string): void;
onDispose(cleanup: Dispose): void; onDispose(cleanup: Dispose): void;
workspace: { workspace: {
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
listMarkdown?(): Promise<string[]>;
read(path: string): Promise<string>; read(path: string): Promise<string>;
readBytes?(path: string): Promise<Uint8Array>; readBytes?(path: string): Promise<Uint8Array>;
readOptional?(path: string): Promise<string | null>; readOptional?(path: string): Promise<string | null>;
@@ -34,7 +43,7 @@ export interface PluginApi {
write(path: string, contents: string, expected: string): Promise<void>; write(path: string, contents: string, expected: string): Promise<void>;
subscribe?(listener: () => void): Dispose; subscribe?(listener: () => void): Dispose;
}; };
settings: { read(): Promise<unknown>; write(value: unknown): Promise<void> }; settings: { read(): Promise<unknown>; write(value: unknown): Promise<void>; subscribe?(listener: () => void): Dispose };
assets: { read(path: string): Promise<Uint8Array> }; assets: { read(path: string): Promise<Uint8Array> };
} }
export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise<void | Dispose> } export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise<void | Dispose> }
+10
View File
@@ -6,6 +6,16 @@
<svg viewBox="0 0 24 24" aria-hidden="true"> <svg viewBox="0 0 24 24" aria-hidden="true">
{#if icon === "settings"} {#if icon === "settings"}
<path d="m9 3-1 3-3 1-2 3 2 2v3l3 2 1 4h5l1-3 3-1 3-4-2-2V8l-3-2-1-3Z" /><circle cx="12" cy="12" r="3" /> <path d="m9 3-1 3-3 1-2 3 2 2v3l3 2 1 4h5l1-3 3-1 3-4-2-2V8l-3-2-1-3Z" /><circle cx="12" cy="12" r="3" />
{:else if icon === "globe"}
<circle cx="12" cy="12" r="9" /><ellipse cx="12" cy="12" rx="4" ry="9" /><path d="M3 12h18" />
{:else if icon === "arrow-left"}
<path d="M20 12H4m6-6-6 6 6 6" />
{:else if icon === "arrow-right"}
<path d="M4 12h16m-6-6 6 6-6 6" />
{:else if icon === "copy"}
<rect x="8" y="8" width="12" height="12" rx="2" /><path d="M16 8V4H4v12h4" />
{:else if icon === "stop"}
<rect x="5" y="5" width="14" height="14" rx="2" />
{:else if icon === "help"} {:else if icon === "help"}
<circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" /> <circle cx="12" cy="12" r="9" /><path d="M9.5 9a2.5 2.5 0 1 1 4 2c-1 .6-1.5 1-1.5 3M12 17h.01" />
{:else if icon === "puzzle"} {:else if icon === "puzzle"}
+5
View File
@@ -2,6 +2,11 @@
import { onDestroy } from "svelte"; import { onDestroy } from "svelte";
import Icon from "./Icon.svelte"; import Icon from "./Icon.svelte";
export type IconName = export type IconName =
| "globe"
| "arrow-left"
| "arrow-right"
| "copy"
| "stop"
| "settings" | "settings"
| "help" | "help"
| "puzzle" | "puzzle"
+16
View File
@@ -0,0 +1,16 @@
<script lang="ts">
import Icon from "./Icon.svelte";
import type { IconName } from "./IconButton.svelte";
let { image, icon }: { image?: string | null; icon?: IconName } = $props();
let failed = $state<string | null>(null);
</script>
{#if image && image !== failed}
<img class="tab-icon" src={image} alt="" width="16" height="16" draggable="false" onerror={() => { failed = image ?? null; }} />
{:else if icon}
<Icon {icon} />
{/if}
<style>
.tab-icon { width: 16px; height: 16px; flex-shrink: 0; object-fit: contain; }
</style>
+4
View File
@@ -1,5 +1,9 @@
// Stroke icons share the same 24px grid and weight as IconButton. // Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = { export const actionIcons = {
globe: '<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/>',
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
'split-down': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 12h18m-12 3 3 3 3-3"/>',
kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>', kanban: '<rect x="3" y="4" width="5" height="16" rx="1"/><rect x="10" y="4" width="5" height="11" rx="1"/><rect x="17" y="4" width="4" height="7" rx="1"/>',
bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>', bookmark: '<path d="M6 4h12v16l-6-3-6 3z"/>',
'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>', 'file-plus': '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8zM14 2v6h6M12 18v-6M9 15h6"/>',
+1
View File
@@ -76,6 +76,7 @@ export class Documents {
const index = this.buffers.indexOf(previous); const index = this.buffers.indexOf(previous);
const opened = this.buffers.find(b => b.relPath === entry.rel_path); const opened = this.buffers.find(b => b.relPath === entry.rel_path);
if (index !== -1 && opened) { if (index !== -1 && opened) {
opened.tabId = previous.tabId ?? previous.id;
this.buffers = this.buffers.filter(b => b !== opened); this.buffers = this.buffers.filter(b => b !== opened);
this.buffers.splice(this.buffers.indexOf(previous), 1, opened); this.buffers.splice(this.buffers.indexOf(previous), 1, opened);
} }
+25
View File
@@ -0,0 +1,25 @@
export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout };
export type PaneBounds = { left: number; top: number; width: number; height: number };
export function containsPane(tree: SplitLayout, key: string): boolean {
return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key);
}
export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down"): SplitLayout {
if (typeof tree === "string") return tree === key ? { direction, first: tree, second: next } : tree;
return { ...tree, first: splitPane(tree.first, key, next, direction), second: splitPane(tree.second, key, next, direction) };
}
export function removePane(tree: SplitLayout, key: string): SplitLayout | null {
if (typeof tree === "string") return tree === key ? null : tree;
const first = removePane(tree.first, key), second = removePane(tree.second, key);
return first === null ? second : second === null ? first : { ...tree, first, second };
}
export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record<string, PaneBounds> {
if (typeof tree === "string") return { [tree]: bounds };
const a = { ...bounds }, b = { ...bounds };
if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; }
else { a.height /= 2; b.height /= 2; b.top += a.height; }
return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) };
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { OpenBuffer } from "./types";
export type TabCloseScope = "one" | "others" | "after" | "all"; export type TabCloseScope = "one" | "others" | "after" | "all";
export function tabsToClose(tabs: OpenBuffer[], path: string, scope: TabCloseScope): OpenBuffer[] { export function tabsToClose<T extends Pick<OpenBuffer, "relPath" | "pinned">>(tabs: T[], path: string, scope: TabCloseScope): T[] {
const index = tabs.findIndex(tab => tab.relPath === path); const index = tabs.findIndex(tab => tab.relPath === path);
if (index < 0) return []; if (index < 0) return [];
if (scope === "one") return [tabs[index]]; if (scope === "one") return [tabs[index]];
+1
View File
@@ -22,6 +22,7 @@ export type WorkspaceEvent = {
export type OpenBuffer = { export type OpenBuffer = {
id: string; id: string;
tabId?: string;
relPath: string; relPath: string;
name: string; name: string;
contents: string; contents: string;
+27
View File
@@ -0,0 +1,27 @@
import type { IconName } from "../ui/IconButton.svelte";
export type WorkbenchTab = {
id: string;
relPath: string;
name: string;
title: string;
dirty?: boolean;
pinned?: boolean;
draggable?: boolean;
icon?: IconName;
iconImage?: string | null;
panelId?: string;
};
export function orderWorkbenchTabs<T extends { id: string }>(tabs: T[], order: string[]): T[] {
const remaining = new Map(tabs.map(tab => [tab.id, tab]));
const ordered: T[] = [];
for (const id of order) {
const tab = remaining.get(id);
if (tab) {
ordered.push(tab);
remaining.delete(id);
}
}
return [...ordered, ...remaining.values()];
}
+7 -1
View File
@@ -3,13 +3,17 @@
import { onMount } from "svelte"; import { onMount } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window"; import { getCurrentWindow } from "@tauri-apps/api/window";
import Workbench from "$lib/layout/Workbench.svelte"; import Workbench from "$lib/layout/Workbench.svelte";
import BrowserWindow from "$lib/layout/BrowserWindow.svelte";
import SettingsWindow from "$lib/layout/SettingsWindow.svelte";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import { pluginHost } from "$lib/plugins/registry"; import { pluginHost } from "$lib/plugins/registry";
const terminalRoot = new URLSearchParams(location.search).get("terminalWindow"); const terminalRoot = new URLSearchParams(location.search).get("terminalWindow");
const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true";
const settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true";
let dock: TerminalSlot | undefined = $state(); let dock: TerminalSlot | undefined = $state();
let error = $state(""); let error = $state("");
const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
onMount(startExternalPlugins); onMount(() => startExternalPlugins(browserWindow ? ["runestone.browser"] : undefined));
function keydown(event: KeyboardEvent) { function keydown(event: KeyboardEvent) {
if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return; if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
const action = terminal?.shortcut(event); const action = terminal?.shortcut(event);
@@ -27,5 +31,7 @@
{/key} {/key}
{:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if} {:else}<p>Install and enable the Terminal plugin in Settings → Plug-ins in the main window.</p>{/if}
</div> </div>
{:else if browserWindow}<BrowserWindow />
{:else if settingsWindow}<SettingsWindow />
{:else}<Workbench />{/if} {:else}<Workbench />{/if}
<style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style> <style>.terminal-window { height: 100vh; display: flex; flex-direction: column; }</style>