diff --git a/.gitignore b/.gitignore index f12849a..d4b0f04 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ src-tauri/target src-tauri/gen .idea /.audit + +/plugin-packages/ diff --git a/README.md b/README.md index 699ee10..d21d23d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ A desktop workspace for writing and code. -RuneStone brings Markdown notes, scripts, images, and a terminal into one window. +RuneStone brings Markdown notes, scripts, images, and optional plugins into one window. Open a folder and work with the files already inside it. ## Why RuneStone? @@ -18,15 +18,15 @@ and use your own tools to manage them. Workspace settings live separately in `.r - **Markdown writing:** Live formatting, source editing, split view, and read view. - **Code editing:** A source editor for scripts, with file navigation and workspace search. - **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams. -- **Tables:** Editable Markdown tables with formulas for calculations. -- **Terminals:** Multiple shell sessions, split panes, and commands beside your documents. -- **File handling:** Autosave every five seconds and controls to resolve changes from other tools. +- **Tables:** Editable Markdown tables with optional calculations through the Table formulas plugin. +- **Terminal plugin:** Shell sessions, split panes, and commands beside your documents. +- **File handling:** Adjustable auto-save and controls to resolve changes from other tools. ## Project status RuneStone is under development, with Windows as its first target. -**Plugin support is planned and is not available yet.** Git controls, language servers, -session restoration, and crash recovery are also pending. +Local [plugin packages](docs/plugins.md) are available. Git controls, language servers, +session restoration, and crash recovery remain planned. The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones. The [user guide](docs/user-guide.md) covers current features and limitations. @@ -47,7 +47,10 @@ If Microsoft Edge WebView2 is missing, setup downloads and installs it, which ne Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save. See the [installation guide](docs/installation.md) for setup help, updates, and removal. -To run from source, see the [development guide](docs/development.md#run-from-source). +To run from source, see the [Developer README](docs/development.md#run-from-source). +For feature tests, use `pnpm tauri dev` after setup. +It reloads interface changes without a full rebuild. +See [the development workflow](docs/development.md#test-changes-without-a-full-rebuild) for commands and rebuild limits. ## Documentation @@ -55,7 +58,7 @@ Documentation lives in this repository: - [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts. - [Installation guide](docs/installation.md): Windows setup and troubleshooting. -- [Development guide](docs/development.md): Build tools, source setup, and tests. +- [Developer README](docs/development.md): Source setup, live updates, rebuild limits, and tests. - [Release guide](docs/releases.md): Build and package the Windows installer. - [Roadmap](docs/roadmap.md): Product direction, goals, and milestones. diff --git a/docs/development.md b/docs/development.md index 1001e1a..066b99e 100644 --- a/docs/development.md +++ b/docs/development.md @@ -1,7 +1,61 @@ -# Development guide +# Developer README [Back to RuneStone](../README.md) +## Test changes without a full rebuild + +From the repository folder, run: + +```powershell +pnpm tauri dev +``` + +For a fresh checkout, complete [Run from source](#run-from-source) first. + +This command starts Vite and opens RuneStone in a native desktop window. +Keep the terminal open while you edit the source. +Svelte, TypeScript, and CSS changes update through hot module replacement (HMR), or a page reload when required. +Frontend changes do not need a Rust rebuild or an installer. + +The first launch compiles the Rust app and its dependencies. +Later launches reuse Cargo's cached output. +Rust changes still need compilation, but Cargo reuses unchanged build output. +Tauri then restarts the app automatically. +See [Tauri development](https://v2.tauri.app/develop/) and [Vite HMR](https://vite.dev/guide/features.html#hot-module-replacement) for details. + +### Daily workflow + +1. Start `pnpm tauri dev` in a terminal at the repository root. +2. Open a test workspace with the folder button in the development window. +3. Edit a source file in your code editor. +4. Save the source file, then test the change in the development window. +5. To stop the development session, press Ctrl+C in its terminal. + +Use sample documents for feature tests. The desktop app reads and writes real files. +Save open documents before a change that reloads or restarts the app. +A reload can reset editor state, and a Rust restart ends terminal sessions. + +`pnpm tauri dev` starts `pnpm dev` through `beforeDevCommand` in `src-tauri/tauri.conf.json`. +Do not start a separate `pnpm dev` process for this workflow. +The frontend uses port 1420, and Tauri loads `http://localhost:1420`. + +### What needs a rebuild? + +| Change or task | Action | +| --- | --- | +| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. | +| Feature source under `plugins/` | Run `pnpm build:plugins`, then uninstall and install the changed package through Settings. | +| Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. | +| Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. | +| JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. | +| Tauri configuration, capabilities, or Vite configuration | Restart `pnpm tauri dev` to check the new settings. Native changes can require compilation. | +| Release or installer behavior | Use the [release guide](releases.md). Packaging requires a release build. | + +Keep `src-tauri/target/` between sessions so Cargo can reuse its build cache. +Do not run `cargo clean` as part of normal feature tests. +An installed copy from the Start menu uses its packaged code and does not show source changes. +Use the window that `pnpm tauri dev` opens. + ## Stack RuneStone uses Tauri 2 and Rust for the desktop host. @@ -12,6 +66,7 @@ Windows is the first target. The older WriterHost component remains unused. 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. Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md). +See the [plugin guide](plugins.md) to build and install feature packages, use the API, and understand current plugin boundaries. ## Run from source @@ -35,9 +90,25 @@ See the [release guide](releases.md) to build a Windows installer. ## Checks -Run these commands from the repository folder: +Run checks from the repository folder in a second terminal. +These commands do not require an installer. + +For type errors while you edit: + +```powershell +pnpm check:watch +``` + +For one test file: + +```powershell +node --experimental-strip-types --test scripts/tableSelection.spec.ts +``` + +For the full set of checks: ```sh +pnpm build:plugins pnpm check pnpm test pnpm build @@ -45,7 +116,9 @@ cargo test --manifest-path src-tauri/Cargo.toml --lib --offline ``` The offline Rust command requires cached dependencies. Omit `--offline` if Cargo needs to download them. -`pnpm build` builds the frontend. Use `pnpm tauri build` to build the desktop app. +`pnpm build` checks the production frontend build. It is not required after each source edit. +`pnpm preview` serves the last frontend build and does not watch source changes. +Use `pnpm tauri build` to build the release desktop app. The Rust tests cover real terminal shells, working directories, Unicode output, resizing, exit status, and session termination. Native terminal tests launch each @@ -53,20 +126,54 @@ detected shell profile and check shell prompt integration. ## Browser smoke tests +`pnpm dev` starts only the Vite server at `http://127.0.0.1:1420`. +A browser can show the interface, but real folder access, file writes, and terminals require the desktop host. +Use `pnpm tauri dev` for manual tests of those features. + +Run `pnpm build:plugins` before tests that use Terminal or Table formulas. +These tests load the compiled packages through the production module loader. The browser tests use the real interface with mocked desktop communication. They do not replace native desktop tests. 1. Install Playwright, or set `PLAYWRIGHT_MODULE` to a shared Playwright package. -2. Start the frontend with `pnpm dev`. +2. Start the frontend with `pnpm dev`, or reuse the server from an active `pnpm tauri dev` session. 3. In a second terminal, run a smoke script, such as `node scripts/workbench.smoke.mjs`. -Set `CHROME_PATH` if you need to select an installed browser executable. +Playwright is not a dependency in `package.json`. +Set `PLAYWRIGHT_MODULE` to the absolute path of an existing Playwright package if you use a shared installation. +That package must have Chromium installed, or you must select an installed browser with `CHROME_PATH`. + +For example, in PowerShell, replace these example paths with your local paths: + +```powershell +$env:PLAYWRIGHT_MODULE = "C:\tools\browser-tests\node_modules\playwright" +$env:CHROME_PATH = "C:\Program Files\Google\Chrome\Application\chrome.exe" +node scripts/workbench.smoke.mjs +``` | Script | Coverage | | --- | --- | | `scripts/workbench.smoke.mjs` | The Svelte, Monaco, and xterm interface | +| `scripts/pluginInstall.smoke.mjs` | Package review, external commands and views, the uninstall confirmation, and cleanup | +| `scripts/plugins.smoke.mjs` | Plugin toggles, formula source preservation, terminal cleanup, and preferences across windows | | `scripts/terminal.smoke.mjs` | Terminal groups, single-session layout, menus, profiles, history, tasks, settings, and editor actions | | `scripts/images.smoke.mjs` | Image drops, clipboard imports, source editing, zoom, undo, failed writes, and tab changes during imports | | `scripts/imageNavigation.smoke.mjs` | Navigator pointer drags, hidden image source, selection, context actions, inline/reference images, and drag cancellation | Additional smoke scripts live in `scripts/`. + +## Development help + +| Problem | Action | +| --- | --- | +| Port 1420 is already in use | Stop the other RuneStone development server in its terminal, then retry. Vite uses a fixed port. | +| The app still shows the old interface | Use the development window. Check the terminal for compile errors, then restart the development command if needed. | +| Browser view says desktop features require `pnpm tauri dev` | Start that command and use its native window for real workspace and terminal tests. | +| Windows cannot find `link.exe`, or Rust cannot link the app | Install the C++ build tools and Windows SDK from the Tauri prerequisites guide above. Open a new terminal. | +| A smoke test cannot find Playwright or Chromium | Set `PLAYWRIGHT_MODULE` to an installed package. Install its Chromium browser or set `CHROME_PATH`. | +| Cargo reports missing dependencies with `--offline` | Run the command without `--offline` while connected to the internet. | + +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. +Use its console for frontend errors. +See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector). diff --git a/docs/plugins.md b/docs/plugins.md new file mode 100644 index 0000000..640af93 --- /dev/null +++ b/docs/plugins.md @@ -0,0 +1,213 @@ +# Plugins + +[Back to development](development.md) + +RuneStone installs local JavaScript plugins from package files or folders. +Open Settings → Plug-ins to install, enable, disable, or uninstall them. +Terminal and Table formulas use the same installed package system as all other plugins. + +## Build and install the feature packages + +1. Run `pnpm build:plugins` from the repository root. +2. In Settings → Plug-ins, choose Install from folder and select `plugin-packages/`. +3. Review both packages, then choose Install and enable. + +No plugin starts automatically in a fresh installation. +The application build does not include these packages. Package builds include their JavaScript dependencies and terminal styles. +Build them again after source changes, then uninstall the old package and install the new folder. +The old bundled switches no longer apply. Existing terminal appearance settings remain available after installation. +Formula source stays in Markdown files when the plugin is absent, disabled, or removed. +Native pseudo-terminal services remain in the desktop host. The Terminal package supplies the interface, shortcuts, and session controls. + +## Install a plugin + +1. Choose Install from file or Install from folder. +2. Select the packages to install in the review dialog. +3. Choose Install to keep them disabled, or Install and enable to run them. + +A plugin file uses the `.runestone-plugin` extension and ZIP format. +You can also select `plugin.json`, its containing folder, or a collection folder containing plugin folders and package files. +Collection discovery checks one level and accepts at most 100 entries. +RuneStone copies packages into its per-user application data directory. It never modifies the selected source. +The review shows the author, version, source, destination, and access level. + +External plugins run with RuneStone's application access. Enable only code you trust. +Package metadata and hashes do not verify a publisher's identity. This version has no permission sandbox or marketplace. +Scanning and installation do not execute code, install dependencies, or run installation scripts. + +Plugins cannot overwrite an existing ID. Uninstall the previous package before installing another version. +Each package succeeds or fails independently. The result identifies any failures. +A changed source requires a new review. Cancelling the review removes its temporary copies. + +Try the example in `fixtures/plugins/workspace-overview/`. +Install that folder, then choose Install and enable. +Use the puzzle button in the main toolbar to run Show workspace overview or open the Workspace overview view. + +## Uninstall with one confirmation + +1. Choose Uninstall on the plugin's row. +2. Check its name, author, version, folder, and deletion message, then choose Uninstall and delete files. + +The dialog initially focuses Cancel. Escape cancels the uninstall flow. +Cancel leaves the files and enabled state unchanged. +Disable instead keeps every installed file and turns the plugin off. +Each uninstall requires a new confirmation. + +After confirmation, RuneStone disables the plugin in every window and waits for cleanup. +It deletes only the installed package. Source downloads, plugin settings, generated data, and workspace documents remain intact. +The app shows Restart required because already loaded JavaScript can remain in memory until RuneStone closes. + +Cleanup failure blocks deletion and keeps the installed files. Restart RuneStone before trying again. +An interrupted file deletion shows Removal incomplete. Retry cleanup continues only that previously confirmed removal. +Changed files in the removal directory block further deletion. Inspect the path named in the error before retrying. +Reinstallation requires a new enable decision and can reuse retained settings. + +```mermaid +flowchart LR + installed("Installed plugin") --> confirm("Confirm file deletion") + confirm --> cleanup("Stop in all windows") + cleanup --> removed("Delete package; retain data") +``` + +## Storage and recovery + +RuneStone resolves the root through Tauri's `app_data_dir()`. Settings shows the complete path. + +```text +/ + plugins// + plugin.json + main.js + assets/ + plugin-data//settings.json + plugin-state.json + plugin-staging/ + plugin-removals/ +``` + +Rust stores desired enable states in `plugin-state.json` and broadcasts changes to open windows. +The browser preview has no installed plugins unless a smoke test supplies a desktop mock. + +Startup, window focus, Refresh, and a five-second poll scan installed files. +Changed packages stop running and require another enable decision. Missing packages are never restored automatically. +Valid packages copied directly into the managed directory appear disabled. +Staging directories never participate in plugin discovery. + +Each reviewed candidate belongs to one window and expires after 30 minutes. +Rust checks the source and staged content hashes before publishing a complete directory. +A duplicate destination blocks publication. A crash cannot enable a partial installation. + +Removal plans belong to one window and expire after five minutes. +The backend accepts a single-use removal token when the user confirms deletion. +A changed package requires a new confirmation. +Runtime cleanup must complete in every window before the package moves into `plugin-removals/`. +A persisted record identifies that directory and the original file hashes. +Recovery deletes only unchanged remaining files from that confirmed transaction. It cannot target a newly installed copy. +Install and removal operations share one native service and serialize their state changes. + +## Package contract + +Place `plugin.json` at the root of the folder or archive: + +```json +{ + "schemaVersion": 1, + "id": "org.example.hello", + "name": "Hello", + "author": "Example author", + "description": "Open a small example view.", + "version": "1.0.0", + "apiVersion": 1, + "entry": "main.js", + "access": "full-app" +} +``` + +The package API is version 1. Its interface lives in `src/lib/plugins/sdk.ts`. +All packages use one API and the same installation, enable, disable, and removal lifecycle. +Versions use three numeric parts. Schema and API versions must match the supported version exactly. +The `runestone.*` prefix follows the same rules as other package IDs. It does not prove the publisher's identity. + +Package names use ASCII letters, digits, dots, underscores, and hyphens, with forward slashes between directories. +IDs use lowercase letters, digits, dots, and hyphens and start with a letter. +Windows device names, parent traversal, absolute paths, links, junctions, and case-insensitive collisions are invalid. +Limits are 5,000 entries, 100 MiB of expanded data, and 25 MiB per file. +The manifest has a 64 KiB limit. The final installed path cannot exceed 240 characters. + +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. +Raw TypeScript, Svelte source, native libraries, plugin dependencies, and automatic updates are unsupported. + +## Plugin API + +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. +A timeout reports an error and blocks successful cleanup until the app restarts. + +```js +export function activate(api) { + api.registerView({ + id: "hello", + title: "Hello", + mount(container) { + const text = document.createElement("p"); + text.textContent = "Hello from a RuneStone plugin."; + container.append(text); + return () => text.remove(); + } + }); + api.registerCommand({ + id: "show-hello", + title: "Show hello", + run: () => api.openView("hello") + }); +} +``` + +| API | Contract | +| --- | --- | +| `api.id` | The installed plugin ID | +| `api.signal` | An abort signal triggered before shutdown | +| `contribute(key, value)` | Register a typed terminal or table formula contribution | +| `registerCommand({ id, title, run })` | Add a command to the toolbar's plugin menu | +| `registerView({ id, title, mount })` | Add a view that mounts into a supplied DOM element | +| `openView(id)` | Open one of the plugin's registered views | +| `onDispose(callback)` | Register synchronous or asynchronous cleanup | +| `workspace.list(path?)` | List a directory in this window's active workspace | +| `workspace.read(path)` | Read a workspace text file | +| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text | +| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit | +| `assets.read(path)` | Read package bytes as a `Uint8Array` | + +Command and view IDs must be unique within their respective plugin collections. +Views can return asynchronous cleanup. Closing a view and disabling its plugin share the same cleanup promise. +Remove timers, listeners, and other resources in cleanup. Use the abort signal to stop pending work. +The SDK rejects calls after shutdown starts, but it does not isolate JavaScript with full application access. +Packages activate in every RuneStone window, including standalone terminal windows. + +Contribution types live in `src/lib/plugins/contracts.ts`. +Only one active package can own each contribution. The runtime removes contributions before cleanup starts. +Terminal controls mount into a host element and return update, command, and disposal functions. +The plugin must stop its mounted controls and native sessions in `onDispose` before cleanup completes. + +## Modules and checks + +| Module | Owns | +| --- | --- | +| `src-tauri/src/plugins.rs` | Discovery, validation, installation, persistence, removal plans, and cleanup acknowledgments | +| `src/lib/plugins/PluginManager.svelte` | Package review, switches, and the uninstall dialog | +| `src/lib/plugins/sdk.ts` | External package types | +| `src/lib/plugins/externalSession.ts` | Activation, contributions, view disposal, and shutdown | +| `src/lib/plugins/external.ts` | Native state synchronization and external module loading | +| `src/lib/plugins/PluginTools.svelte` | External commands and views | +| `src/lib/plugins/registry.ts` / `contracts.ts` | Shared feature contributions and their types | +| `src/lib/plugins/TerminalSlot.svelte` | The host element for terminal controls | +| `plugins/terminal/` / `plugins/table-formulas/` | Separate feature packages | +| `scripts/buildPlugins.mjs` | Package compilation into `plugin-packages/` | + +Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`. +The Rust tests use real temporary files and archives. Browser tests mock desktop calls and exercise the real UI and module loader. +Run `scripts/pluginInstall.smoke.mjs`, `scripts/plugins.smoke.mjs`, and `scripts/settings.smoke.mjs` against the development server. + +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. diff --git a/docs/product-scope.md b/docs/product-scope.md index 82b605f..eac4536 100644 --- a/docs/product-scope.md +++ b/docs/product-scope.md @@ -5,16 +5,17 @@ This reference preserves intended capabilities and design constraints. Some features already exist. See the [roadmap](roadmap.md) for goals and milestones, and the [user guide](user-guide.md) for current behavior and limitations. -The planned design keeps the core active and adds optional features through separately packaged plugins. Plugin support is not implemented yet. +The core stays active while installed packages supply optional Terminal and Table formulas features. +External JavaScript packages can add commands and views. See the [plugin guide](plugins.md) for current boundaries. ## Workspace and files - Open one folder as the workspace. - Keep notes, scripts, and images in the same tree. -- Honor `.gitignore` in the navigator. +- Show workspace files without applying `.gitignore`, `.ignore`, or global Git exclusions. - Watch the folder for changes. Poll when the path is a network drive. - Prefer a local Git clone. Do not treat a live network share as the sync path. -- Store display order, pins, bookmarks, and plugin settings in `.runestone/`. +- Store display order, pins, and bookmarks in `.runestone/`. Store plugin packages and retained plugin settings in application data. - Open an existing Obsidian folder as files plus wiki links. Ignore `.obsidian`. ## Writer and IDE @@ -47,15 +48,25 @@ The planned design keeps the core active and adds optional features through sepa ## Plugins -Plugin support is pending. In-house plugins ship with RuneStone as separate packages and use the same interfaces as external plugins. +Terminal and Table formulas use the same installed package system as all other plugins. +External JavaScript packages now support local installation, commands, views, retained settings, and removal with one confirmation. Users can enable or disable each plugin. A marketplace is outside the planned scope. +Installation accepts plugin packages or folders and stores copies in the application data directory. +Uninstall requires one confirmation before RuneStone removes the installed plugin files. +Cancel preserves the plugin. Removal keeps settings, source packages, and workspace documents. +See the [installation and removal guide](plugins.md#uninstall-with-one-confirmation). ### Plugin to-do list -- [ ] Build the plugin system: package loading, version checks, permissions, settings, and enable or disable controls. -- [ ] Define shared interfaces for plugins to add commands, views, and workspace features. -- [ ] Move the terminal into a separate in-house plugin that ships with RuneStone. -- [ ] Move Excel-like table features, including formulas and spreadsheet operations, into a separate in-house plugin that ships with RuneStone. +- [x] Use one package system with API version checks, cleanup, saved preferences, and enable controls. +- [x] Add external package loading, exact API compatibility checks, and retained plugin settings. +- [x] Define an external API for commands, views, and workspace files. +- [x] Require one confirmation before removing installed plugin files. +- [ ] Add isolated execution and restricted permissions. +- [x] Move terminal views, shortcuts, settings, and desktop API calls into an external plugin package. +- [ ] Move native terminal services into a separate in-house package. +- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package. +- [ ] Move the remaining spreadsheet operations into a separate in-house package. - [ ] Add a Kanban plugin for boards, columns, and task cards. - [ ] Add a Gantt plugin for task timelines and dependencies. - [ ] Add a Calendar plugin for dated tasks and events. @@ -65,9 +76,9 @@ Keep basic Markdown table editing and rendering in the core. Users must retain a Kanban, Gantt, and Calendar are separate plugins that share a task index. Kanban boards are Markdown files. Headings are columns. Task list items are cards. -### Planned defaults +### Planned plugin lineup -Planned plugins enabled by default: +No plugin starts automatically in a fresh installation. The planned lineup includes: - Terminal. Workspace shells, sessions, and script execution. - Tables. Excel-like formulas and spreadsheet operations. diff --git a/docs/roadmap.md b/docs/roadmap.md index 1ca9db1..4a8fcab 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -44,8 +44,10 @@ and identify a reported code problem within the workspace. **Objective:** Support different ways of working while keeping the core editor simple. -Plugin support is pending. Separately packaged plugins would let users choose tools for planning, tabletop play, and other workflows. -The terminal and Excel-like table features would ship as in-house plugins through the same plugin system. +Users can install, disable, and remove Terminal and Table formulas while retaining access to their files. +Separately packaged plugins can extend that choice to planning, tabletop play, and other workflows. +Users can now install local packages and remove them through one confirmation while retaining their data. +Restricted permissions and the remaining spreadsheet modules are still planned. **Milestone:** A user can enable a packaged plugin, use it with workspace files, and disable it while retaining access to those files in the core editor. diff --git a/docs/user-guide.md b/docs/user-guide.md index 8fae6e5..b892fa7 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -2,10 +2,33 @@ [Back to RuneStone](../README.md) -Current features and limitations as of September 2026. +Current features and limitations as of October 2026. + +## Settings and help + +Use the gear beside the workspace selector to open Settings, or press Ctrl+,. +Use the question mark beside it to open Help and about, or press F1. +Both shortcuts work when the sidebar is hidden. + +General settings control auto-save. It starts enabled, with a five-second interval. +Choose a whole number from 1 to 300 seconds, or turn auto-save off. +Changes apply when you leave the interval field and persist across restarts. +These preferences apply to all workspaces on this device. Other open windows receive changes immediately. +Restore defaults enables auto-save and sets the interval to five seconds. + +Search settings to find a category. Plug-ins lists installed packages, including Terminal and Table formulas after installation. +No plugin starts automatically in a fresh installation. Enable changes persist across restarts and open windows. +Disabling Terminal ends its sessions. Disabling Table formulas keeps the formula source and basic table editing. +Use Install from file or Install from folder to add local plugins. The puzzle button opens their commands and views. +Uninstall requires one confirmation and preserves settings, source packages, and workspace documents. +See the [plugin guide](plugins.md) for package formats, removal, and current boundaries. +Help and about includes the app version, basic instructions, and keyboard shortcuts. +Press Escape or use the close button to return to your work. ## Workspace, editing, and terminals +- The navigator, Quick Open, and search do not apply `.gitignore`, `.ignore`, or global Git exclusions. + Internal folders (`.git`, `.obsidian`, and `.runestone`) and temporary save files stay hidden. - The folder button and Ctrl+O open recent workspaces, with the current workspace marked and full paths shown. The list remembers the 20 most recently opened folders across restarts. Open another folder from the bottom of the menu, or @@ -88,7 +111,8 @@ Current features and limitations as of September 2026. - Right-click a tab for Move tab left and Move tab right. With a tab focused, use Alt+Shift+Left or Alt+Shift+Right. Use the arrow keys, Home, or End to select tabs. Press Escape to cancel a drag. - Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file. -- Changed notes and scripts autosave every 5 seconds, including background tabs. +- Changed notes and scripts auto-save every five seconds by default, including background tabs. + Use Settings to change the interval or turn auto-save off. Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts and unavailable files preserve your edits for resolution instead of overwriting. - The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks, @@ -143,6 +167,6 @@ Current features and limitations as of September 2026. ## Limitations Vault-wide wiki-link resolution, backlinks and math rendering still need work. -Git UI, language servers, plugins, persistent tab restoration and crash recovery +Git UI, language servers, restricted plugin permissions, persistent tab restoration and crash recovery are not implemented. Unsaved buffers and terminals last for the current app session only. diff --git a/fixtures/plugins/workspace-overview/main.js b/fixtures/plugins/workspace-overview/main.js new file mode 100644 index 0000000..acc5ecb --- /dev/null +++ b/fixtures/plugins/workspace-overview/main.js @@ -0,0 +1,26 @@ +export function activate(api) { + api.registerCommand({ id: "show-overview", title: "Show workspace overview", run: () => api.openView("overview") }); + api.registerView({ + id: "overview", + title: "Workspace overview", + async mount(container) { + const status = document.createElement("p"); + status.textContent = "Loading workspace files…"; + container.append(status); + let disposed = false; + try { + const entries = await api.workspace.list(); + if (api.signal.aborted || disposed) return; + status.textContent = `${entries.length} files and folders in this workspace.`; + const list = document.createElement("ul"); + for (const entry of entries) { + const item = document.createElement("li"); + item.textContent = `${entry.name}${entry.kind === "folder" ? "/" : ""}`; + list.append(item); + } + container.append(list); + } catch (error) { status.textContent = String(error); } + return () => { disposed = true; container.replaceChildren(); }; + }, + }); +} diff --git a/fixtures/plugins/workspace-overview/plugin.json b/fixtures/plugins/workspace-overview/plugin.json new file mode 100644 index 0000000..d0aeaa8 --- /dev/null +++ b/fixtures/plugins/workspace-overview/plugin.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "id": "org.runestone-example.workspace-overview", + "name": "Workspace overview", + "author": "RuneStone example", + "description": "List files and folders in the active workspace.", + "version": "1.0.0", + "apiVersion": 1, + "entry": "main.js", + "access": "full-app" +} diff --git a/package.json b/package.json index 438f7ae..548277d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.3", + "version": "0.1.4", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { @@ -9,10 +9,11 @@ "build:installer": "tauri build --bundles nsis -- --locked", "preview": "vite preview", "prepare": "svelte-kit sync || echo ''", - "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json", + "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tsconfig.plugins.json", "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch", "tauri": "tauri", - "test": "node --experimental-strip-types --test scripts/*.spec.ts" + "test": "node --experimental-strip-types --test scripts/*.spec.ts", + "build:plugins": "node scripts/buildPlugins.mjs" }, "license": "MIT", "dependencies": { diff --git a/plugins/table-formulas/controls.ts b/plugins/table-formulas/controls.ts new file mode 100644 index 0000000..b3a38c3 --- /dev/null +++ b/plugins/table-formulas/controls.ts @@ -0,0 +1,46 @@ +import { actionIcon } from "../../src/lib/ui/actionIcons.ts"; + +export function createFormulaTools(finish: () => void, measure: () => void) { + const formulaTools = document.createElement("div"); + formulaTools.className = "table-formula-tools"; + const formulaHelp = document.createElement("details"); + formulaHelp.className = "table-formula-help"; + const summary = document.createElement("summary"); + summary.append(actionIcon("math"), document.createTextNode("Formulas")); + summary.title = "How to calculate with table cells"; + // Committing a wrapped formula can shrink its row. Keep the click target in + // place until mouseup, then finish editing and give keyboard focus to help. + summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } }); + summary.addEventListener("click", () => { finish(); summary.focus(); }); + const instructions = document.createElement("div"); + instructions.className = "table-formula-instructions"; + const intro = document.createElement("p"); + intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2."; + const examples = document.createElement("dl"); + for (const [formula, description] of [ + ["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."], + ["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."], + ["=SUM(B2:B10)", "Add the values in a range."], + ["=(B2+C2)/2", "Add two values and divide by two."], + ["=ROUND(B2/3,2)", "Round to two decimal places."], + ]) { + const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd"); + code.textContent = formula; term.append(code); descriptionElement.textContent = description; + examples.append(term, descriptionElement); + } + const functions = document.createElement("p"); + functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range."; + const references = document.createElement("p"); + references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting."; + instructions.append(intro, examples, functions, references); + formulaHelp.append(summary, instructions); + formulaHelp.addEventListener("toggle", measure); + const formulaStatus = document.createElement("span"); + formulaStatus.className = "table-formula-status"; + formulaStatus.textContent = "Type = in a cell to calculate"; + const formulaHint = document.createElement("div"); + formulaHint.className = "table-formula-hint"; + formulaHint.hidden = true; + formulaTools.append(formulaHelp, formulaStatus); + return { formulaTools, formulaStatus, formulaHint }; +} diff --git a/src/lib/editor/tableFormulas.ts b/plugins/table-formulas/formulas.ts similarity index 100% rename from src/lib/editor/tableFormulas.ts rename to plugins/table-formulas/formulas.ts diff --git a/plugins/table-formulas/index.ts b/plugins/table-formulas/index.ts new file mode 100644 index 0000000..81ff006 --- /dev/null +++ b/plugins/table-formulas/index.ts @@ -0,0 +1,8 @@ +import type { PluginApi } from "../../src/lib/plugins/sdk.ts"; +import { createFormulaTools } from "./controls.ts"; +import * as formulas from "./formulas.ts"; +import { tableFormulaHtml, renderTableFormulas } from "./render.ts"; + +export function activate(api: PluginApi) { + api.contribute("tableFormulas", { ...formulas, tableFormulaHtml, renderTableFormulas, createFormulaTools }); +} diff --git a/plugins/table-formulas/plugin.json b/plugins/table-formulas/plugin.json new file mode 100644 index 0000000..a42b22e --- /dev/null +++ b/plugins/table-formulas/plugin.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "id": "runestone.table-formulas", + "name": "Table formulas", + "author": "RuneStone", + "description": "Calculate formulas in Markdown tables.", + "version": "1.0.0", + "apiVersion": 1, + "entry": "main.js", + "access": "full-app" +} diff --git a/plugins/table-formulas/render.ts b/plugins/table-formulas/render.ts new file mode 100644 index 0000000..e4ad7fb --- /dev/null +++ b/plugins/table-formulas/render.ts @@ -0,0 +1,29 @@ +import MarkdownIt from "markdown-it"; +import type { Token } from "markdown-it"; +import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "./formulas.ts"; +const escapeHtml = (text: string) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """); + +export function tableFormulaHtml(result: FormulaResult): string { + const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`; + return `${escapeHtml(result.text)}`; +} + +export function renderTableFormulas(tokens: Token[]) { + let rows: Token[][] | undefined; + for (const token of tokens) { + if (token.type === "table_open") rows = []; + else if (rows && token.type === "tr_open") rows.push([]); + else if (rows && token.type === "inline") rows.at(-1)?.push(token); + else if (rows && token.type === "table_close") { + const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content))); + rows.forEach((row, r) => row.forEach((cell, c) => { + const result = results[r][c]; + if (!result) return; + const output = new MarkdownIt.Token("html_inline", "", 0); + output.content = tableFormulaHtml(result); + cell.children = [output]; + })); + rows = undefined; + } + } +} diff --git a/plugins/terminal/TerminalBridge.svelte b/plugins/terminal/TerminalBridge.svelte new file mode 100644 index 0000000..f2248b2 --- /dev/null +++ b/plugins/terminal/TerminalBridge.svelte @@ -0,0 +1,11 @@ + + diff --git a/src/lib/layout/TerminalDock.svelte b/plugins/terminal/TerminalDock.svelte similarity index 98% rename from src/lib/layout/TerminalDock.svelte rename to plugins/terminal/TerminalDock.svelte index ad6fdc4..d517daf 100644 --- a/src/lib/layout/TerminalDock.svelte +++ b/plugins/terminal/TerminalDock.svelte @@ -2,10 +2,11 @@ import { onMount, tick } from "svelte"; import IconButton from "$lib/ui/IconButton.svelte"; import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu"; - import { ptyProfiles, ptyNewWindow, ptyDictation, workspaceRead } from "$lib/workspace/api"; - import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "$lib/terminal/model"; - import TerminalPicker from "$lib/terminal/TerminalPicker.svelte"; - import TerminalSettings from "$lib/terminal/TerminalSettings.svelte"; + import { workspaceRead } from "$lib/workspace/api"; + import { ptyProfiles, ptyNewWindow, ptyDictation } from "./api"; + import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "./model"; + import TerminalPicker from "./TerminalPicker.svelte"; + import TerminalSettings from "./TerminalSettings.svelte"; import TerminalPane from "./TerminalPane.svelte"; type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string }; diff --git a/src/lib/layout/TerminalPane.svelte b/plugins/terminal/TerminalPane.svelte similarity index 98% rename from src/lib/layout/TerminalPane.svelte rename to plugins/terminal/TerminalPane.svelte index 996406d..6ed107d 100644 --- a/src/lib/layout/TerminalPane.svelte +++ b/plugins/terminal/TerminalPane.svelte @@ -3,8 +3,8 @@ import { FitAddon } from "@xterm/addon-fit"; import { Terminal } from "@xterm/xterm"; import { onMount } from "svelte"; - import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "$lib/workspace/api"; - import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "$lib/terminal/model"; + import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "./api"; + import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "./model"; import "@xterm/xterm/css/xterm.css"; type Props = { diff --git a/src/lib/terminal/TerminalPicker.svelte b/plugins/terminal/TerminalPicker.svelte similarity index 100% rename from src/lib/terminal/TerminalPicker.svelte rename to plugins/terminal/TerminalPicker.svelte diff --git a/src/lib/terminal/TerminalSettings.svelte b/plugins/terminal/TerminalSettings.svelte similarity index 100% rename from src/lib/terminal/TerminalSettings.svelte rename to plugins/terminal/TerminalSettings.svelte diff --git a/plugins/terminal/api.ts b/plugins/terminal/api.ts new file mode 100644 index 0000000..f416a34 --- /dev/null +++ b/plugins/terminal/api.ts @@ -0,0 +1,47 @@ +import { invoke } from "@tauri-apps/api/core"; + +const sessions = new Set(); +const opening = new Set>(); +const closing = new Map>(); +let stopped = false; + +export async function closeTerminals(): Promise { + stopped = true; + await Promise.allSettled([...opening]); + const results = await Promise.allSettled([...sessions].map(ptyClose)); + const errors = results.filter(result => result.status === "rejected"); + if (errors.length) throw new Error(errors.map(result => String(result.reason)).join("\n")); +} + +export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise { + if (stopped) return Promise.reject(new Error("This plugin is disabled.")); + sessions.add(id); + const pending = invoke("pty_open", { id, cols, rows, cwd, profile, directory }); + opening.add(pending); + void pending.finally(() => opening.delete(pending)).catch(() => {}); + return pending; +} + +export function ptyProfiles(): Promise { + return invoke("pty_profiles"); +} +export function ptyNewWindow(): Promise { + return invoke("pty_new_window", { id: crypto.randomUUID() }); +} +export function ptyDictation(): Promise { return invoke("pty_dictation"); } + +export function ptyWrite(id: string, data: string): Promise { + return invoke("pty_write", { id, data }); +} + +export function ptyResize(id: string, cols: number, rows: number): Promise { + return invoke("pty_resize", { id, cols, rows }); +} + +export function ptyClose(id: string): Promise { + const pending = closing.get(id); + if (pending) return pending; + const close = invoke("pty_close", { id }).then(() => { sessions.delete(id); }).finally(() => closing.delete(id)); + closing.set(id, close); + return close; +} diff --git a/plugins/terminal/index.ts b/plugins/terminal/index.ts new file mode 100644 index 0000000..d186232 --- /dev/null +++ b/plugins/terminal/index.ts @@ -0,0 +1,29 @@ +import { flushSync, mount, unmount } from "svelte"; +import type { PluginApi } from "../../src/lib/plugins/sdk.ts"; +import { terminalShortcut } from "./model.ts"; +import TerminalBridge from "./TerminalBridge.svelte"; +import { closeTerminals } from "./api.ts"; + +export async function activate(api: PluginApi) { + const css = new TextDecoder().decode(await api.assets.read("style.css")); + if (api.signal.aborted) return; + const style = document.createElement("style"); + style.textContent = css; + document.head.append(style); + api.onDispose(() => style.remove()); + const mounts = new Set<() => Promise>(); + api.onDispose(closeTerminals); + api.onDispose(async () => { await Promise.all([...mounts].map(dispose => dispose())); }); + api.contribute("terminal", { + shortcut: terminalShortcut, + mount(container, props) { + if (api.signal.aborted) throw new Error("This plugin is disabled."); + const instance = mount(TerminalBridge, { target: container, props: { initial: props } }); + flushSync(); + let stopping: Promise | undefined; + const dispose = () => stopping ??= unmount(instance).then(() => { mounts.delete(dispose); }); + mounts.add(dispose); + return { update: value => instance.update(value), command: action => instance.command(action), dispose }; + }, + }); +} diff --git a/src/lib/terminal/model.ts b/plugins/terminal/model.ts similarity index 100% rename from src/lib/terminal/model.ts rename to plugins/terminal/model.ts diff --git a/plugins/terminal/plugin.json b/plugins/terminal/plugin.json new file mode 100644 index 0000000..59683c8 --- /dev/null +++ b/plugins/terminal/plugin.json @@ -0,0 +1,11 @@ +{ + "schemaVersion": 1, + "id": "runestone.terminal", + "name": "Terminal", + "author": "RuneStone", + "description": "Run shells, scripts, and workspace tasks.", + "version": "1.0.0", + "apiVersion": 1, + "entry": "main.js", + "access": "full-app" +} diff --git a/scripts/buildPlugins.mjs b/scripts/buildPlugins.mjs new file mode 100644 index 0000000..dde38b1 --- /dev/null +++ b/scripts/buildPlugins.mjs @@ -0,0 +1,23 @@ +import { build } from "vite"; +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { copyFile, mkdir } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +for (const name of ["terminal", "table-formulas"]) { + const source = new URL(`../plugins/${name}/`, import.meta.url); + const output = new URL(`../plugin-packages/${name}/`, import.meta.url); + await build({ + configFile: false, + root, + plugins: [svelte({ configFile: false, compilerOptions: { dev: false } })], + resolve: { alias: { $lib: fileURLToPath(new URL("../src/lib/", import.meta.url)) }, conditions: ["browser"] }, + build: { + outDir: fileURLToPath(output), emptyOutDir: true, + lib: { entry: fileURLToPath(new URL("index.ts", source)), formats: ["es"], fileName: () => "main.js", cssFileName: "style" }, + rolldownOptions: { output: { codeSplitting: false } }, + }, + }); + await mkdir(output, { recursive: true }); + await copyFile(new URL("plugin.json", source), new URL("plugin.json", output)); +} diff --git a/scripts/externalPlugins.spec.ts b/scripts/externalPlugins.spec.ts new file mode 100644 index 0000000..cedc078 --- /dev/null +++ b/scripts/externalPlugins.spec.ts @@ -0,0 +1,77 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; +import type { PluginApi } from "../src/lib/plugins/sdk.ts"; +function fixture() { + let writes = 0; + const session = new ExternalSession("org.test.demo", { + workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, + }, () => {}, () => {}); + return { session, writes: () => writes }; +} +test("external commands run and all host access stops before cleanup", async () => { + const { session, writes } = fixture(); let api!: PluginApi; let ran = 0; + await session.start({ activate(value) { + api = value; + api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } }); + api.registerView({ id: "view", title: "View", mount: () => {} }); + api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); }); + } }); + await session.run("run"); assert.equal(ran, 1); + assert.throws(() => api.workspace.write("x", "new", undefined!), /original/); + await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1); + await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0); + await assert.rejects(session.run("run"), /disabled/); + assert.throws(() => api.settings.read(), /disabled/); +}); +test("async activation cleanup runs once even when disabled before activation finishes", async () => { + const { session } = fixture(); let resolve!: () => void; let cleaned = 0; + const gate = new Promise(done => resolve = done); + const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } }); + await Promise.resolve(); + const stopped = session.stop(); resolve(); + await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1); +}); +test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => { + const { session } = fixture(); const calls: number[] = []; + await session.start({ activate(api) { + api.onDispose(() => { calls.push(1); }); + api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); }); + api.onDispose(() => { calls.push(3); }); + } }); + await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]); +}); +test("duplicate contribution IDs fail and partial activation can be cleaned", async () => { + const { session } = fixture(); let cleaned = false; + await assert.rejects(session.start({ activate(api) { + api.onDispose(() => { cleaned = true; }); + api.registerCommand({ id: "run", title: "Run", run() {} }); + api.registerCommand({ id: "run", title: "Again", run() {} }); + } }), /duplicate/); + await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0); +}); +test("view disposal is idempotent and participates in plugin shutdown", async () => { + const { session } = fixture(); let cleaned = 0; let cleared = 0; + await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } }); + const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement); + await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1); +}); +test("shutdown waits for view cleanup that already started when the view closed", async () => { + const { session } = fixture(); let done!: () => void; let cleaned = false; + const gate = new Promise(resolve => done = resolve); + await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } }); + const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement); + const closing = cleanup(); await Promise.resolve(); + let stopped = false; const stopping = session.stop().then(() => { stopped = true; }); + await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false); + done(); await Promise.all([closing, stopping]); assert(cleaned); +}); +test("cleanup returned by late activation still blocks shutdown when it fails", async () => { + const { session } = fixture(); let done!: () => void; + const gate = new Promise(resolve => done = resolve); + const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } }); + await Promise.resolve(); const stopping = session.stop(); done(); + await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/); +}); diff --git a/scripts/pluginInstall.smoke.mjs b/scripts/pluginInstall.smoke.mjs new file mode 100644 index 0000000..0003e55 --- /dev/null +++ b/scripts/pluginInstall.smoke.mjs @@ -0,0 +1,172 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +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(); +page.setDefaultTimeout(10000); +const errors = []; +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)); +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'; +await page.context().addInitScript(({ manifest, pluginCode }) => { + 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 = []; + let installed = []; + let removalPrepared = false; + const data = { preserved: true }; + const path = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id; + const snapshot = () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed }); + 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:window|is_maximized") return false; + if (command.startsWith("plugin:window|")) return null; + if (command === "plugins_snapshot") return snapshot(); + if (command === "plugins_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.runestone-plugin', manifest, error: null }]; + if (command === "plugins_cancel") { removalPrepared = false; return; } + if (command === "plugins_install") { + installed = [{ manifest, hash: 'reviewed-hash', enabled: args.enabled, path, error: null, removal: false }]; + emit('plugins-changed', null); return [{ name: manifest.name, error: null }]; + } + if (command === "plugins_set_enabled") { + installed[0].enabled = args.enabled; + emit('plugins-changed', null); return; + } + if (command === "plugins_load") { window.__TEST__.cleaned = false; window.__TEST__.released = false; return pluginCode.replace('export function activate(api) {', 'export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });'); } + if (command === "plugins_release") { window.__TEST__.released = true; return; } + if (command === "plugins_data") return JSON.stringify(data); + if (command === "plugins_reveal") return; + if (command === "plugins_prepare_remove") { removalPrepared = true; return { token: 'remove-plan', plugin: installed[0] }; } + if (command === "plugins_remove") { + if (!removalPrepared) throw Error('Missing removal plan'); + removalPrepared = false; + installed[0].enabled = false; emit('plugins-changed', null); + for (let i=0; i<100 && !window.__TEST__.released; i++) await new Promise(resolve => setTimeout(resolve, 50)); + if (!window.__TEST__.cleaned || !window.__TEST__.released) throw Error('Cleanup was not acknowledged'); + installed = []; emit('plugins-changed', null); return; + } + 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_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; + 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, data }; +}, { manifest, pluginCode }); + +async function quickOpen(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 page.locator('.live-writer').waitFor(); +} + + +const settingsDialog = page.getByRole('dialog', { name: 'Settings', exact: true }); +const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); +async function settings() { + await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); + await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); +} +async function uninstall() { await settingsDialog.getByRole('button', { name: 'Uninstall Workspace overview', exact: true }).click(); } +try { + await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420'); + await page.getByText('smoke-workspace', { exact: true }).waitFor(); + await settings(); + await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).click(); + let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true }); + await review.getByRole('button', { name: 'Cancel', exact: true }).click(); + assert.equal(await count('plugins_install'), 0); + await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).click(); + await review.getByRole('button', { name: 'Install and enable', exact: true }).click(); + await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor(); + assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); + await page.screenshot({ path: '.audit/plugin-manager-installed.png' }); + await page.keyboard.press('Escape'); + await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click(); + await page.getByRole('button', { name: /Show workspace overview/ }).click(); + const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true }); + await view.getByText(/files and folders in this workspace/).waitFor(); + await view.getByRole('button', { name: 'Close plugin view', exact: true }).click(); + await settings(); + await uninstall(); + const confirmation = page.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true }); + 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); + await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click(); + assert.equal(await count('plugins_remove'), 0); + assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); + await uninstall(); + await confirmation.waitFor(); + await page.keyboard.press('Escape'); + assert(await settingsDialog.isVisible()); + assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); + assert.equal(await count('plugins_remove'), 0); + await uninstall(); + await confirmation.waitFor(); + await page.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' }); + await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); + await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor(); + assert.equal(await count('plugins_remove'), 1); + assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true); + assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true); + await page.keyboard.press('Escape'); + assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0); + await page.setViewportSize({ width: 590, height: 820 }); + await settings(); + await page.screenshot({ path: '.audit/plugin-manager-narrow.png' }); + assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false); + assert.deepEqual(errors, []); + console.log('External plugin smoke passed: file/folder review, code loading, command/view, one confirmation, cancellation, focus, cleanup, and uninstall.'); +} finally { await browser.close(); } diff --git a/scripts/pluginMocks.mjs b/scripts/pluginMocks.mjs new file mode 100644 index 0000000..5ebaaa9 --- /dev/null +++ b/scripts/pluginMocks.mjs @@ -0,0 +1,36 @@ +import { readFile } from "node:fs/promises"; + +/** Load the actual compiled packages through the production Blob module loader. */ +export async function mockFeaturePlugins(surface) { + const packages = await Promise.all(["terminal", "table-formulas"].map(async name => { + const root = new URL(`../plugin-packages/${name}/`, import.meta.url); + return { + manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")), + code: await readFile(new URL("main.js", root), "utf8"), + css: name === "terminal" ? await readFile(new URL("style.css", root), "base64") : "", + }; + })); + await surface.addInitScript(packages => { + const key = "test.installed-plugins"; + const root = "C:\\AppData\\RuneStone\\plugins"; + const defaults = packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false })); + const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults)); + const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); }; + if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults)); + window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); }); + const original = window.__TAURI_INTERNALS__.invoke; + window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => { + if (!command.startsWith("plugins_")) return original(command, args); + window.__TEST__?.calls.push({ command, args }); + if (command === "plugins_snapshot") return { root, plugins: read() }; + if (command === "plugins_load") return packages.find(item => item.manifest.id === args.id).code; + if (command === "plugins_asset") return packages.find(item => item.manifest.id === args.id).css; + if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; } + if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) }; + if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; } + if (command === "plugins_data") return "null"; + if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return; + throw new Error(`Unhandled plugin IPC: ${command}`); + }; + }, packages); +} diff --git a/scripts/plugins.smoke.mjs b/scripts/plugins.smoke.mjs new file mode 100644 index 0000000..5f1bf20 --- /dev/null +++ b/scripts/plugins.smoke.mjs @@ -0,0 +1,194 @@ +import { mockFeaturePlugins } from "./pluginMocks.mjs"; +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +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(); +page.setDefaultTimeout(10000); +const errors = []; +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.context().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_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }]; + 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 }; +}); +await mockFeaturePlugins(page.context()); + + +async function quickOpen(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 page.locator('.live-writer').waitFor(); +} + +const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n'; +const table = page.locator('.live-writer table'); +const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }); +const switchFor = name => dialog.getByRole('switch', { name, exact: true }); +async function settings() { + await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); + await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); +} +async function closeSettings() { + await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); + await page.keyboard.press('Escape'); + await dialog.waitFor({ state: 'hidden' }); +} +const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); +try { + await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420'); + await page.getByText('smoke-workspace', { exact: true }).waitFor(); + await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source); + await quickOpen('formulas.md'); + await table.waitFor(); + assert.equal(await table.locator('.md-table-formula').innerText(), '6'); + await settings(); + await switchFor('Table formulas').uncheck(); + await closeSettings(); + await page.waitForFunction(() => !document.querySelector('.md-table-formula')); + assert.match(await table.innerText(), /=A2\*3/); + assert.equal(await page.locator('.table-formula-tools').count(), 0); + await table.locator('td').last().click(); + await page.locator('.writer-cell-editor').fill('=A2*4'); + await page.keyboard.press('Enter'); + await settings(); + await switchFor('Table formulas').check(); + await closeSettings(); + await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8'); + await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight'); + const preview = page.locator('.md-page table').first(); + await preview.locator('.md-table-formula').waitFor(); + await settings(); + await switchFor('Table formulas').uncheck(); + await closeSettings(); + await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula')); + assert.match(await preview.innerText(), /=A2\*4/); + await settings(); + await switchFor('Table formulas').check(); + await closeSettings(); + await preview.locator('.md-table-formula').waitFor(); + assert.equal(await preview.locator('.md-table-formula').innerText(), '8'); + await page.keyboard.press('Control+s'); + await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4')); + assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<'))); + + await page.getByRole('button', { name: 'Terminal', exact: true }).click(); + await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open')); + await settings(); + await switchFor('Terminal').uncheck(); + await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close')); + await page.screenshot({ path: '.audit/plugins-settings.png' }); + await closeSettings(); + assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); + const opened = await count('pty_open'); + await page.keyboard.press('Control+j'); + assert.equal(await count('pty_open'), opened); + await page.reload(); + await page.getByText('smoke-workspace', { exact: true }).waitFor(); + assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); + await settings(); + assert(!await switchFor('Terminal').isChecked()); + + const standalone = await page.context().newPage(); + await standalone.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '?terminalWindow=C%3A%5Csmoke-workspace'); + await standalone.getByText(/Install and enable the Terminal plugin/).waitFor(); + await switchFor('Terminal').check(); + await standalone.locator('.xterm').waitFor(); + await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open')); + await switchFor('Terminal').uncheck(); + await standalone.getByText(/Install and enable the Terminal plugin/).waitFor(); + await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close')); + await standalone.close(); + await switchFor('Terminal').check(); + await closeSettings(); + await page.getByRole('button', { name: 'Terminal', exact: true }).click(); + await page.locator('.xterm').waitFor(); + await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source); + await page.getByRole('button', { name: 'Terminal', exact: true }).focus(); + await quickOpen('formulas.md'); + await settings(); + assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0); + for (const name of ['Terminal', 'Table formulas']) { + await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); + await dialog.getByRole('button', { name: `Uninstall ${name}`, exact: true }).click(); + const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true }); + await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); + await confirmation.waitFor({ state: 'hidden' }); + await switchFor(name).waitFor({ state: 'detached' }); + } + await closeSettings(); + await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm')); + assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); + assert.match(await table.innerText(), /=A2\*4/); + await page.reload(); + await page.getByText('smoke-workspace', { exact: true }).waitFor(); + await settings(); + await dialog.getByText('No plugins installed.', { exact: true }).waitFor(); + assert.deepEqual(errors, []); + console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.'); +} catch (error) { + await page.screenshot({ path: ".audit/plugins-failure.png" }); + console.log(await page.locator('.md-page').allTextContents()); + console.log(errors); + throw error; +} finally { await browser.close(); } diff --git a/scripts/plugins.spec.ts b/scripts/plugins.spec.ts new file mode 100644 index 0000000..3728cc0 --- /dev/null +++ b/scripts/plugins.spec.ts @@ -0,0 +1,62 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts"; +import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; +import { activate } from "../plugins/table-formulas/index.ts"; +import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts"; +import type { PluginApi } from "../src/lib/plugins/sdk.ts"; + +const services = { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, +}; +test("core starts without optional features and formula packages preserve source when stopped", async () => { + assert.equal(pluginHost.get("terminal"), undefined); + assert.equal(pluginHost.get("tableFormulas"), undefined); + const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n"; + assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/); + const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {}); + await session.start({ activate }); + const enabled = renderMarkdownHtml(source, new Map()); + assert.match(enabled, />6<\/span>/); + await session.stop(); + for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) { + assert.doesNotMatch(html, /md-table-formula/); + assert.match(html, /=A2\*3/); + assert.match(html, //); + } + const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {}); + await next.start({ activate }); + assert.equal(renderMarkdownHtml(source, new Map()), enabled); + await next.stop(); +}); + +test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => { + const registry = new ContributionRegistry(); + const first = new ExternalSession("first", services, () => {}, () => {}, registry); + const second = new ExternalSession("second", services, () => {}, () => {}, registry); + let api!: PluginApi; + await first.start({ activate(value) { api = value; activate(api); } }); + const contribution = registry.get("tableFormulas"); + await assert.rejects(second.start({ activate }), /already registered/); + await second.stop(); + assert.equal(registry.get("tableFormulas"), contribution); + api.onDispose(() => { + assert.equal(registry.get("tableFormulas"), undefined); + assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/); + }); + await first.stop(); +}); + +test("partial activation and failed cleanup cannot retain feature contributions", async () => { + const registry = new ContributionRegistry(); + const session = new ExternalSession("failed", services, () => {}, () => {}, registry); + await assert.rejects(session.start({ activate(api) { + activate(api); + api.onDispose(() => { throw new Error("Cleanup failed"); }); + throw new Error("Activation failed"); + } }), /Activation failed/); + await assert.rejects(session.stop(), /Cleanup failed/); + assert.equal(registry.get("tableFormulas"), undefined); +}); diff --git a/scripts/settings.smoke.mjs b/scripts/settings.smoke.mjs new file mode 100644 index 0000000..849052c --- /dev/null +++ b/scripts/settings.smoke.mjs @@ -0,0 +1,165 @@ +// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed. +import { createRequire } from "node:module"; +import { mkdirSync, readFileSync } from "node:fs"; +import assert from "node:assert/strict"; +const require = createRequire(import.meta.url); +const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); +mkdirSync(".audit", { recursive: true }); +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: 1100, height: 800 } }); +const page = await context.newPage(); +const errors = []; +page.on("pageerror", error => errors.push(error.message)); +await context.addInitScript(() => { + window.isTauri = true; + const disk = { "note.txt": "Original note" }; + const writes = []; + window.__TEST__ = { disk, writes }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: () => 1, unregisterCallback: () => {}, + invoke: async (command, args = {}) => { + if (command === "plugins_snapshot") return { root: "D:\\AppData\\RuneStone\\plugins", plugins: [] }; + if (command === "workspace_last_path") return "D:\\Notes"; + if (command === "workspace_open") return { root: "D:\\Notes", name: "Notes", watch_mode: "native" }; + if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }]; + if (command === "workspace_read") { if (args.rel in disk) return disk[args.rel]; throw "Missing file"; } + if (command === "workspace_write") { disk[args.rel] = args.contents; writes.push(args); return; } + return null; + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; +}); +const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; +const settings = page.getByRole("dialog", { name: "Settings", exact: true }); +const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }); +const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" }); +const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true }); +async function changeSeconds(value) { + await interval.fill(String(value)); + await interval.press("Tab"); +} +async function edit(value) { + await page.evaluate(async text => { + const { monaco } = await import("/src/lib/editor/monacoEnv.ts"); + monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text); + }, value); +} +const writes = () => page.evaluate(() => window.__TEST__.writes.length); +try { + await page.clock.install(); + await page.goto(url); + await page.locator(".ws").filter({ hasText: "Notes" }).waitFor(); + await trigger.click(); + assert.equal(await interval.inputValue(), "5"); + assert(await enabled.isChecked()); + await changeSeconds(2); + await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor(); + await page.keyboard.press("Escape"); + assert(await trigger.evaluate(element => element === document.activeElement), "Closing restores focus"); + await page.reload(); + await trigger.click(); + assert.equal(await interval.inputValue(), "2", "Interval survives reload"); + await changeSeconds(0); + await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor(); + assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2); + await changeSeconds(2); + await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins"); + await settings.getByText("No plugins installed.", { exact: true }).waitFor(); + assert(await settings.getByRole("button", { name: "Install from folder", exact: true }).isEnabled()); + await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting"); + await settings.getByText("No settings found", { exact: true }).waitFor(); + await settings.getByRole("button", { name: "Clear search" }).click(); + await page.screenshot({ path: ".audit/settings-general.png" }); + await page.keyboard.press("Escape"); + + await page.keyboard.press("Control+p"); + 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.locator(".monaco-editor textarea").waitFor(); + await page.clock.pauseAt(new Date()); + await trigger.click(); + await changeSeconds(3); + await page.keyboard.press("Escape"); + await edit("Saved at three seconds"); + const before = await writes(); + await page.clock.runFor(2100); + assert.equal(await writes(), before, "Old two-second timer is removed"); + await page.clock.runFor(1000); + assert.equal(await writes(), before + 1, "New interval saves the dirty buffer"); + await page.clock.runFor(3100); + assert.equal(await writes(), before + 1, "Clean files are not rewritten"); + await trigger.click(); + await enabled.uncheck(); + assert(await interval.isDisabled()); + await page.keyboard.press("Escape"); + await edit("Manual save while auto-save is disabled"); + await page.clock.runFor(10000); + assert.equal(await writes(), before + 1); + await page.keyboard.press("Control+s"); + await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2); + await page.locator(".monaco-editor textarea").focus(); + await page.keyboard.press("Control+,"); + await settings.waitFor(); + await page.keyboard.press("Escape"); + await page.locator(".monaco-editor textarea").focus(); + await page.keyboard.press("F1"); + await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor(); + await page.keyboard.press("Escape"); + + const other = await context.newPage(); + await other.goto(url); + 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("switch", { name: "Auto-save", exact: true }).isChecked(), false); + await other.getByRole("button", { name: "Restore defaults" }).click(); + await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled); + await trigger.click(); + await enabled.waitFor(); + assert(await enabled.isChecked(), "Other windows receive changes"); + assert.equal(await interval.inputValue(), "5"); + await page.keyboard.press("Escape"); + await edit("Auto-save enabled from another window"); + await page.clock.runFor(5100); + assert.equal(await writes(), before + 3); + await other.close(); + + await trigger.click(); + await page.evaluate(() => { + window.__SET_ITEM__ = Storage.prototype.setItem; + Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); }; + }); + await changeSeconds(7); + await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor(); + await page.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; }); + await page.keyboard.press("Escape"); + await trigger.click(); + assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings"); + await page.keyboard.press("Escape"); + + await page.getByRole("button", { name: "Help and about (F1)" }).click(); + const help = page.getByRole("dialog", { name: "Help and about", exact: true }); + await help.getByRole("heading", { name: "RuneStone", exact: true }).waitFor(); + await help.getByText(`Version ${version}`, { exact: false }).waitFor(); + await page.screenshot({ path: ".audit/settings-help.png" }); + await page.keyboard.press("Escape"); + await page.keyboard.press("Control+b"); + await page.keyboard.press("Control+,"); + await settings.waitFor(); + await page.keyboard.press("Escape"); + await page.keyboard.press("F1"); + await help.waitFor(); + await page.keyboard.press("Escape"); + await page.setViewportSize({ width: 420, height: 650 }); + await page.keyboard.press("Control+,"); + await settings.waitFor(); + assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits"); + await page.screenshot({ path: ".audit/settings-narrow.png" }); + for (let i = 0; i < 12; i++) { + await page.keyboard.press("Tab"); + assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal"); + } + assert.deepEqual(errors, []); + console.log("Settings smoke passed: timer changes, disabled auto-save, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, shortcuts, and narrow layout."); +} finally { await browser.close(); } diff --git a/scripts/settings.spec.ts b/scripts/settings.spec.ts new file mode 100644 index 0000000..56aae33 --- /dev/null +++ b/scripts/settings.spec.ts @@ -0,0 +1,32 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../src/lib/workspace/settings.ts"; + +test("missing or damaged preferences keep safe defaults", () => { + for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) { + assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS); + } + for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) { + assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds })), { autosaveEnabled: false, autosaveSeconds: 5 }); + } + assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10 }); +}); + +test("preferences persist and load at both interval limits", () => { + const store = new Map(); + for (const autosaveSeconds of [1, 23, 300]) { + const settings = { autosaveEnabled: false, autosaveSeconds }; + saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings); + assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings); + } +}); + +test("invalid changes never reach storage and storage failures reach the caller", () => { + let writes = 0; + const storage = { setItem: () => { writes++; } }; + for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) { + assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds })); + } + assert.equal(writes, 0); + assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/); +}); diff --git a/scripts/tableFormulas.smoke.mjs b/scripts/tableFormulas.smoke.mjs index 1cb6184..02738a4 100644 --- a/scripts/tableFormulas.smoke.mjs +++ b/scripts/tableFormulas.smoke.mjs @@ -1,3 +1,4 @@ +import { mockFeaturePlugins } from "./pluginMocks.mjs"; // Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; @@ -69,14 +70,15 @@ await page.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TEST__ = { files, calls, emit, root }; }); +await mockFeaturePlugins(page); + async function quickOpen(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(); - if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) { - await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); - } + await page.locator('.live-writer').waitFor(); + await page.keyboard.press('Control+e'); await page.locator(".monaco-editor textarea").waitFor(); } @@ -98,7 +100,7 @@ try { window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] }); }, source); await quickOpen('formulas.md'); - await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); + await page.keyboard.press('Control+e'); await table.waitFor(); assert.equal(await result(1, 3).innerText(), '9.5'); assert.equal(await result(3, 3).innerText(), '17.5'); @@ -172,12 +174,12 @@ try { await checkFooter(); await page.setViewportSize({ width: 1440, height: 1000 }); await page.screenshot({ path: '.audit/table-formulas.png' }); - await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click(); - await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); + await page.keyboard.press('Control+e'); + await page.keyboard.press('Control+e'); assert.equal(await result(3, 1).innerText(), '12'); assert.equal(await result(3, 3).innerText(), '58'); for (const mode of ['Read', 'Split']) { - await page.getByRole('button', { name: mode, exact: true }).click(); + await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight'); const preview = page.locator('.md-page table').first(); await preview.waitFor(); assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58'); diff --git a/scripts/tableFormulas.spec.ts b/scripts/tableFormulas.spec.ts index 795e2e7..707e90f 100644 --- a/scripts/tableFormulas.spec.ts +++ b/scripts/tableFormulas.spec.ts @@ -1,6 +1,15 @@ import assert from "node:assert/strict"; -import test from "node:test"; -import { cellAddress, evaluateTableFormulas } from "../src/lib/editor/tableFormulas.ts"; +import test, { before, after } from "node:test"; +import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; +import { activate } from "../plugins/table-formulas/index.ts"; +const session = new ExternalSession("runestone.table-formulas", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, +}, () => {}, () => {}); +before(() => session.start({ activate })); +after(() => session.stop()); +import { cellAddress, evaluateTableFormulas } from "../plugins/table-formulas/formulas.ts"; import { tableCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts"; import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts"; diff --git a/scripts/terminal.smoke.mjs b/scripts/terminal.smoke.mjs index e94d78a..3f38d48 100644 --- a/scripts/terminal.smoke.mjs +++ b/scripts/terminal.smoke.mjs @@ -1,3 +1,4 @@ +import { mockFeaturePlugins } from "./pluginMocks.mjs"; // Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; @@ -71,6 +72,8 @@ await page.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TEST__ = { files, calls, emit, root }; }); +await mockFeaturePlugins(page); + const count = command => page.evaluate(command => window.__TEST__.calls.filter(c => c.command === command).length, command); const waitCount = (command, n) => page.waitForFunction(({ command, n }) => window.__TEST__.calls.filter(c => c.command === command).length === n, { command, n }); @@ -78,7 +81,7 @@ const click = name => page.getByRole("button", { name, exact: true }).click(); const menu = name => page.getByRole("menuitem", { name, exact: true }).click(); const writes = () => page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_write").map(c => c.args.data).join("")); try { - await page.goto("http://127.0.0.1:1420"); + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); await page.getByText("smoke-workspace", { exact: true }).waitFor(); await click("Terminal"); await waitCount("pty_open", 1); @@ -181,7 +184,7 @@ try { await waitCount("pty_open", 8); await page.keyboard.press("Control+Shift+Alt+Backquote"); await waitCount("pty_new_window", 2); - await page.goto("http://127.0.0.1:1420/?terminalWindow=C%3A%5Csmoke-workspace"); + await page.goto((process.env.SMOKE_URL || "http://127.0.0.1:1420") + "/?terminalWindow=C%3A%5Csmoke-workspace"); await waitCount("pty_open", 1); assert.equal(await count("workspace_open"), 0); assert.equal(await page.getByRole("button", { name: "Close terminal window", exact: true }).count(), 1); diff --git a/scripts/terminal.spec.ts b/scripts/terminal.spec.ts index 4432298..32ce593 100644 --- a/scripts/terminal.spec.ts +++ b/scripts/terminal.spec.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../src/lib/terminal/model.ts"; +import { directoryCommand, fileCommand, parseTasks, quoteShell, remember, terminalShortcut } from "../plugins/terminal/model.ts"; test("paths are shell-quoted without evaluating metacharacters", () => { assert.equal(directoryCommand("C:\\a'b\\$notes", "powershell"), "Set-Location -LiteralPath 'C:\\a''b\\$notes'"); diff --git a/scripts/workbench.smoke.mjs b/scripts/workbench.smoke.mjs index c67b998..e786cdc 100644 --- a/scripts/workbench.smoke.mjs +++ b/scripts/workbench.smoke.mjs @@ -1,3 +1,4 @@ +import { mockFeaturePlugins } from "./pluginMocks.mjs"; // Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; @@ -71,6 +72,8 @@ await page.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TEST__ = { files, calls, emit, root }; }); +await mockFeaturePlugins(page); + async function quickOpen(name) { await page.keyboard.press("Control+p"); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index c4cb1c5..2c12ea9 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3032,7 +3032,7 @@ dependencies = [ [[package]] name = "runestone" -version = "0.1.3" +version = "0.1.4" dependencies = [ "base64 0.23.1", "dunce", @@ -3041,12 +3041,15 @@ dependencies = [ "portable-pty", "serde", "serde_json", + "sha2", "tauri", "tauri-build", "tauri-plugin-dialog", "tauri-plugin-opener", "thiserror 2.0.20", + "uuid", "windows-sys 0.61.2", + "zip", ] [[package]] @@ -4294,6 +4297,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typeid" version = "1.0.3" @@ -5341,6 +5350,20 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap 2.14.2", + "memchr", + "typed-path", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" @@ -5353,6 +5376,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zvariant" version = "5.15.0" diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 31d8a11..2cf096c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runestone" -version = "0.1.3" +version = "0.1.4" description = "Writing workspace plus script editor" authors = ["you"] edition = "2021" @@ -25,6 +25,9 @@ tauri-plugin-dialog = "2.7.3" windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } base64 = "0.23.1" portable-pty = "0.9.0" +zip = { version = "8.6.0", default-features = false, features = ["deflate"] } +sha2 = "0.10" +uuid = { version = "1", features = ["v4"] } # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration diff --git a/src-tauri/build.rs b/src-tauri/build.rs index e8ec99f..fab3cbf 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -19,6 +19,19 @@ fn main() { "workspace_abs_path", "workspace_reveal", "workspace_search", + "plugins_snapshot", + "plugins_choose", + "plugins_cancel", + "plugins_install", + "plugins_set_enabled", + "plugins_load", + "plugins_release", + "plugins_prepare_remove", + "plugins_remove", + "plugins_retry_remove", + "plugins_reveal", + "plugins_data", + "plugins_asset", "pty_open", "pty_write", "pty_resize", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index a68ab99..0eb9aaa 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -29,6 +29,19 @@ "allow-workspace-abs-path", "allow-workspace-reveal", "allow-workspace-search", + "allow-plugins-snapshot", + "allow-plugins-choose", + "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-pty-open", "allow-pty-write", "allow-pty-resize", diff --git a/src-tauri/permissions/autogenerated/plugins_asset.toml b/src-tauri/permissions/autogenerated/plugins_asset.toml new file mode 100644 index 0000000..21b9558 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_asset.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-asset" +description = "Enables the plugins_asset command without any pre-configured scope." +commands.allow = ["plugins_asset"] + +[[permission]] +identifier = "deny-plugins-asset" +description = "Denies the plugins_asset command without any pre-configured scope." +commands.deny = ["plugins_asset"] diff --git a/src-tauri/permissions/autogenerated/plugins_cancel.toml b/src-tauri/permissions/autogenerated/plugins_cancel.toml new file mode 100644 index 0000000..280c605 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_cancel.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-cancel" +description = "Enables the plugins_cancel command without any pre-configured scope." +commands.allow = ["plugins_cancel"] + +[[permission]] +identifier = "deny-plugins-cancel" +description = "Denies the plugins_cancel command without any pre-configured scope." +commands.deny = ["plugins_cancel"] diff --git a/src-tauri/permissions/autogenerated/plugins_choose.toml b/src-tauri/permissions/autogenerated/plugins_choose.toml new file mode 100644 index 0000000..c6de7fa --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_choose.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-choose" +description = "Enables the plugins_choose command without any pre-configured scope." +commands.allow = ["plugins_choose"] + +[[permission]] +identifier = "deny-plugins-choose" +description = "Denies the plugins_choose command without any pre-configured scope." +commands.deny = ["plugins_choose"] diff --git a/src-tauri/permissions/autogenerated/plugins_data.toml b/src-tauri/permissions/autogenerated/plugins_data.toml new file mode 100644 index 0000000..b41e86e --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_data.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-data" +description = "Enables the plugins_data command without any pre-configured scope." +commands.allow = ["plugins_data"] + +[[permission]] +identifier = "deny-plugins-data" +description = "Denies the plugins_data command without any pre-configured scope." +commands.deny = ["plugins_data"] diff --git a/src-tauri/permissions/autogenerated/plugins_install.toml b/src-tauri/permissions/autogenerated/plugins_install.toml new file mode 100644 index 0000000..878901d --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_install.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-install" +description = "Enables the plugins_install command without any pre-configured scope." +commands.allow = ["plugins_install"] + +[[permission]] +identifier = "deny-plugins-install" +description = "Denies the plugins_install command without any pre-configured scope." +commands.deny = ["plugins_install"] diff --git a/src-tauri/permissions/autogenerated/plugins_load.toml b/src-tauri/permissions/autogenerated/plugins_load.toml new file mode 100644 index 0000000..1b7be5b --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_load.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-load" +description = "Enables the plugins_load command without any pre-configured scope." +commands.allow = ["plugins_load"] + +[[permission]] +identifier = "deny-plugins-load" +description = "Denies the plugins_load command without any pre-configured scope." +commands.deny = ["plugins_load"] diff --git a/src-tauri/permissions/autogenerated/plugins_prepare_remove.toml b/src-tauri/permissions/autogenerated/plugins_prepare_remove.toml new file mode 100644 index 0000000..9f62420 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_prepare_remove.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-prepare-remove" +description = "Enables the plugins_prepare_remove command without any pre-configured scope." +commands.allow = ["plugins_prepare_remove"] + +[[permission]] +identifier = "deny-plugins-prepare-remove" +description = "Denies the plugins_prepare_remove command without any pre-configured scope." +commands.deny = ["plugins_prepare_remove"] diff --git a/src-tauri/permissions/autogenerated/plugins_release.toml b/src-tauri/permissions/autogenerated/plugins_release.toml new file mode 100644 index 0000000..663fe16 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_release.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-release" +description = "Enables the plugins_release command without any pre-configured scope." +commands.allow = ["plugins_release"] + +[[permission]] +identifier = "deny-plugins-release" +description = "Denies the plugins_release command without any pre-configured scope." +commands.deny = ["plugins_release"] diff --git a/src-tauri/permissions/autogenerated/plugins_remove.toml b/src-tauri/permissions/autogenerated/plugins_remove.toml new file mode 100644 index 0000000..a12e805 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_remove.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-remove" +description = "Enables the plugins_remove command without any pre-configured scope." +commands.allow = ["plugins_remove"] + +[[permission]] +identifier = "deny-plugins-remove" +description = "Denies the plugins_remove command without any pre-configured scope." +commands.deny = ["plugins_remove"] diff --git a/src-tauri/permissions/autogenerated/plugins_retry_remove.toml b/src-tauri/permissions/autogenerated/plugins_retry_remove.toml new file mode 100644 index 0000000..463d0fa --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_retry_remove.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-retry-remove" +description = "Enables the plugins_retry_remove command without any pre-configured scope." +commands.allow = ["plugins_retry_remove"] + +[[permission]] +identifier = "deny-plugins-retry-remove" +description = "Denies the plugins_retry_remove command without any pre-configured scope." +commands.deny = ["plugins_retry_remove"] diff --git a/src-tauri/permissions/autogenerated/plugins_reveal.toml b/src-tauri/permissions/autogenerated/plugins_reveal.toml new file mode 100644 index 0000000..2311d1d --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_reveal.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-reveal" +description = "Enables the plugins_reveal command without any pre-configured scope." +commands.allow = ["plugins_reveal"] + +[[permission]] +identifier = "deny-plugins-reveal" +description = "Denies the plugins_reveal command without any pre-configured scope." +commands.deny = ["plugins_reveal"] diff --git a/src-tauri/permissions/autogenerated/plugins_set_enabled.toml b/src-tauri/permissions/autogenerated/plugins_set_enabled.toml new file mode 100644 index 0000000..13ec270 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_set_enabled.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-set-enabled" +description = "Enables the plugins_set_enabled command without any pre-configured scope." +commands.allow = ["plugins_set_enabled"] + +[[permission]] +identifier = "deny-plugins-set-enabled" +description = "Denies the plugins_set_enabled command without any pre-configured scope." +commands.deny = ["plugins_set_enabled"] diff --git a/src-tauri/permissions/autogenerated/plugins_snapshot.toml b/src-tauri/permissions/autogenerated/plugins_snapshot.toml new file mode 100644 index 0000000..766f141 --- /dev/null +++ b/src-tauri/permissions/autogenerated/plugins_snapshot.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-plugins-snapshot" +description = "Enables the plugins_snapshot command without any pre-configured scope." +commands.allow = ["plugins_snapshot"] + +[[permission]] +identifier = "deny-plugins-snapshot" +description = "Denies the plugins_snapshot command without any pre-configured scope." +commands.deny = ["plugins_snapshot"] diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index dcf82e5..32217aa 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ mod pty; +mod plugins; mod workspace; use pty::PtyState; @@ -12,6 +13,7 @@ pub fn run() { .plugin(tauri_plugin_dialog::init()) .manage(WorkspaceState::new()) .manage(PtyState::new()) + .manage(plugins::PluginState::default()) .invoke_handler(tauri::generate_handler![ workspace::workspace_open, workspace::workspace_open_window, @@ -30,6 +32,19 @@ pub fn run() { workspace::workspace_abs_path, workspace::workspace_reveal, workspace::workspace_search, + plugins::plugins_snapshot, + plugins::plugins_choose, + plugins::plugins_cancel, + plugins::plugins_install, + plugins::plugins_set_enabled, + plugins::plugins_load, + plugins::plugins_release, + plugins::plugins_prepare_remove, + plugins::plugins_remove, + plugins::plugins_retry_remove, + plugins::plugins_reveal, + plugins::plugins_data, + plugins::plugins_asset, pty::pty_open, pty::pty_write, pty::pty_resize, @@ -43,6 +58,7 @@ pub fn run() { .run(|app, event| { if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event { app.state::().close_window(label); + app.state::().close_window(label); app.state::().close_window(label); } if matches!(event, tauri::RunEvent::Exit) { diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs new file mode 100644 index 0000000..04e4f79 --- /dev/null +++ b/src-tauri/src/plugins.rs @@ -0,0 +1,1485 @@ +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::Read, + path::{Path, PathBuf}, + sync::Mutex, + time::{Duration, Instant}, +}; +use tauri::{AppHandle, Emitter, Manager, State}; +use tauri_plugin_dialog::DialogExt; +use tauri_plugin_opener::OpenerExt; +use uuid::Uuid; + +type Result = std::result::Result; +const MAX_FILES: usize = 5000; +const MAX_FILE: u64 = 25 * 1024 * 1024; +const MAX_TOTAL: usize = 100 * 1024 * 1024; +fn fail(error: impl std::fmt::Display) -> String { + error.to_string() +} +fn uid() -> String { + Uuid::new_v4().to_string() +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Manifest { + schema_version: u32, + pub id: String, + pub name: String, + pub author: String, + pub description: String, + pub version: String, + api_version: u32, + entry: String, + access: String, +} +#[derive(Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +struct Installed { + manifest: Manifest, + hash: String, + enabled: bool, + #[serde(default)] + removal: Option, + #[serde(default)] + removal_files: BTreeMap, +} +#[derive(Default, Serialize, Deserialize)] +struct Catalog { + #[serde(default)] + plugins: BTreeMap, +} +#[derive(Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PluginRow { + pub manifest: Manifest, + pub hash: String, + pub enabled: bool, + pub path: String, + pub error: Option, + pub removal: bool, +} +#[derive(Serialize)] +pub struct Snapshot { + pub root: String, + pub plugins: Vec, +} +#[derive(Clone, Serialize)] +pub struct CandidateRow { + pub token: String, + pub source: String, + pub manifest: Option, + pub error: Option, +} +struct Candidate { + owner: String, + source: PathBuf, + directory: PathBuf, + hash: String, + manifest: Manifest, + created: Instant, +} +#[derive(Clone, Serialize)] +pub struct RemovalPlan { + pub token: String, + pub plugin: PluginRow, +} +struct Plan { + owner: String, + id: String, + hash: String, + created: Instant, +} +#[derive(Serialize)] +pub struct InstallResult { + pub name: String, + pub error: Option, +} +#[derive(Debug)] +struct Package { + manifest: Manifest, + files: BTreeMap>, + hash: String, +} +struct Service { + root: PathBuf, + catalog: Catalog, + candidates: BTreeMap, + plans: BTreeMap, + leases: BTreeMap>, + cleanup_errors: BTreeMap, + removing: BTreeMap, +} +#[derive(Default)] +pub struct PluginState { + inner: Mutex>, +} + +fn normal_component(name: &str) -> bool { + if name.is_empty() || name == "." || name == ".." || name.ends_with('.') || name.len() > 120 { + return false; + } + if !name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) + { + return false; + } + let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase(); + !matches!( + stem.as_str(), + "CON" + | "PRN" + | "AUX" + | "NUL" + | "COM1" + | "COM2" + | "COM3" + | "COM4" + | "COM5" + | "COM6" + | "COM7" + | "COM8" + | "COM9" + | "LPT1" + | "LPT2" + | "LPT3" + | "LPT4" + | "LPT5" + | "LPT6" + | "LPT7" + | "LPT8" + | "LPT9" + ) +} +fn valid_id(id: &str) -> bool { + normal_component(id) + && id.as_bytes()[0].is_ascii_lowercase() + && id + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || b".-".contains(&c)) +} +fn relative(name: &str) -> Result { + if name.len() > 180 || !name.split('/').all(normal_component) { + return Err(format!("Invalid package path: {name}")); + } + Ok(name.split('/').collect()) +} +fn plain(path: &Path) -> Result { + let meta = fs::symlink_metadata(path).map_err(fail)?; + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + if meta.file_attributes() & 0x400 != 0 { + return Err("Links and junctions are not allowed in plugin paths.".into()); + } + } + if meta.file_type().is_symlink() { + return Err("Links are not allowed in plugin paths.".into()); + } + Ok(meta) +} +fn bounded(path: &Path, limit: u64) -> Result> { + let meta = plain(path)?; + if !meta.is_file() || meta.len() > limit { + return Err("The package contains an invalid or oversized file.".into()); + } + let mut data = Vec::new(); + fs::File::open(path) + .map_err(fail)? + .take(limit + 1) + .read_to_end(&mut data) + .map_err(fail)?; + if data.len() as u64 > limit { + return Err("The file exceeds the size limit.".into()); + } + Ok(data) +} +fn add_file( + files: &mut BTreeMap>, + names: &mut BTreeSet, + total: &mut usize, + name: String, + bytes: Vec, +) -> Result<()> { + relative(&name)?; + if !names.insert(name.to_ascii_lowercase()) { + return Err("The package contains duplicate file paths.".into()); + } + *total += bytes.len(); + if files.len() >= MAX_FILES || bytes.len() as u64 > MAX_FILE || *total > MAX_TOTAL { + return Err("The package exceeds the file count or size limit.".into()); + } + files.insert(name, bytes); + Ok(()) +} +fn walk( + root: &Path, + directory: &Path, + files: &mut BTreeMap>, + names: &mut BTreeSet, + total: &mut usize, + count: &mut usize, +) -> Result<()> { + plain(directory)?; + for entry in fs::read_dir(directory).map_err(fail)? { + let path = entry.map_err(fail)?.path(); + *count += 1; + if *count > MAX_FILES { + return Err("The package contains too many entries.".into()); + } + let name = path + .strip_prefix(root) + .map_err(fail)? + .to_str() + .ok_or("The package path is not UTF-8.")? + .replace('\\', "/"); + relative(&name)?; + let meta = plain(&path)?; + if meta.is_dir() { + walk(root, &path, files, names, total, count)?; + } else { + add_file(files, names, total, name, bounded(&path, MAX_FILE)?)?; + } + } + Ok(()) +} +fn fingerprint(files: &BTreeMap>) -> String { + let mut hash = Sha256::new(); + for (name, bytes) in files { + hash.update((name.len() as u64).to_le_bytes()); + hash.update(name.as_bytes()); + hash.update((bytes.len() as u64).to_le_bytes()); + hash.update(bytes); + } + format!("{:x}", hash.finalize()) +} +fn directory_files(path: &Path) -> Result>> { + let mut files = BTreeMap::new(); + walk(path, path, &mut files, &mut BTreeSet::new(), &mut 0, &mut 0)?; + Ok(files) +} +fn tree_hash(path: &Path) -> Result { + Ok(fingerprint(&directory_files(path)?)) +} +fn package(source: &Path) -> Result { + let source = if source.file_name().is_some_and(|n| n == "plugin.json") { + source.parent().ok_or("Missing plugin folder.")? + } else { + source + }; + let mut files = BTreeMap::new(); + let mut names = BTreeSet::new(); + let mut total = 0; + let meta = plain(source)?; + if meta.is_dir() { + walk(source, source, &mut files, &mut names, &mut total, &mut 0)?; + } else { + if source.extension().and_then(|s| s.to_str()) != Some("runestone-plugin") { + return Err("Select a .runestone-plugin package or plugin.json.".into()); + } + if meta.len() > MAX_TOTAL as u64 { + return Err("The archive exceeds 100 MiB.".into()); + } + let mut archive = + zip::ZipArchive::new(fs::File::open(source).map_err(fail)?).map_err(fail)?; + if archive.len() > MAX_FILES { + return Err("The archive contains too many entries.".into()); + } + let mut archive_names = BTreeSet::new(); + for index in 0..archive.len() { + let mut file = archive.by_index(index).map_err(fail)?; + let name = std::str::from_utf8(file.name_raw()) + .map_err(fail)? + .trim_end_matches('/') + .to_string(); + relative(&name)?; + if !archive_names.insert(name.to_ascii_lowercase()) { + return Err("The archive contains duplicate paths.".into()); + } + if file.unix_mode().is_some_and(|m| { + m & 0o170000 != 0 && m & 0o170000 != 0o100000 && m & 0o170000 != 0o040000 + }) { + return Err("Archive links and special files are not allowed.".into()); + } + if file.is_dir() { + continue; + } + if file.size() > MAX_FILE { + return Err("An archive file exceeds 25 MiB.".into()); + } + let mut bytes = Vec::new(); + file.by_ref() + .take(MAX_FILE + 1) + .read_to_end(&mut bytes) + .map_err(fail)?; + add_file(&mut files, &mut names, &mut total, name, bytes)?; + } + } + let bytes = files + .get("plugin.json") + .ok_or("The package needs plugin.json at its root.")?; + if bytes.len() > 64 * 1024 { + return Err("The manifest exceeds 64 KiB.".into()); + } + let manifest: Manifest = serde_json::from_slice(bytes).map_err(fail)?; + if !valid_id(&manifest.id) { + return Err("The plugin ID is invalid.".into()); + } + if manifest.schema_version != 1 || manifest.api_version != 1 || manifest.access != "full-app" { + return Err("This plugin needs an unsupported schema, API version, or access mode.".into()); + } + if [ + &manifest.name, + &manifest.author, + &manifest.description, + &manifest.version, + ] + .iter() + .any(|v| v.trim().is_empty() || v.len() > 1000) + { + return Err("The manifest needs a name, author, description, and version.".into()); + } + if manifest.version.split('.').count() != 3 + || !manifest + .version + .split('.') + .all(|n| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit())) + { + return Err("Use a plugin version such as 1.0.0.".into()); + } + relative(&manifest.entry)?; + if !manifest.entry.ends_with(".js") && !manifest.entry.ends_with(".mjs") { + return Err("The entry must be a compiled JavaScript module.".into()); + } + std::str::from_utf8( + files + .get(&manifest.entry) + .ok_or("The entry module is missing.")?, + ) + .map_err(fail)?; + let hash = fingerprint(&files); + Ok(Package { + manifest, + files, + hash, + }) +} +fn safe_child(parent: &Path, child: &Path) -> Result<()> { + plain(parent)?; + plain(child)?; + let parent = dunce::canonicalize(parent).map_err(fail)?; + let resolved = dunce::canonicalize(child).map_err(fail)?; + if resolved.parent() != Some(parent.as_path()) { + return Err("The plugin path is outside its managed directory.".into()); + } + Ok(()) +} +fn erase(parent: &Path, target: &Path) -> Result<()> { + safe_child(parent, target)?; + fn descend(path: &Path, boundary: &Path) -> Result<()> { + let meta = plain(path)?; + if !dunce::canonicalize(path) + .map_err(fail)? + .starts_with(boundary) + { + return Err("Removal escaped its managed directory.".into()); + } + if meta.is_dir() { + for item in fs::read_dir(path).map_err(fail)? { + descend(&item.map_err(fail)?.path(), boundary)?; + } + fs::remove_dir(path).map_err(fail) + } else { + fs::remove_file(path).map_err(fail) + } + } + let boundary = dunce::canonicalize(target).map_err(fail)?; + descend(target, &boundary) +} +impl Service { + fn open(root: PathBuf) -> Result { + fs::create_dir_all(&root).map_err(fail)?; + plain(&root)?; + for name in [ + "plugins", + "plugin-data", + "plugin-staging", + "plugin-removals", + ] { + let path = root.join(name); + if path.exists() { + plain(&path)?; + } else { + fs::create_dir(&path).map_err(fail)?; + } + safe_child(&root, &path)?; + } + let state = root.join("plugin-state.json"); + let catalog: Catalog = if state.exists() { + serde_json::from_slice(&bounded(&state, 4 * 1024 * 1024)?).map_err(fail)? + } else { + Catalog::default() + }; + for (id, record) in &catalog.plugins { + if !valid_id(id) || record.manifest.id != *id { + return Err("The plugin catalog contains an invalid ID.".into()); + } + if let Some(token) = &record.removal { + Uuid::parse_str(token).map_err(fail)?; + } + } + let mut service = Self { + root, + catalog, + candidates: BTreeMap::new(), + plans: BTreeMap::new(), + leases: BTreeMap::new(), + cleanup_errors: BTreeMap::new(), + removing: BTreeMap::new(), + }; + let mut recovered = false; + for (id, record) in &mut service.catalog.plugins { + if let Some(token) = &record.removal { + if service.root.join("plugins").join(id).exists() + && !service.root.join("plugin-removals").join(token).exists() + { + record.removal = None; + record.removal_files.clear(); + record.enabled = false; + recovered = true; + } + } + } + if recovered { + service.persist()?; + } + Ok(service) + } + fn directory(&self, name: &str) -> Result { + let path = self.root.join(name); + safe_child(&self.root, &path)?; + Ok(path) + } + fn persist(&self) -> Result<()> { + let path = self.root.join("plugin-state.json"); + if path.exists() { + plain(&path)?; + } + let temp = self.root.join(format!("plugin-state-{}.tmp", uid())); + let data = serde_json::to_vec_pretty(&self.catalog).map_err(fail)?; + use std::io::Write; + let mut file = fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&temp) + .map_err(fail)?; + file.write_all(&data).map_err(fail)?; + file.sync_all().map_err(fail)?; + drop(file); + fs::rename(&temp, path).map_err(fail) + } + fn row(&self, id: &str) -> Result { + let record = self + .catalog + .plugins + .get(id) + .ok_or("The plugin is not installed.")?; + let path = self.directory("plugins")?.join(id); + let checked = if record.removal.is_some() { + Err("Removal incomplete. Retry file cleanup.".into()) + } else { + safe_child(&self.directory("plugins")?, &path).and_then(|_| package(&path)) + }; + let mut manifest = record.manifest.clone(); + if let Ok(current) = &checked { + if current.manifest.id == id { + manifest = current.manifest.clone(); + } + } + let (hash, error) = match checked { + Ok(current) if current.manifest.id != id => ( + current.hash, + Some("The installed plugin ID changed.".into()), + ), + Ok(current) if current.hash != record.hash => ( + current.hash, + Some("Plugin files changed. Review them before enabling this plugin.".into()), + ), + Ok(current) => (current.hash, self.cleanup_errors.get(id).cloned()), + Err(error) => (record.hash.clone(), Some(error)), + }; + Ok(PluginRow { + manifest, + hash, + enabled: record.enabled && error.is_none() && !self.removing.contains_key(id), + path: path.to_string_lossy().into_owned(), + error, + removal: record.removal.is_some(), + }) + } + fn snapshot(&mut self) -> Result { + let mut changed = false; + let directory = self.directory("plugins")?; + for entry in fs::read_dir(&directory).map_err(fail)? { + let path = entry.map_err(fail)?.path(); + let id = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + if !valid_id(&id) || self.catalog.plugins.contains_key(&id) { + continue; + } + if let Ok(current) = safe_child(&directory, &path).and_then(|_| package(&path)) { + if current.manifest.id == id { + self.catalog.plugins.insert( + id, + Installed { + manifest: current.manifest, + hash: current.hash, + enabled: false, + removal: None, + removal_files: BTreeMap::new(), + }, + ); + changed = true; + } + } + } + let mut plugins = Vec::new(); + for id in self.catalog.plugins.keys().cloned().collect::>() { + if !directory.join(&id).exists() && self.catalog.plugins[&id].removal.is_none() { + self.catalog.plugins.remove(&id); + changed = true; + continue; + } + let row = self.row(&id)?; + if row.error.is_some() && self.catalog.plugins[&id].enabled { + self.catalog.plugins.get_mut(&id).unwrap().enabled = false; + changed = true; + } + plugins.push(row); + } + if changed { + self.persist()?; + } + Ok(Snapshot { + root: directory.to_string_lossy().into_owned(), + plugins, + }) + } + fn inspect(&mut self, owner: &str, source: PathBuf) -> CandidateRow { + let token = uid(); + let display = source.to_string_lossy().into_owned(); + let result = (|| { + let current = package(&source)?; + if self.catalog.plugins.contains_key(¤t.manifest.id) + || self + .directory("plugins")? + .join(¤t.manifest.id) + .exists() + { + return Err("This plugin ID is already installed. Uninstall it before installing another version.".into()); + } + let staging = self.directory("plugin-staging")?.join(&token); + fs::create_dir(&staging).map_err(fail)?; + for (name, bytes) in ¤t.files { + let target = staging.join(relative(name)?); + if self + .root + .join("plugins") + .join(¤t.manifest.id) + .join(relative(name)?) + .as_os_str() + .len() + > 240 + { + return Err("The installed path would exceed 240 characters.".into()); + } + fs::create_dir_all(target.parent().unwrap()).map_err(fail)?; + fs::write(target, bytes).map_err(fail)?; + } + let manifest = current.manifest.clone(); + self.candidates.insert( + token.clone(), + Candidate { + owner: owner.into(), + source, + directory: staging, + hash: current.hash, + manifest: manifest.clone(), + created: Instant::now(), + }, + ); + Ok(manifest) + })(); + match result { + Ok(manifest) => CandidateRow { + token, + source: display, + manifest: Some(manifest), + error: None, + }, + Err(error) => { + if let Ok(parent) = self.directory("plugin-staging") { + let target = parent.join(&token); + if target.exists() { + let _ = erase(&parent, &target); + } + } + CandidateRow { + token, + source: display, + manifest: None, + error: Some(error), + } + } + } + } + fn install(&mut self, owner: &str, token: &str, enabled: bool) -> Result { + let candidate = self + .candidates + .get(token) + .ok_or("Select the package again.")?; + if candidate.owner != owner || candidate.created.elapsed() > Duration::from_secs(1800) { + return Err("The package review expired. Select it again.".into()); + } + let id = candidate.manifest.id.clone(); + if self.catalog.plugins.contains_key(&id) { + return Err("This plugin ID is already installed.".into()); + } + if package(&candidate.source)?.hash != candidate.hash + || package(&candidate.directory)?.hash != candidate.hash + { + return Err("The package changed after review. Select it again.".into()); + } + let parent = self.directory("plugins")?; + let target = parent.join(&id); + if target.exists() { + return Err("The plugin directory already exists.".into()); + } + safe_child(&self.directory("plugin-staging")?, &candidate.directory)?; + // Persist disabled first. A crash cannot enable unreviewed or partial code. + self.catalog.plugins.insert( + id.clone(), + Installed { + manifest: candidate.manifest.clone(), + hash: candidate.hash.clone(), + enabled: false, + removal: None, + removal_files: BTreeMap::new(), + }, + ); + if let Err(error) = self.persist() { + self.catalog.plugins.remove(&id); + return Err(error); + } + let candidate = self.candidates.remove(token).unwrap(); + if let Err(error) = fs::rename(&candidate.directory, &target) { + self.catalog.plugins.remove(&id); + let _ = self.persist(); + return Err(fail(error)); + } + if enabled { + self.catalog.plugins.get_mut(&id).unwrap().enabled = true; + if let Err(error) = self.persist() { + self.catalog.plugins.get_mut(&id).unwrap().enabled = false; + return Err(format!("Installed but disabled: {error}")); + } + } + Ok(candidate.manifest.name) + } + fn prepare(&mut self, owner: &str, id: &str) -> Result { + if self.removing.contains_key(id) { + return Err("This plugin is already being removed.".into()); + } + let plugin = self.row(id)?; + if plugin.removal { + return Err("Retry cleanup for the confirmed removal.".into()); + } + // A corrupt package cannot expand the removal target beyond its recorded folder. + let current_hash = tree_hash(&self.directory("plugins")?.join(id))?; + let token = uid(); + self.plans.insert( + token.clone(), + Plan { + owner: owner.into(), + id: id.into(), + hash: current_hash, + created: Instant::now(), + }, + ); + Ok(RemovalPlan { token, plugin }) + } + fn begin_remove(&mut self, owner: &str, token: &str) -> Result { + let plan = self.plans.remove(token).ok_or("Start uninstall again.")?; + if plan.owner != owner || plan.created.elapsed() > Duration::from_secs(300) { + return Err( + "The removal plan expired or belongs to another window. Start uninstall again." + .into(), + ); + } + let parent = self.directory("plugins")?; + let target = parent.join(&plan.id); + safe_child(&parent, &target)?; + if tree_hash(&target)? != plan.hash { + return Err("Plugin files changed. Confirm uninstall again.".into()); + } + if self.removing.contains_key(&plan.id) { + return Err("This plugin is already being removed.".into()); + } + let record = self + .catalog + .plugins + .get_mut(&plan.id) + .ok_or("The plugin is not installed.")?; + let was_enabled = record.enabled; + record.enabled = false; + if let Err(error) = self.persist() { + self.catalog.plugins.get_mut(&plan.id).unwrap().enabled = was_enabled; + return Err(error); + } + self.removing.insert(plan.id.clone(), plan.hash); + Ok(plan.id) + } + fn finish_remove(&mut self, id: &str) -> Result<()> { + if self + .leases + .get(id) + .is_some_and(|windows| !windows.is_empty()) + { + return Err("Removal blocked. Close other RuneStone windows and try again.".into()); + } + if let Some(error) = self.cleanup_errors.get(id) { + return Err(format!( + "Cleanup failed. Restart RuneStone before removal. {error}" + )); + } + let parent = self.directory("plugins")?; + let target = parent.join(id); + safe_child(&parent, &target)?; + let current_files = directory_files(&target)?; + let current_hash = fingerprint(¤t_files); + if self.removing.get(id) != Some(¤t_hash) { + return Err("Plugin files changed during shutdown. Confirm uninstall again.".into()); + } + let token = uid(); + // This journal is the only authorization for recovery after a crash. + let record = self + .catalog + .plugins + .get_mut(id) + .ok_or("The plugin is not installed.")?; + record.removal = Some(token.clone()); + record.removal_files = current_files + .iter() + .map(|(name, bytes)| (name.clone(), format!("{:x}", Sha256::digest(bytes)))) + .collect(); + self.persist()?; + let destination = self.directory("plugin-removals")?.join(token); + if let Err(error) = fs::rename(&target, &destination) { + self.catalog.plugins.get_mut(id).unwrap().removal = None; + let _ = self.persist(); + return Err(fail(error)); + } + if tree_hash(&destination)? != current_hash { + return Err("Plugin files changed during removal. Inspect the removal directory before retrying.".into()); + } + self.retry_removal(id) + } + fn retry_removal(&mut self, id: &str) -> Result<()> { + let token = self + .catalog + .plugins + .get(id) + .and_then(|record| record.removal.clone()) + .ok_or("No confirmed removal exists.")?; + Uuid::parse_str(&token).map_err(fail)?; + let parent = self.directory("plugin-removals")?; + let target = parent.join(&token); + if self.directory("plugins")?.join(id).exists() { + return Err( + "Removal did not move the package. Restart and confirm uninstall again.".into(), + ); + } + if target.exists() { + safe_child(&parent, &target)?; + let expected = &self.catalog.plugins[id].removal_files; + for (name, bytes) in directory_files(&target)? { + if expected.get(&name) != Some(&format!("{:x}", Sha256::digest(bytes))) { + return Err(format!( + "Removal files changed. Inspect {} before retrying.", + target.display() + )); + } + } + erase(&parent, &target)?; + } + let old = self.catalog.plugins.remove(id).unwrap(); + if let Err(error) = self.persist() { + self.catalog.plugins.insert(id.into(), old); + return Err(error); + } + Ok(()) + } +} +impl PluginState { + fn with( + &self, + app: &AppHandle, + action: impl FnOnce(&mut Service) -> Result, + ) -> Result { + let mut guard = self.inner.lock().map_err(fail)?; + if guard.is_none() { + *guard = Some(Service::open(app.path().app_data_dir().map_err(fail)?)?); + } + action(guard.as_mut().unwrap()) + } + pub fn close_window(&self, owner: &str) { + if let Ok(mut guard) = self.inner.lock() { + if let Some(service) = guard.as_mut() { + for windows in service.leases.values_mut() { + windows.remove(owner); + } + service.plans.retain(|_, plan| plan.owner != owner); + let tokens: Vec<_> = service + .candidates + .iter() + .filter(|(_, candidate)| candidate.owner == owner) + .map(|(token, _)| token.clone()) + .collect(); + for token in tokens { + if let Some(candidate) = service.candidates.remove(&token) { + if let Ok(parent) = service.directory("plugin-staging") { + let _ = erase(&parent, &candidate.directory); + } + } + } + } + } + } +} +fn changed(app: &AppHandle) { + let _ = app.emit("plugins-changed", ()); +} + +#[tauri::command] +pub async fn plugins_snapshot(app: AppHandle, state: State<'_, PluginState>) -> Result { + state.with(&app, |service| service.snapshot()) +} + +#[tauri::command] +pub async fn plugins_choose( + app: AppHandle, + window: tauri::Window, + folder: bool, +) -> Result> { + let picker_app = app.clone(); + let source = tauri::async_runtime::spawn_blocking(move || { + let picker = picker_app + .dialog() + .file() + .set_title("Install RuneStone plugins"); + if folder { + picker.blocking_pick_folder() + } else { + picker + .add_filter("RuneStone plugins", &["runestone-plugin", "json"]) + .blocking_pick_file() + } + }) + .await + .map_err(fail)?; + let Some(source) = source else { + return Ok(Vec::new()); + }; + let source = source.into_path().map_err(fail)?; + app.state::().with(&app, |service| { + let mut paths = Vec::new(); + if source.is_dir() && !source.join("plugin.json").exists() { + plain(&source)?; + for (index, entry) in fs::read_dir(&source).map_err(fail)?.enumerate() { + if index >= 100 { + return Err("Choose a collection with at most 100 entries.".into()); + } + let path = entry.map_err(fail)?.path(); + if path.is_dir() + || path.extension().and_then(|n| n.to_str()) == Some("runestone-plugin") + { + paths.push(path); + } + } + if paths.len() > 100 { + return Err("Choose a collection with at most 100 plugins.".into()); + } + } else { + paths.push(source); + } + if paths.is_empty() { + return Err("No plugin packages or folders were found.".into()); + } + Ok(paths + .into_iter() + .map(|path| service.inspect(window.label(), path)) + .collect()) + }) +} +#[tauri::command] +pub async fn plugins_cancel( + app: AppHandle, + window: tauri::Window, + state: State<'_, PluginState>, + tokens: Vec, +) -> Result<()> { + state.with(&app, |service| { + for token in tokens { + if service + .candidates + .get(&token) + .is_some_and(|c| c.owner == window.label()) + { + let candidate = service.candidates.remove(&token).unwrap(); + let _ = erase(&service.directory("plugin-staging")?, &candidate.directory); + } + if service + .plans + .get(&token) + .is_some_and(|p| p.owner == window.label()) + { + service.plans.remove(&token); + } + } + Ok(()) + }) +} +#[tauri::command] +pub async fn plugins_install( + app: AppHandle, + window: tauri::Window, + state: State<'_, PluginState>, + tokens: Vec, + enabled: bool, +) -> Result> { + let result = state.with(&app, |service| { + Ok(tokens + .iter() + .map(|token| { + let name = service + .candidates + .get(token) + .map(|c| c.manifest.name.clone()) + .unwrap_or_else(|| "Plugin".into()); + InstallResult { + name, + error: service.install(window.label(), token, enabled).err(), + } + }) + .collect()) + }); + changed(&app); + result +} +#[tauri::command] +pub async fn plugins_set_enabled( + app: AppHandle, + state: State<'_, PluginState>, + id: String, + enabled: bool, + hash: Option, +) -> Result<()> { + state.with(&app, |service| { + if service.removing.contains_key(&id) { + return Err("Wait for plugin removal to finish.".into()); + } + let row = service.row(&id)?; + if row.removal { + return Err("Finish the confirmed removal first.".into()); + } + let old = service.catalog.plugins[&id].clone(); + if enabled { + if service.cleanup_errors.contains_key(&id) { + return Err("Restart RuneStone after the cleanup failure.".into()); + } + let current = package(&service.directory("plugins")?.join(&id))?; + if current.manifest.id != id || hash.as_deref() != Some(¤t.hash) { + return Err("Plugin files changed. Refresh and review them again.".into()); + } + let record = service.catalog.plugins.get_mut(&id).unwrap(); + record.hash = current.hash; + record.manifest = current.manifest; + } + service.catalog.plugins.get_mut(&id).unwrap().enabled = enabled; + if let Err(error) = service.persist() { + service.catalog.plugins.insert(id, old); + return Err(error); + } + Ok(()) + })?; + changed(&app); + Ok(()) +} +#[tauri::command] +pub async fn plugins_load( + app: AppHandle, + window: tauri::Window, + state: State<'_, PluginState>, + id: String, + hash: String, +) -> Result { + state.with(&app, |service| { + let row = service.row(&id)?; + if !row.enabled || row.hash != hash { + return Err("The plugin is disabled or changed.".into()); + } + let current = package(&service.directory("plugins")?.join(&id))?; + if current.hash != hash { + return Err("The plugin changed during loading.".into()); + } + service + .leases + .entry(id) + .or_default() + .insert(window.label().into()); + String::from_utf8(current.files[¤t.manifest.entry].clone()).map_err(fail) + }) +} +#[tauri::command] +pub async fn plugins_release( + app: AppHandle, + window: tauri::Window, + state: State<'_, PluginState>, + id: String, + error: Option, +) -> Result<()> { + state.with(&app, |service| { + if let Some(error) = error { + service.cleanup_errors.insert(id.clone(), error); + } + if let Some(windows) = service.leases.get_mut(&id) { + windows.remove(window.label()); + } + Ok(()) + }) +} +#[tauri::command] +pub async fn plugins_prepare_remove( + app: AppHandle, + window: tauri::Window, + state: State<'_, PluginState>, + id: String, +) -> Result { + state.with(&app, |service| service.prepare(window.label(), &id)) +} +#[tauri::command] +pub async fn plugins_remove(app: AppHandle, window: tauri::Window, token: String) -> Result<()> { + let id = app + .state::() + .with(&app, |service| service.begin_remove(window.label(), &token))?; + changed(&app); + let worker_app = app.clone(); + let result = tauri::async_runtime::spawn_blocking(move || { + let start = Instant::now(); + loop { + let leased = worker_app + .state::() + .with(&worker_app, |service| { + Ok(service + .leases + .get(&id) + .is_some_and(|windows| !windows.is_empty())) + })?; + if !leased || start.elapsed() > Duration::from_secs(10) { + break; + } + std::thread::sleep(Duration::from_millis(50)); + } + worker_app + .state::() + .with(&worker_app, |service| { + let result = service.finish_remove(&id); + service.removing.remove(&id); + result + }) + }) + .await + .map_err(fail)?; + changed(&app); + result +} +#[tauri::command] +pub async fn plugins_retry_remove( + app: AppHandle, + state: State<'_, PluginState>, + id: String, +) -> Result<()> { + let result = state.with(&app, |service| service.retry_removal(&id)); + changed(&app); + result +} +#[tauri::command] +pub async fn plugins_reveal( + app: AppHandle, + state: State<'_, PluginState>, + id: Option, +) -> Result<()> { + let open_directory = id.is_none(); + let path = state.with(&app, |service| { + let root = service.directory("plugins")?; + if let Some(id) = id { + if !service.catalog.plugins.contains_key(&id) { + return Err("The plugin is not installed.".into()); + } + let path = root.join(id); + safe_child(&root, &path)?; + Ok(path) + } else { + Ok(root) + } + })?; + if open_directory { + app.opener() + .open_path(path.to_string_lossy().into_owned(), None::<&str>) + .map_err(fail) + } else { + app.opener().reveal_item_in_dir(path).map_err(fail) + } +} +#[tauri::command] +pub async fn plugins_data( + app: AppHandle, + state: State<'_, PluginState>, + id: String, + value: Option, +) -> Result { + state.with(&app, |service| { + if !service.row(&id)?.enabled { + return Err("The plugin is disabled.".into()); + } + let parent = service.directory("plugin-data")?; + let dir = parent.join(&id); + if !dir.exists() { + fs::create_dir(&dir).map_err(fail)?; + } + safe_child(&parent, &dir)?; + let path = dir.join("settings.json"); + if let Some(value) = value { + if value.len() > 1024 * 1024 { + return Err("Plugin settings exceed 1 MiB.".into()); + } + serde_json::from_str::(&value).map_err(fail)?; + if path.exists() { + plain(&path)?; + } + let temp = dir.join(format!("{}.tmp", uid())); + fs::write(&temp, value).map_err(fail)?; + fs::rename(temp, &path).map_err(fail)?; + } + if path.exists() { + String::from_utf8(bounded(&path, 1024 * 1024)?).map_err(fail) + } else { + Ok("null".into()) + } + }) +} +#[tauri::command] +pub async fn plugins_asset( + app: AppHandle, + state: State<'_, PluginState>, + id: String, + path: String, +) -> Result { + use base64::Engine; + state.with(&app, |service| { + if !service.row(&id)?.enabled { + return Err("The plugin is disabled.".into()); + } + relative(&path)?; + let current = package(&service.directory("plugins")?.join(&id))?; + if current.hash != service.catalog.plugins[&id].hash { + return Err("Plugin assets changed. Review the package again.".into()); + } + let bytes = current + .files + .get(&path) + .ok_or("The plugin asset is missing.")?; + Ok(base64::engine::general_purpose::STANDARD.encode(bytes)) + }) +} +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + struct Fixture { + root: PathBuf, + service: Service, + source: PathBuf, + } + impl Fixture { + fn new() -> Self { + let root = std::env::temp_dir().join(format!("runestone-plugin-tests-{}", uid())); + fs::create_dir(&root).unwrap(); + let source = root.join("source"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("plugin.json"), r#"{"schemaVersion":1,"id":"org.test.demo","name":"Demo","author":"Test","description":"Test plugin","version":"1.0.0","apiVersion":1,"entry":"main.js","access":"full-app"}"#).unwrap(); + fs::write(source.join("main.js"), "export function activate() {}").unwrap(); + let service = Service::open(root.join("app")).unwrap(); + Self { + root, + service, + source, + } + } + fn install(&mut self, enabled: bool) -> String { + let row = self.service.inspect("main", self.source.clone()); + assert!(row.error.is_none(), "{:?}", row.error); + self.service.install("main", &row.token, enabled).unwrap(); + "org.test.demo".into() + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let root = dunce::canonicalize(&self.root).unwrap(); + let parent = dunce::canonicalize(std::env::temp_dir()).unwrap(); + assert_eq!(root.parent(), Some(parent.as_path())); + assert!(root + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("runestone-plugin-tests-")); + let _ = fs::remove_dir_all(root); + } + } + fn archive(path: &Path, entries: &[(&str, &[u8])]) { + let mut zip = zip::ZipWriter::new(fs::File::create(path).unwrap()); + for (name, data) in entries { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(data).unwrap(); + } + zip.finish().unwrap(); + } + #[test] + fn installs_directory_and_zip_without_changing_source() { + let mut f = Fixture::new(); + let original = package(&f.source).unwrap(); + let archive_path = f.root.join("demo.runestone-plugin"); + let entries: Vec<_> = original + .files + .iter() + .map(|(name, bytes)| (name.as_str(), bytes.as_slice())) + .collect(); + archive(&archive_path, &entries); + assert_eq!(package(&archive_path).unwrap().hash, original.hash); + let row = f.service.inspect("main", archive_path); + assert!(row.error.is_none()); + f.service.install("main", &row.token, false).unwrap(); + assert!(!f.service.row("org.test.demo").unwrap().enabled); + assert_eq!(package(&f.source).unwrap().hash, original.hash); + assert!(f.service.inspect("main", f.source.clone()).error.is_some()); + } + #[test] + fn feature_packages_use_the_standard_install_and_remove_lifecycle() { + for id in ["runestone.terminal", "runestone.table-formulas"] { + let mut f = Fixture::new(); + let manifest = fs::read_to_string(f.source.join("plugin.json")) + .unwrap() + .replace("org.test.demo", id); + fs::write(f.source.join("plugin.json"), manifest).unwrap(); + let reviewed = f.service.inspect("main", f.source.clone()); + assert!(reviewed.error.is_none()); + f.service.install("main", &reviewed.token, true).unwrap(); + assert!(f.service.row(id).unwrap().enabled); + let mut reopened = Service::open(f.root.join("app")).unwrap(); + assert_eq!(reopened.snapshot().unwrap().plugins.len(), 1); + let plan = reopened.prepare("main", id).unwrap(); + reopened.begin_remove("main", &plan.token).unwrap(); + reopened.finish_remove(id).unwrap(); + assert!(reopened.snapshot().unwrap().plugins.is_empty()); + assert!(f.source.join("plugin.json").exists()); + } + } + #[test] + fn old_bundled_preferences_do_not_restore_or_enable_packages() { + let mut f = Fixture::new(); + fs::write(f.root.join("app/plugin-state.json"), + r#"{"plugins":{},"bundled":{"runestone.terminal":true,"runestone.table-formulas":true}}"#).unwrap(); + f.service = Service::open(f.root.join("app")).unwrap(); + let snapshot = f.service.snapshot().unwrap(); + assert!(snapshot.plugins.is_empty()); + assert!(serde_json::to_value(snapshot) + .unwrap() + .get("bundled") + .is_none()); + } + #[test] + fn validates_paths_ids_limits_and_versions() { + for name in [ + "../file", + "/file", + "C:/file", + "a\\b", + "a/../b", + "CON", + "x/NUL.txt", + "a.", + "a:stream", + "a//b", + ] { + assert!(relative(name).is_err(), "{name}"); + } + for id in ["", "../x", "CON", "X.test", "a."] { + assert!(!valid_id(id), "{id}"); + } + let f = Fixture::new(); + let path = f.root.join("bad.runestone-plugin"); + archive(&path, &[("../outside", b"test")]); + assert!(package(&path).is_err()); + assert!(!f.root.join("outside").exists()); + archive(&path, &[("main.js", b"a"), ("MAIN.js", b"b")]); + assert!(package(&path).unwrap_err().contains("duplicate")); + let manifest = fs::read_to_string(f.source.join("plugin.json")) + .unwrap() + .replace("\"apiVersion\":1", "\"apiVersion\":99"); + fs::write(f.source.join("plugin.json"), manifest).unwrap(); + assert!(package(&f.source).is_err()); + let huge = fs::File::create(f.source.join("big.bin")).unwrap(); + huge.set_len(MAX_FILE + 1).unwrap(); + assert!(package(&f.source).is_err()); + } + #[test] + fn source_changes_expired_reviews_and_other_windows_cannot_install() { + let mut f = Fixture::new(); + let row = f.service.inspect("main", f.source.clone()); + assert!(f.service.install("other", &row.token, true).is_err()); + fs::write(f.source.join("main.js"), "changed").unwrap(); + assert!(f.service.install("main", &row.token, true).is_err()); + assert!(!f + .service + .directory("plugins") + .unwrap() + .join("org.test.demo") + .exists()); + let row = f.service.inspect("main", f.source.clone()); + f.service.candidates.get_mut(&row.token).unwrap().created = + Instant::now() - Duration::from_secs(1900); + assert!(f.service.install("main", &row.token, false).is_err()); + } + #[test] + fn confirmation_uses_a_valid_plan_and_cancel_does_not_disable() { + let mut f = Fixture::new(); + let id = f.install(true); + assert!(f.service.begin_remove("main", "missing-plan").is_err()); + let plan = f.service.prepare("main", &id).unwrap(); + assert!(f.service.row(&id).unwrap().enabled); + f.service.plans.remove(&plan.token); + assert!(f.service.begin_remove("main", &plan.token).is_err()); + assert!(f.service.row(&id).unwrap().enabled); + let plan = f.service.prepare("main", &id).unwrap(); + assert!(f.service.begin_remove("other", &plan.token).is_err()); + assert!(f.service.row(&id).unwrap().enabled); + let plan = f.service.prepare("main", &id).unwrap(); + f.service.plans.get_mut(&plan.token).unwrap().created = + Instant::now() - Duration::from_secs(301); + assert!(f.service.begin_remove("main", &plan.token).is_err()); + assert!(f.service.row(&id).unwrap().enabled); + let plan = f.service.prepare("main", &id).unwrap(); + f.service.begin_remove("main", &plan.token).unwrap(); + assert!(f.service.begin_remove("main", &plan.token).is_err()); + f.service.finish_remove(&id).unwrap(); + assert!(!f.service.directory("plugins").unwrap().join(id).exists()); + } + #[test] + fn changed_target_requires_new_confirmation() { + let mut f = Fixture::new(); + let id = f.install(true); + let plan = f.service.prepare("main", &id).unwrap(); + let path = f.service.directory("plugins").unwrap().join(&id); + fs::write(path.join("main.js"), "changed").unwrap(); + assert!(f.service.begin_remove("main", &plan.token).is_err()); + assert!(path.exists()); + let plan = f.service.prepare("main", &id).unwrap(); + f.service.begin_remove("main", &plan.token).unwrap(); + fs::write(path.join("main.js"), "changed again").unwrap(); + assert!(f.service.finish_remove(&id).is_err()); + assert!(path.exists()); + } + #[test] + fn removal_waits_for_every_window_and_preserves_user_data() { + let mut f = Fixture::new(); + let id = f.install(true); + let data = f.service.directory("plugin-data").unwrap().join(&id); + fs::create_dir(&data).unwrap(); + fs::write(data.join("settings.json"), "retained").unwrap(); + let document = f.root.join("note.md"); + fs::write(&document, "retained note").unwrap(); + let plan = f.service.prepare("main", &id).unwrap(); + f.service.begin_remove("main", &plan.token).unwrap(); + f.service + .leases + .insert(id.clone(), BTreeSet::from(["main".into(), "other".into()])); + assert!(f.service.finish_remove(&id).is_err()); + f.service.leases.get_mut(&id).unwrap().remove("main"); + assert!(f.service.finish_remove(&id).is_err()); + f.service.leases.remove(&id); + f.service.cleanup_errors.insert(id.clone(), "Failed".into()); + assert!(f.service.finish_remove(&id).is_err()); + f.service.cleanup_errors.clear(); + f.service.finish_remove(&id).unwrap(); + assert_eq!( + fs::read_to_string(data.join("settings.json")).unwrap(), + "retained" + ); + assert_eq!(fs::read_to_string(document).unwrap(), "retained note"); + assert!(f.source.join("main.js").exists()); + } + #[test] + fn crash_before_move_preserves_package_and_resets_removal() { + let mut f = Fixture::new(); + let id = f.install(true); + let record = f.service.catalog.plugins.get_mut(&id).unwrap(); + record.enabled = false; + record.removal = Some(uid()); + f.service.persist().unwrap(); + let recovered = Service::open(f.service.root.clone()).unwrap(); + assert!(recovered.catalog.plugins[&id].removal.is_none()); + assert!(!recovered.row(&id).unwrap().enabled); + } + #[test] + fn partial_removal_recovery_checks_remaining_files() { + let mut f = Fixture::new(); + let id = f.install(false); + let source = f.service.directory("plugins").unwrap().join(&id); + let files = directory_files(&source).unwrap(); + let token = uid(); + let record = f.service.catalog.plugins.get_mut(&id).unwrap(); + record.removal = Some(token.clone()); + record.removal_files = files + .iter() + .map(|(name, bytes)| (name.clone(), format!("{:x}", Sha256::digest(bytes)))) + .collect(); + f.service.persist().unwrap(); + let target = f.service.directory("plugin-removals").unwrap().join(token); + fs::rename(source, &target).unwrap(); + fs::remove_file(target.join("main.js")).unwrap(); + fs::write(target.join("unexpected.txt"), "keep").unwrap(); + let mut recovered = Service::open(f.service.root.clone()).unwrap(); + assert!(recovered.retry_removal(&id).is_err()); + assert!(target.join("unexpected.txt").exists()); + fs::remove_file(target.join("unexpected.txt")).unwrap(); + recovered.retry_removal(&id).unwrap(); + assert!(!target.exists()); + assert!(f.service.directory("plugin-data").unwrap().exists()); + } + #[test] + fn malformed_catalog_cannot_create_a_deletion_target() { + let f = Fixture::new(); + fs::write(f.service.root.join("plugin-state.json"), "{broken").unwrap(); + assert!(Service::open(f.service.root.clone()).is_err()); + assert!(safe_child(&f.service.directory("plugins").unwrap(), &f.source).is_err()); + } +} diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index d990f21..5196e37 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -456,7 +456,11 @@ pub fn workspace_open( #[tauri::command] pub fn workspace_list(window: tauri::Window, state: State, rel: String) -> WsResult> { let root = current_root(&state, window.label())?; - let dir = resolve_existing(&root, &rel)?; + list_entries(&root, &rel) +} + +fn list_entries(root: &Path, rel: &str) -> WsResult> { + let dir = resolve_existing(root, rel)?; if !dir.is_dir() { return Err(err("path is not a folder")); } @@ -464,12 +468,7 @@ pub fn workspace_list(window: tauri::Window, state: State, rel: let mut entries = Vec::new(); let walker = ignore::WalkBuilder::new(&dir) .max_depth(Some(1)) - .hidden(false) - .git_ignore(true) - .require_git(false) - .git_global(true) - .git_exclude(true) - .parents(true) + .standard_filters(false) .build(); for result in walker { @@ -788,17 +787,18 @@ pub struct SearchHit { #[tauri::command] pub fn workspace_search(window: tauri::Window, state: State, query: String) -> WsResult> { + let root = current_root(&state, window.label())?; + search_entries(&root, &query) +} + +fn search_entries(root: &Path, query: &str) -> WsResult> { let needle = query.trim().to_lowercase(); if needle.is_empty() { return Ok(Vec::new()); } - let root = current_root(&state, window.label())?; let mut hits = Vec::new(); - let walker = ignore::WalkBuilder::new(&root) - .hidden(false) - .git_ignore(true) - .require_git(false) - .git_global(true) + let walker = ignore::WalkBuilder::new(root) + .standard_filters(false) .filter_entry(|entry| { entry.depth() == 0 || !is_internal_name(&entry.file_name().to_string_lossy()) }) @@ -887,6 +887,33 @@ mod tests { use super::*; use std::path::PathBuf; + #[test] + fn ignore_files_do_not_hide_workspace_entries_or_search_results() { + let fixture = std::env::temp_dir().join(format!("rs-ignore-rules-{}", std::process::id())); + let root = fixture.join("workspace"); + fs::create_dir_all(root.join(".git/info")).unwrap(); + fs::write(fixture.join(".ignore"), "parent-excluded/\n").unwrap(); + fs::write(root.join(".gitignore"), "papers/\n").unwrap(); + fs::write(root.join(".ignore"), "local-excluded/\n").unwrap(); + fs::write(root.join(".git/info/exclude"), "git-excluded/\n").unwrap(); + for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] { + fs::create_dir_all(root.join(folder)).unwrap(); + fs::write(root.join(folder).join("note.md"), "unique search phrase").unwrap(); + } + fs::write(root.join("papers/.gitignore"), "note.md\n").unwrap(); + let root = dunce::canonicalize(root).unwrap(); + let entries = list_entries(&root, "").unwrap(); + let hits = search_entries(&root, "unique search phrase").unwrap(); + for folder in ["papers", "local-excluded", "git-excluded", "parent-excluded", ".hidden-notes"] { + assert!(entries.iter().any(|entry| entry.rel_path == folder && entry.kind == "folder"), "{folder}"); + let note = format!("{folder}/note.md"); + assert!(list_entries(&root, folder).unwrap().iter().any(|entry| entry.rel_path == note), "{note}"); + assert!(hits.iter().any(|hit| hit.rel_path == note && hit.line == 1), "{note}"); + } + assert!(!entries.iter().any(|entry| entry.name == ".git")); + fs::remove_dir_all(fixture).unwrap(); + } + #[test] fn windows_keep_independent_roots_and_cleanup() { let state = WorkspaceState::new(); diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index c372aa2..9cd8311 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RuneStone", - "version": "0.1.3", + "version": "0.1.4", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte index fca0808..fe56e91 100644 --- a/src/lib/editor/LiveWriter.svelte +++ b/src/lib/editor/LiveWriter.svelte @@ -1,4 +1,5 @@ + + { if (event.target === dialog) { event.preventDefault(); onClose(); } }}> +
+

{help ? "Help and about" : "Settings"}

+ +
+
+ {#if !help} + + {/if} +
+ {#if !selected} +

No settings found

+

Try “save”, “plug-ins”, or “help”.

+ + {:else if selected.id === "general"} +

General

+

Choose how RuneStone saves your work.

+

Files

+
+
+

Save changed notes and scripts, including background tabs.

+ { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} /> +
+
+

Time between saves, even while you type. Choose 1–300 seconds.

+
seconds
+
+
+

{settings.autosaveEnabled ? "Only changed files are saved." : "Auto-save is off. Use Ctrl+S to save your changes."} Disk conflicts keep your edits for review.

+ + {#if error}{/if} +

{message}

+ {:else if selected.id === "plugins"} + + {:else} +

RuneStone

Version {version}

+
+
Get started

Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.

Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.

Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.

+
Save your work

Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.

If another app changes a file, RuneStone keeps your edits and offers both versions for review.

+
Keyboard shortcuts
Open a workspace
Ctrl+O
Find a file
Ctrl+P
Save the active file
Ctrl+S
Search the workspace
Ctrl+Shift+F
Open settings
Ctrl+,
Help and about
F1
+
+

RuneStone is under development. Maintained by kwyvern-gh.

+ {/if} +
+
+
+ + diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index 093aa92..d33b871 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -1,7 +1,10 @@ + +

Plug-ins

+

Install a package file or select a folder containing plugins.

+
+ + + reveal()} /> + +
+{#if $installedPlugins.root}

{$installedPlugins.root}

{/if} +{#if !desktop}

Installation requires the RuneStone desktop app.

{/if} +{#if $pluginServiceError}{/if} +

Installed plugins

+

Plugins run with RuneStone's access. Only enable code you trust.

+{#if !external.length}

No plugins installed.

{/if} +{#each external as plugin (plugin.manifest.id)} +
+
+

{plugin.manifest.description}

{plugin.manifest.author} · {plugin.manifest.version} · Full app access
+ { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} /> +
+

{plugin.path}

+ {#if plugin.error || $externalErrors[plugin.manifest.id]}{/if} +
+ {plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"} + + {#if plugin.removal} + + {:else} + + {/if} +
+
+{/each} +{#if $restartPlugins.length}

Restart RuneStone to clear all code from plugins that stopped in this window.

{/if} +{#if error}{/if} +

{message}

+ +{#if candidates.length || plan} + { event.preventDefault(); event.stopPropagation(); void cancel(); }}> + {#if plan} +

{`Uninstall ${plan.plugin.manifest.name}?`}

+

{plan.plugin.manifest.author} · {plan.plugin.manifest.version}

+

{plan.plugin.path}

+

This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.

+ {#if error}{/if} +
+ + + +
+ {:else} +

Review plugin installation

+

Plugins run with RuneStone's access. Only enable code you trust.

+ {#each candidates as candidate (candidate.token)} +
+ + {#if candidate.manifest}

{candidate.manifest.author} · {candidate.manifest.version}

{candidate.manifest.description}

Destination: {$installedPlugins.root}\{candidate.manifest.id}

{/if} +

Source: {candidate.source}

+ {#if candidate.error}

{candidate.error}

{/if} +
+ {/each} + {#if error}{/if} +
+ {/if} +
+{/if} + + diff --git a/src/lib/plugins/PluginTools.svelte b/src/lib/plugins/PluginTools.svelte new file mode 100644 index 0000000..6853af7 --- /dev/null +++ b/src/lib/plugins/PluginTools.svelte @@ -0,0 +1,64 @@ + + +{#if $pluginTools.length} +
+ menu = !menu} /> + {#if menu} +
+ {#each $pluginTools as tool (`${tool.owner}:${tool.kind}:${tool.id}`)} + + {/each} +
+ {/if} +
+{/if} +{#if error && !$pluginView}{/if} +{#if $pluginView} + { event.preventDefault(); pluginView.set(null); }}> +

{$pluginView.title}

pluginView.set(null)} />
+ {#if error}{/if} +
+
+{/if} + diff --git a/src/lib/plugins/TerminalSlot.svelte b/src/lib/plugins/TerminalSlot.svelte new file mode 100644 index 0000000..5727a03 --- /dev/null +++ b/src/lib/plugins/TerminalSlot.svelte @@ -0,0 +1,18 @@ + +{#if error}

{error}

{/if} +
+ diff --git a/src/lib/plugins/contracts.ts b/src/lib/plugins/contracts.ts new file mode 100644 index 0000000..e83cd2d --- /dev/null +++ b/src/lib/plugins/contracts.ts @@ -0,0 +1,31 @@ +import type { Token } from "markdown-it"; +import type { Dispose } from "./sdk.ts"; + +export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories"; +export interface TerminalProps { + cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; + onClose: () => void; onMaximize?: () => void; activeFile?: boolean; + onRunFile?: () => Promise; getSelection?: () => string; onConfigureTasks?: () => Promise; +} +export interface TerminalMount { + update(props: TerminalProps): void; + command(action: Exclude): void | Promise; + dispose: Dispose; +} +export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!"; +export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode }; +export interface Contributions { + terminal: { + mount(container: HTMLElement, props: TerminalProps): TerminalMount; + shortcut(event: Pick): TerminalAction | null; + }; + tableFormulas: { + formulaErrors: Record; + isTableFormula(text: string): boolean; + cellAddress(row: number, column: number): string; + evaluateTableFormulas(rows: string[][]): (FormulaResult | null)[][]; + tableFormulaHtml(result: FormulaResult): string; + renderTableFormulas(tokens: Token[]): void; + createFormulaTools(finish: () => void, measure: () => void): { formulaTools: HTMLDivElement; formulaStatus: HTMLSpanElement; formulaHint: HTMLDivElement }; + }; +} diff --git a/src/lib/plugins/external.ts b/src/lib/plugins/external.ts new file mode 100644 index 0000000..459eaa3 --- /dev/null +++ b/src/lib/plugins/external.ts @@ -0,0 +1,127 @@ +import { writable } from "svelte/store"; +import { invoke, isTauri } from "@tauri-apps/api/core"; +import { listen } from "@tauri-apps/api/event"; +import { workspaceList, workspaceRead, workspaceWrite } from "../workspace/api"; +import { ExternalSession, deadline } from "./externalSession"; +import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose } from "./sdk"; + +export const installedPlugins = writable({ root: "", plugins: [] }); +export const externalErrors = writable>({}); +export const pluginTools = writable<{ owner: string; id: string; title: string; kind: "command" | "view" }[]>([]); +export const pluginView = writable<{ owner: string; id: string; title: string } | null>(null); +export const pluginServiceError = writable(""); +export const restartPlugins = writable([]); +const sessions = new Map(); +const failures = new Map(); +const errors: Record = {}; +const restarted = new Set(); +let queue: Promise = Promise.resolve(); +let started = false; +let generation = 0; + +function publish() { + pluginTools.set([...sessions].flatMap(([owner, { session }]) => [ + ...[...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 }); +} +function report(id: string, reason: unknown) { errors[id] = String(reason); publish(); } +async function release(id: string, error?: string) { + await invoke("plugins_release", { id, error: error ?? null }); +} +async function stop(id: string) { + const loaded = sessions.get(id); + if (!loaded) return; + sessions.delete(id); + pluginView.update(view => view?.owner === id ? null : view); + restarted.add(id); restartPlugins.set([...restarted]); + let error: string | undefined; + try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); } + await release(id, error); publish(); +} +function show(owner: string, id: string) { + const view = sessions.get(owner)?.session.views.get(id); + if (view) pluginView.set({ owner, id, title: view.title }); +} +async function activate(row: InstalledPlugin) { + const id = row.manifest.id; + let leased = false; + const session = new ExternalSession(id, { + workspace: { list: path => workspaceList(path ?? ""), read: workspaceRead, write: workspaceWrite }, + settings: { + read: async () => JSON.parse(await invoke("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 }); }, + }, + assets: { read: async path => Uint8Array.from(atob(await invoke("plugins_asset", { id, path })), char => char.charCodeAt(0)) }, + }, publish, view => show(id, view)); + try { + const code = await invoke("plugins_load", { id, hash: row.hash }); leased = true; + const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" })); + let module: PluginModule; + try { module = await deadline(import(/* @vite-ignore */ url)); } + catch (reason) { await release(id, String(reason)); leased = false; throw reason; } + finally { URL.revokeObjectURL(url); } + sessions.set(id, { hash: row.hash, session }); + await session.start(module); + delete errors[id]; publish(); + } catch (reason) { + failures.set(id, row.hash); report(id, reason); + let cleanupError: string | undefined; + try { await session.stop(); } catch (error) { cleanupError = String(error); } + sessions.delete(id); + if (leased) await release(id, cleanupError); + publish(); + } +} +export function refreshPlugins(): Promise { + if (!isTauri()) return Promise.resolve(); + const version = generation; + const job = async () => { + try { + const snapshot = await invoke("plugins_snapshot"); + if (!snapshot || version !== generation) return; + installedPlugins.set(snapshot); pluginServiceError.set(""); + for (const id of sessions.keys()) { + const row = snapshot.plugins.find(row => row.manifest.id === id); + if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id); + } + for (const row of snapshot.plugins) { + const id = row.manifest.id; + if (!row.enabled) { failures.delete(id); continue; } + if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row); + } + } catch (reason) { pluginServiceError.set(String(reason)); } + }; + queue = queue.then(job, job); + return queue; +} +export async function setPluginEnabled(id: string, enabled: boolean, hash?: string) { + await invoke("plugins_set_enabled", { id, enabled, hash: hash ?? null }); + await refreshPlugins(); +} +export async function runPluginCommand(owner: string, id: string) { + 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 async function mountPluginView(owner: string, id: string, element: HTMLElement): Promise { + const session = sessions.get(owner)?.session; + if (!session) throw new Error("The plugin is disabled."); + return session.mount(id, element); +} +export function startExternalPlugins(): () => void { + if (!isTauri() || started) return () => {}; + started = true; + let disposed = false; + 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 refreshPlugins(); + const focus = () => { void refreshPlugins(); }; + window.addEventListener("focus", focus); + // Also detects changes made in a file manager while this window stays open. + const timer = setInterval(focus, 5000); + return () => { + disposed = true; started = false; generation++; off?.(); clearInterval(timer); window.removeEventListener("focus", focus); + for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason)); + }; +} diff --git a/src/lib/plugins/externalSession.ts b/src/lib/plugins/externalSession.ts new file mode 100644 index 0000000..f066f0a --- /dev/null +++ b/src/lib/plugins/externalSession.ts @@ -0,0 +1,99 @@ +import { pluginHost, type ContributionRegistry } from "./registry.ts"; +import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView } from "./sdk.ts"; + +export function deadline(work: Promise, milliseconds = 5000): Promise { + let timer: ReturnType; + return Promise.race([work, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Plugin cleanup or activation timed out. Restart RuneStone.")), milliseconds); })]).finally(() => clearTimeout(timer)); +} + +/** Revokes host access before cleanup, including when activation is still pending. */ +export class ExternalSession { + readonly controller = new AbortController(); + readonly commands = new Map(); + readonly views = new Map(); + private cleanups: Dispose[] = []; + private stopped = false; + private activation: Promise = Promise.resolve(); + private stopping?: Promise; + private lateCleanup?: Promise; + private mounted = new Set(); + private contributions: Dispose[] = []; + private registry: ContributionRegistry; + readonly id: string; + private services: Pick; + private changed: () => void; + private show: (id: string) => void; + constructor(id: string, services: Pick, changed: () => void, show: (id: string) => void, registry: ContributionRegistry = pluginHost) { + 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."); } + async start(module: PluginModule) { + const register = (map: Map, item: T) => { + this.check(); + if (!/^[a-z][a-z0-9.-]*$/.test(item.id) || !item.title?.trim() || map.has(item.id)) throw new Error("Invalid or duplicate plugin contribution."); + map.set(item.id, item); this.changed(); + }; + const api: PluginApi = { + id: this.id, signal: this.controller.signal, + 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); }, + registerView: item => { if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); }, + openView: id => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id); }, + onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); }, + workspace: { + list: path => { this.check(); return this.services.workspace.list(path); }, + read: path => { this.check(); return this.services.workspace.read(path); }, + 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: { + read: () => { this.check(); return this.services.settings.read(); }, + write: value => { this.check(); return this.services.settings.write(value); }, + }, + assets: { read: path => { this.check(); return this.services.assets.read(path); } }, + }; + this.activation = Promise.resolve().then(() => { + if (typeof module.activate !== "function") throw new Error("The plugin must export activate(api)."); + this.check(); return module.activate(api); + }).then(async cleanup => { + if (typeof cleanup === "function") { + if (this.stopped) { this.lateCleanup = Promise.resolve().then(cleanup); await this.lateCleanup; } else this.cleanups.push(cleanup); + } + }); + 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 mount(id: string, element: HTMLElement): Promise { + this.check(); const view = this.views.get(id); if (!view) throw new Error("Unknown plugin view."); + let cleaning: Promise | undefined; + const pending = Promise.resolve().then(() => { this.check(); return view.mount(element); }); + const cleanup = () => { + cleaning ??= (async () => { + const dispose = await pending; + if (typeof dispose === "function") await dispose(); + element.replaceChildren(); this.mounted.delete(cleanup); + })(); + return cleaning; + }; + this.mounted.add(cleanup); + try { await deadline(pending); } catch (error) { await deadline(cleanup()).catch(() => {}); throw error; } + if (this.stopped) await cleanup(); + return cleanup; + } + stop(): Promise { + if (this.stopping) return this.stopping; + this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.changed(); + for (const remove of this.contributions.splice(0)) remove(); + this.stopping = (async () => { + const errors: unknown[] = []; + // Activation rejection is reported by start. A timeout still blocks removal. + try { await deadline(this.activation.catch(() => {})); } catch (error) { errors.push(error); } + if (this.lateCleanup) { try { await deadline(this.lateCleanup); } catch (error) { errors.push(error); } } + for (const cleanup of [...this.mounted, ...this.cleanups.reverse()]) { + try { await deadline(Promise.resolve().then(cleanup)); } catch (error) { errors.push(error); } + } + this.cleanups = []; + if (errors.length) throw new Error(errors.map(String).join("\n")); + })(); + return this.stopping; + } +} diff --git a/src/lib/plugins/registry.ts b/src/lib/plugins/registry.ts new file mode 100644 index 0000000..db14619 --- /dev/null +++ b/src/lib/plugins/registry.ts @@ -0,0 +1,27 @@ +import type { Contributions } from "./contracts.ts"; + +/** Contributions belong to installed package sessions. This registry never loads code. */ +export class ContributionRegistry { + private entries = new Map(); + private listeners = new Set<(revision: number) => void>(); + private revision = 0; + get(key: K): Contributions[K] | undefined { + return this.entries.get(key)?.value as Contributions[K] | undefined; + } + register(owner: string, key: K, value: Contributions[K]): () => void { + if (key !== "terminal" && key !== "tableFormulas") throw new Error("Unknown plugin contribution."); + if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`); + const entry = { owner, value }; + this.entries.set(key, entry); this.emit(); + return () => { + if (this.entries.get(key) !== entry) return; + this.entries.delete(key); this.emit(); + }; + } + subscribe = (listener: (revision: number) => void) => { + this.listeners.add(listener); listener(this.revision); + return () => { this.listeners.delete(listener); }; + }; + private emit() { this.revision++; for (const listener of this.listeners) listener(this.revision); } +} +export const pluginHost = new ContributionRegistry(); diff --git a/src/lib/plugins/sdk.ts b/src/lib/plugins/sdk.ts new file mode 100644 index 0000000..6d53814 --- /dev/null +++ b/src/lib/plugins/sdk.ts @@ -0,0 +1,30 @@ +import type { Contributions } from "./contracts.ts"; +/** Package API v1. Compiled plugins export activate(api). */ +export type Dispose = () => void | Promise; +export interface PluginCommand { id: string; title: string; run: () => void | Promise } +export interface PluginView { id: string; title: string; mount: (container: HTMLElement) => void | Dispose | Promise } +export interface PluginApi { + readonly id: string; + readonly signal: AbortSignal; + contribute(key: K, value: Contributions[K]): void; + registerCommand(command: PluginCommand): void; + registerView(view: PluginView): void; + openView(id: string): void; + onDispose(cleanup: Dispose): void; + workspace: { + list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>; + read(path: string): Promise; + write(path: string, contents: string, expected: string): Promise; + }; + settings: { read(): Promise; write(value: unknown): Promise }; + assets: { read(path: string): Promise }; +} +export interface PluginModule { activate(api: PluginApi): void | Dispose | Promise } +export interface ExternalManifest { + schemaVersion: 1; id: string; name: string; author: string; description: string; + version: string; apiVersion: 1; entry: string; access: "full-app"; +} +export interface InstalledPlugin { manifest: ExternalManifest; hash: string; enabled: boolean; path: string; error: string | null; removal: boolean } +export interface PluginSnapshot { root: string; plugins: InstalledPlugin[] } +export interface Candidate { token: string; source: string; manifest: ExternalManifest | null; error: string | null } +export interface RemovalPlan { token: string; plugin: InstalledPlugin } diff --git a/src/lib/terminal/TerminalWindow.svelte b/src/lib/terminal/TerminalWindow.svelte deleted file mode 100644 index 6d2c1e6..0000000 --- a/src/lib/terminal/TerminalWindow.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - -
- {#if error}

{error}

{/if} - void getCurrentWindow().destroy().catch(reason => error = String(reason))} /> -
- diff --git a/src/lib/ui/Icon.svelte b/src/lib/ui/Icon.svelte index c5c96f3..e91cc38 100644 --- a/src/lib/ui/Icon.svelte +++ b/src/lib/ui/Icon.svelte @@ -4,7 +4,13 @@ let { icon }: { icon: IconName } = $props();
\n'; markdown.renderer.rules.table_close = () => '
\n'; -export function tableFormulaHtml(result: FormulaResult): string { - const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`; - return `${escapeHtml(result.text)}`; -} - -// Work from raw inline content, before Markdown formatting can interpret * or $. -// Each table gets its own reference scope, including in nested lists/callouts. markdown.core.ruler.after("inline", "table_formulas", state => { - let rows: Token[][] | undefined; - for (const token of state.tokens) { - if (token.type === "table_open") rows = []; - else if (rows && token.type === "tr_open") rows.push([]); - else if (rows && token.type === "inline") rows.at(-1)?.push(token); - else if (rows && token.type === "table_close") { - const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content))); - rows.forEach((row, r) => row.forEach((cell, c) => { - const result = results[r][c]; - if (!result) return; - const output = new MarkdownIt.Token("html_inline", "", 0); - output.content = tableFormulaHtml(result); - cell.children = [output]; - })); - rows = undefined; - } - } + pluginHost.get("tableFormulas")?.renderTableFormulas(state.tokens); }); function documentParts(contents: string) { diff --git a/src/lib/workspace/settings.ts b/src/lib/workspace/settings.ts new file mode 100644 index 0000000..c65abb1 --- /dev/null +++ b/src/lib/workspace/settings.ts @@ -0,0 +1,35 @@ +export const SETTINGS_KEY = "runestone.settings"; +export const MIN_AUTOSAVE_SECONDS = 1; +export const MAX_AUTOSAVE_SECONDS = 300; + +export interface AppSettings { + autosaveEnabled: boolean; + autosaveSeconds: number; +} + +export const DEFAULT_SETTINGS: Readonly = { + autosaveEnabled: true, + autosaveSeconds: 5, +}; + +export function validAutosaveSeconds(value: unknown): value is number { + return typeof value === "number" && Number.isInteger(value) + && value >= MIN_AUTOSAVE_SECONDS && value <= MAX_AUTOSAVE_SECONDS; +} + +export function parseSettings(raw: string | null): AppSettings { + try { + const value = JSON.parse(raw ?? "null"); + return { + autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled, + autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds, + }; + } catch { return { ...DEFAULT_SETTINGS }; } +} + +export function saveSettings(storage: Pick, settings: AppSettings): void { + if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") { + throw new Error("Choose a whole number from 1 to 300 seconds."); + } + storage.setItem(SETTINGS_KEY, JSON.stringify(settings)); +} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index ae66b42..87160ce 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -1,7 +1,31 @@ - -{#if terminalRoot}{:else}{/if} + +{#if terminalRoot} +
+ {#if error}

{error}

{/if} + {#if terminal} + {#key terminal} + void getCurrentWindow().destroy().catch(reason => error = String(reason))} /> + {/key} + {:else}

Install and enable the Terminal plugin in Settings → Plug-ins in the main window.

{/if} +
+{:else}{/if} + diff --git a/tsconfig.plugins.json b/tsconfig.plugins.json new file mode 100644 index 0000000..5dbac50 --- /dev/null +++ b/tsconfig.plugins.json @@ -0,0 +1,5 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { "types": ["svelte", "vite/client"] }, + "include": ["src/**/*.d.ts", "plugins/**/*.ts", "plugins/**/*.svelte"] +}