Add workspace links, restore tabs, and update project guides

This commit is contained in:
Knotty Wyvern
2026-10-21 21:05:48 -07:00
parent f741389418
commit 562ef87d24
46 changed files with 2999 additions and 1113 deletions
+29 -7
View File
@@ -3,10 +3,31 @@
## Documentation
Keep the README focused on the project, its usefulness, setup, help, and maintainers.
Keep agent instructions in this file. Put detailed usage, development notes, and
product plans in `docs/`, with links from the README.
Keep the roadmap visual and organized around goals, user outcomes, and milestones.
Keep detailed capability lists and design constraints in the product scope reference.
Keep agent instructions in this file. Put detailed usage and development notes in
`docs/`, with links from the README.
The original roadmap and product scope documents are retired. Do not recreate them.
Keep future plans and roadmaps in RuneStone Project Management.
Keep current behavior and limits in the [user guide](docs/user-guide.md).
Keep product boundaries and architecture constraints in the [development guide](docs/development.md#product-boundaries).
Keep interface rules in the [interface design reference](docs/ui-design.md).
### Write for the task and reader
- Keep each guide within the task and audience named by its title and incoming link descriptions.
An installation guide starts with a supplied release file and ends with installation or launch.
Put workspace tutorials in the user guide and source builds, API details, and test records in developer references.
- Give the general procedure before specific examples. Label every example and cite its source or defining project file.
State the working folder, prerequisites, command, and output for build examples.
Do not present one plugin's build command as the process for all plugins.
- Keep the README's first-use path short. Link to details instead of repeating them.
Include limits when they change a user's choice or action. Avoid repeated availability disclaimers and development history in setup steps.
- Treat deliberate user cuts as scope decisions. Do not restore removed tangents during later documentation edits.
Keep necessary technical detail in the appropriate reference when reorganizing existing material.
- After moving or removing content, check link descriptions, paths, and heading anchors.
A link must lead to the task it promises.
These rules reflect the October 21, 2026 README and installation edits compared with `codex/combined-pr-review` at `f741389`.
Those edits shortened setup, removed workspace steps and source-build instructions, and reduced repeated development notes.
## Kanban workflow
@@ -43,7 +64,7 @@ Do not substitute a numeric build increment for a hotfix suffix.
If a package format rejects the suffix, add support or report the blocker before building.
Do not bypass validation or overwrite an existing release ZIP.
See [versioning for plugin authors and agents](docs/plugins.md#versioning-for-plugin-authors-and-agents) for the package guidance.
See [versioning for plugin authors and agents](docs/plugin-development.md#versioning-for-plugin-authors-and-agents) for the package guidance.
## Windows installer
@@ -54,13 +75,14 @@ See [versioning for plugin authors and agents](docs/plugins.md#versioning-for-pl
## Plugin packages
Use `docs/plugins.md` as the package and release reference for all plugin work.
Use `docs/plugin-development.md` as the package and release reference for all plugin work.
Distribute one standard `.zip` per plugin, with `plugin.json` at the archive root.
Use `pnpm package:plugin <compiled-folder> [output-folder]` to create release files.
Use Settings → Plug-ins for local ZIP and experimental Gitea-link installation.
Do not introduce custom extensions, loose JSON installation, or folder installation instructions.
Keep the manifest and entry module readable. Include the assets and dependencies needed to run the plugin.
Follow the Gitea release standard in `docs/plugins.md`: one plugin ZIP per published release, with an explicit tag for prerelease trials.
Follow the [shared publishing standard](docs/plugin-development.md#publishing-releases) on any hosting service.
Use one plugin ZIP per published release, with an explicit tag for prerelease trials.
Keep the download source separate from package validation and installation.
GitHub and GitLab adapters remain future work. Do not add untested host support.
+8 -28
View File
@@ -2,36 +2,19 @@
A desktop workspace for notes, code, and project work stored in ordinary local files.
RuneStone keeps a project's explanations and scripts together. Open an existing folder,
write Markdown, edit source files, and preview images without importing your documents into a service.
Your files remain usable in other editors. Workspace metadata lives separately in `.runestone/`.
## Install and start
Choose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon),
or [Linux setup](#linux-intelamd-64-bit).
Choose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).
### Windows installer
Use the Windows installer supplied by the maintainer for Windows 10 or 11 on Intel/AMD 64-bit computers.
You do not need Node.js, Rust, or the source repository.
No public download location is configured.
Use the Windows installer supplied for Windows 10 or 11 on Intel/AMD 64-bit computers.
1. Save `RuneStone_<version>_x64-setup.exe` to Downloads.
2. Open the installer.
3. Complete setup.
4. Open RuneStone from the Start menu.
5. Use the folder button to open or create a workspace outside the application folder.
For example, the Windows `0.1.41` installer is `RuneStone_0.1.41_x64-setup.exe`.
Setup installs RuneStone for your Windows account. It downloads WebView2 if that runtime is missing.
Keep your internet connection active until setup finishes.
To update or reinstall, save your documents and close all RuneStone windows first.
Run the installer for the same or a newer version. You do not need to uninstall first.
Setup defaults to reinstall, preserves workspace files and settings, and blocks version downgrades.
Press Ctrl+N to create a file, or Ctrl+P to find an existing file.
See [Installation and updates](docs/installation.md#install-on-windows) for Windows setup help.
### macOS installer: Apple silicon
@@ -41,12 +24,11 @@ If the maintainer supplied a macOS installer:
1. Open `RuneStone_<version>_aarch64.dmg` (for example, `RuneStone_0.1.42_aarch64.dmg`).
2. Drag RuneStone into Applications.
3. Eject the disk image, then open RuneStone from Applications.
4. Use the folder button to open a workspace outside the application bundle.
Quit RuneStone before replacing an existing installation. The installer needs no developer tools.
The current build is experimental, uses local ad hoc signatures, and is not Apple notarized.
Intel Macs are not covered. Installation, updates, and desktop behavior still need acceptance testing.
See [macOS installation help](docs/installation.md#install-on-macos) if macOS blocks opening the app.
See [macOS installation and updates](docs/installation.md#install-on-macos) for the full procedure.
### Linux: Intel/AMD 64-bit
@@ -61,12 +43,11 @@ Node.js, Rust, or the source repository. The package includes RuneStone's Browse
```
3. Enter your password when asked, then open RuneStone from your applications menu.
4. Use the folder button to open a workspace outside the application folder.
The current package was built on Ubuntu 26.04.1 LTS for `amd64` and requires
GLIBC 2.39 or newer. Installation, reinstall, upgrade, removal, and compatibility
with older distributions remain untested. See [Linux installation and updates](docs/installation.md#install-on-linux)
for package checks and help, or the [Linux development guide](docs/linux.md) to build from source.
for package checks and update steps, or the [Linux development guide](docs/linux.md) to build from source.
## What you can do
@@ -80,7 +61,7 @@ for package checks and help, or the [Linux development guide](docs/linux.md) to
RuneStone is under development. Windows and Apple silicon macOS have local test installers,
but no public download location is configured. Linux has an experimental Debian installer with limited package checks.
Linux installation and macOS desktop acceptance remain unvalidated.
Language servers, crash recovery, and restoring open tabs after restart remain planned.
Tab restoration and crash recovery remain planned. Language-server support belongs to a future optional plugin.
Plugin features require their matching packages. See the [user guide](docs/user-guide.md) for current behavior and limits.
## Find help
@@ -89,9 +70,8 @@ Plugin features require their matching packages. See the [user guide](docs/user-
| --- | --- |
| Edit documents, manage tabs, or resolve a save conflict | [User guide](docs/user-guide.md) |
| Change colors or install a theme | [Appearance guide](docs/guides/themes.md) |
| Install or remove an optional plugin | [Plugin installation](<docs/plugins.md#install-a-plugin>) |
| Fix setup or launch problems | [Installation help](docs/installation.md#setup-help) |
| Understand future work | [Roadmap](docs/roadmap.md) |
| Install or remove an optional plugin | [Install and manage plugins](docs/plugins.md) |
| Install or update RuneStone | [Installation and updates](docs/installation.md) |
Press F1 in the app for Help and about. Include the app version, operating system,
steps, expected result, and error text when you report a problem to the maintainer.
@@ -100,7 +80,7 @@ steps, expected result, and error text when you report a problem to the maintain
Use the [development guide](docs/development.md) for source setup and checks.
Read the [interface design reference](docs/ui-design.md) before UI changes.
The [product scope](docs/product-scope.md) contains the detailed capabilities and design constraints.
See [product boundaries](docs/development.md#product-boundaries) for exclusions and architecture constraints.
## Maintainer
+3 -1
View File
@@ -1,11 +1,13 @@
# Documentation archive
[User guide](../user-guide.md) · [Development](../development.md) · [Release history](../releases.md)
[User guide](../user-guide.md) · [Development](../development.md)
These records preserve past checks, decisions, and proposals. They do not define current behavior or authorize planned work.
| Record | Purpose |
| --- | --- |
| [Linux validation, October 14–15](linux-validation-2026-10.md) | Native builds, desktop smoke checks, Debian/AppImage packages, and test limits for 0.1.34 |
| [Plugin release trial, October 5](plugin-release-trial-2026-10-05.md) | Simulated Gitea downloads, native installation, and repeat steps |
| [Kanban review, October 8](kanban-review-2026-10-08.md) | Scope, assignments, checks, and the 0.1.13 test builds |
| [Kanban changes, October 8](kanban-changes-2026-10-08.md) | Editor, settings, browser, and plugin changes |
| [Kanban follow-up, October 8](kanban-followup-2026-10-08.md) | Menu, theme, and Git graph checks |
+128
View File
@@ -0,0 +1,128 @@
# Linux validation records: October 2026
[Documentation archive](README.md) · [Linux development](../linux.md) · [Linux installation](../installation.md#install-on-linux)
These records preserve the October 14–15 checks for version 0.1.34.
Results and outstanding work describe those test runs, not the current release.
## Validation record: 2026-10-14
Validated on `desk`: Ubuntu 26.04.1 LTS, x86_64, four CPUs, 7.2 GiB reported RAM,
XFCE/X11, Linux 7.0.0-38-generic. The execution environment reports a container
boundary and underlying KVM virtualization. This does not validate Ubuntu 24.04,
Wayland, ARM, or another distribution.
Source: base commit `edef2520afc92f7896454bf94a8ea15bbf4e1684` plus the Linux
readiness patch and the Browser window portability fix. The original transferred
source archive had SHA-256
`b16643bfc7a634e5a5d17a7c246e87d95a458c06fb8afb45899a28a460e03047`.
The first native compile found a Windows-only `drag_and_drop(false)` call in
`src-tauri/src/browser.rs`; it now uses the cross-platform
`disable_drag_drop_handler()` API already used by the settings window.
Toolchain: Node.js 24.22.0, pnpm 10.34.7, Rust/Cargo 1.93.1, GLib 2.88.0,
GTK 3.24.52, and WebKitGTK 4.1 version 2.52.6. Native builds used one job and
`CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0` to conserve RAM and disk.
| Check | Recorded result |
| --- | --- |
| `pnpm install --frozen-lockfile` and `npm ci --prefix browser-runtime` | Passed |
| `pnpm check` | Passed; zero errors and warnings |
| `pnpm build` | Passed; bundle-size warnings remain |
| `pnpm browser:check` and `pnpm browser:test` | Passed; 44 Browser unit tests |
| Browser Linux packaging and `pnpm browser:stage` | Passed; x86_64 runtime staged |
| `npm --prefix browser-runtime run test:packaged` | Passed; all 12 engine smoke checks, sandbox enabled |
| `pnpm test` | 238 passed, one skipped, two test files failed because the Table Formulas package was absent |
| `cargo test --manifest-path src-tauri/Cargo.toml --lib --locked --offline -j 1` | Passed after the portability fix; 92 passed, three ignored |
| `pnpm tauri build --debug --no-bundle -- --locked --offline -j 1` | Passed; native debug executable, version 0.1.34 |
| Tauri X11 launch | Visible 1400 by 900 window; rendered frontend verified with an internal capture |
| Host Browser integration | Open Browser opened a Browser tab with address and profile controls; no webpage-navigation claim |
GUI checks used isolated task-local XDG settings/data directories, and the test
processes were closed afterward. Virtual-GPU EGL/VAAPI warnings occurred; they did
not prevent these smoke checks. No sandbox, security, swap, or permission workaround
was used. Existing user settings and workspaces were not used.
No installer or release package was produced, versions were unchanged, and nothing
was published. Remaining work includes supplying/building `RuneStone_Table_Formulas`
and rerunning the full source suite, completing the [Linux desktop checks](../linux.md#desktop-checks), and
validating Debian/AppImage installation and lifecycle behavior on the intended
target distribution. These results do not establish full Linux support.
### Initial bounded release attempt
The normal release profile (`opt-level = 3`, full LTO, one codegen unit) was
attempted with one Cargo job, locked/offline dependencies, and the already-tested
frontend output. Before starting, desk had about 2.0 GiB available RAM, effectively
full 4.0 GiB swap, and 4.1 GiB free disk. A temporary user service bounded the
entire build to 1,677,721,600 bytes of RAM and no additional swap.
The release build reached the GTK Rust crate but exceeded that hard cap. The
service recorded `Result=oom-kill`, `MemoryPeak=1677721600`, and zero swap use after
14 minutes 47 seconds. Soft memory throttling was tried first; it caused repeated
reclaim, so the soft threshold was removed while retaining the hard cap. No larger
memory allowance was attempted. The temporary service was cleaned up; dependency
and build caches were preserved. About 3.3 GiB disk remained afterward.
No optimized executable, Debian package, or AppImage was produced. AppImage
bundling was not attempted because it needs the release executable. Package
contents, generated dependency metadata, and installation lifecycle therefore
remain unvalidated. `ldd` found no missing libraries for the previously tested
debug host and staged Browser on desk. In addition to host libraries, the Browser
needs NSPR/NSS, CUPS, and ALSA libraries; their Ubuntu 26.04 providers include
`libnspr4`, `libnss3`, `libcups2t64`, and `libasound2t64`. Check the eventual package
declares the appropriate runtime dependencies; the current machine having them
installed does not prove that package metadata is complete.
The smallest next step is to free more RAM on desk, or use a host with more
available memory, then retry the cached release build with a larger bounded
allowance. Starting with at least 3 GiB available RAM provides more headroom but
does not establish the required peak; measure it during the retry. Recheck disk
before bundling. Existing debug-build and smoke-test results above still stand.
### Release package validation: 2026-10-15
After desk returned with more headroom, a fresh resource check found 4,956,172 KiB
available RAM (about 4.73 GiB), nearly all 4 GiB swap free, and 47 GiB free disk.
No finite inherited user-cgroup memory limit was found. The cached release build
was retried with one job, a temporary 3.5 GiB memory cap, and no build-group swap.
It completed successfully in 12 minutes 32 seconds, with 3.5 GiB peak group memory
and no OOM event. The earlier failure establishes only that the chosen 1,600 MiB
cap was insufficient; it does not establish that the 8 GB VM cannot build.
The initial Debian bundle declared only GTK and WebKitGTK. Added
`src-tauri/tauri.linux.conf.json` to declare OpenSSL plus the Browser's NSS/NSPR and
ALSA dependencies. The release executable requires GLIBC 2.39, so the Debian
metadata also declares `libc6 (>= 2.39)`. Tauri retains its default GTK/WebKitGTK
dependencies. Recheck symbol requirements when changing the compiler or build host;
this floor is evidence from this build, not a permanent portability guarantee.
The Debian package was regenerated and its final dependency metadata verified.
| Release check | Recorded result |
| --- | --- |
| Normal optimized release profile and Debian bundling | Passed, using locked/offline Cargo dependencies and the previously validated frontend |
| Debian package | `RuneStone_0.1.34_amd64.deb`, package name `rune-stone`, version `0.1.34`, architecture `amd64` |
| Debian package checksums, desktop entry, resources and permissions | Passed; host and Browser executables are executable, Browser resource directory is traversable, packaged checksums match |
| Debian shared libraries on desk | All host and Browser libraries resolve |
| Extracted Debian GUI smoke | Host rendered a visible window, launched its own packaged Browser executable, and rendered an HTTPS page |
| AppImage bundling | Passed from the same optimized release executable; 2 minutes 18 seconds, about 1.6 GiB peak memory, no build-group swap |
| Extracted AppImage GUI smoke | AppRun launched, bundled WebKitGTK child processes were used, its packaged Browser launched, and an HTTPS page rendered |
Both package tests used isolated task-local settings/data and closed their test
processes afterward. AppImage's supported extraction route was used because the
VM does not expose `/dev/fuse`; FUSE-mounted execution was not tested. Virtual-GPU
acceleration warnings did not prevent rendering. Versions remain 0.1.34 under the
explicit validation-build instruction. These are unsigned experimental artifacts,
not published releases. Completed package files, metadata, test limits, and
checksums are archived under `releases/0.1.34/` outside Git.
No app was installed system-wide and no existing user workspace/settings were
used. Installation, same-version reinstall, upgrade, removal, the full desktop
acceptance matrix, Ubuntu 24.04, Wayland, and other architectures remain untested.
The Table Formulas external dependency remains absent. Native library resolution
on desk and successful extraction smoke checks do not prove clean-machine package
installation or compatibility with other distributions.
The AppImage's bundled WebKitGTK and JavaScriptCoreGTK libraries require GLIBC
2.43. The Debian executable's GLIBC 2.39 floor therefore does not describe the
AppImage's minimum runtime. Treat this AppImage as an Ubuntu 26.04 validation
artifact rather than a portable Ubuntu 24.04 build.
@@ -0,0 +1,26 @@
# Plugin release trial: October 5, 2026
[Documentation archive](README.md) · [Plugin host checks](../plugin-host.md#modules-and-checks)
This record describes a historical trial. It does not establish current release availability or live installation support.
The four local packages passed a simulated Gitea release download and isolated native installation on October 5, 2026.
The test checked the installed hashes and kept all four plugins disabled.
| Plugin | Package version |
| --- | --- |
| Terminal | 0.1.0 |
| Table Formulas | 0.1.0 |
| PDF Viewer | 0.0.1 |
| Project management | 0.2.3 |
The authenticated check of the personal Gitea server found no releases in these four repositories.
That check did not test a live release installation or create releases or tags.
It does not establish current release availability.
## Repeat the trial
Complete the [host setup](../development.md#run-from-source) first. Run the following command from the RuneStone repository root.
To repeat the four-package trial, place exactly these four ZIPs in a folder and set `RUNESTONE_GIT_TRIAL_PACKAGES` to its absolute path.
Then run `cargo test --manifest-path src-tauri/Cargo.toml --lib four_plugin_release_trial -- --ignored --nocapture`.
For current native and browser checks, see the [plugin host reference](../plugin-host.md#modules-and-checks).
+41 -3
View File
@@ -104,10 +104,48 @@ Use [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) befor
These checks require a Windows test account or virtual machine. A successful build alone does not confirm them.
## Experimental platform packages
## Build Linux packages
Linux and macOS packages remain unvalidated. Build on the target platform with the correct Browser runtime.
Use the [Linux readiness guide](linux.md) for system packages, desktop checks, and Debian/AppImage commands.
Prepare the Browser runtime and complete the [Linux development checks](linux.md) on the target processor architecture.
Run the commands from the RuneStone repository root.
The examples use the Tauri CLI from [package.json](../package.json) and [Linux bundle configuration](../src-tauri/tauri.linux.conf.json).
Choose the package format for the build. Each example produces a package in the output folder listed below:
```sh
# Example: Debian package
pnpm tauri build --bundles deb -- --locked
# Example: AppImage
pnpm tauri build --bundles appimage -- --locked
```
Do not use `pnpm build:installer` on Linux. That command selects the Windows installer.
These direct Tauri commands do not manage the project release version or archive a
release. Before making a distributable, select the next version using the
[version policy](../AGENTS.md#versioning), keep all four version fields consistent,
and restore them if packaging fails. Move completed packages into
`releases/<version>/` together with checksums and the recorded source/test results;
do not leave duplicate completed packages in the toolchain bundle directory.
Packages appear under `src-tauri/target/release/bundle/deb/` or `src-tauri/target/release/bundle/appimage/`.
Use the [Linux installation procedure](installation.md#install-on-linux) when testing a Debian package.
Test launch without development tools, same-version reinstall, upgrade, and removal on a separate test account.
Reinstall and upgrade must preserve settings and workspace files. Removal must preserve workspaces outside the installation folder.
For shared packages, build on the oldest distribution you intend to support that supplies WebKitGTK 4.1.
A package built on a newer system can require libraries unavailable on an older system.
An AppImage does not remove this compatibility limit.
See [Tauri's AppImage guidance](https://v2.tauri.app/distribute/appimage/) and [Debian packaging guidance](https://v2.tauri.app/distribute/debian/).
Call a distribution supported only after its native tests and package checks pass.
Repeat the automated checks on a Linux runner before each Linux release.
Keep the source commit, environment, results, and untested cases with each release.
See the [October 2026 validation records](archive/linux-validation-2026-10.md) for earlier package checks and their limits.
## Experimental macOS packages
Build on macOS with the correct Browser runtime.
On macOS, a local application bundle can use:
+35 -7
View File
@@ -1,6 +1,6 @@
# Development guide
[RuneStone](../README.md) · [Interface design](ui-design.md) · [Build and package](builds.md) · [Plugin development](plugins.md)
[RuneStone](../README.md) · [Interface design](ui-design.md) · [Build and package](builds.md) · [Plugin development](plugin-development.md)
For task-based app help, use the [user guide](user-guide.md).
Dated implementation records and proposals live in the [archive](archive/README.md).
@@ -67,12 +67,37 @@ The interface uses Svelte 5, TypeScript, and Vite.
CodeMirror handles live Markdown editing, Monaco handles source editing, and xterm handles terminals.
Windows is the first target. The older WriterHost component remains unused.
Use the [Linux readiness guide](linux.md) for Linux setup, native tests, and package checks.
Use the [Linux development guide](linux.md) for source prerequisites, Browser preparation, and native desktop checks.
Use the [Linux package build guide](builds.md#build-linux-packages) for Debian and AppImage builds.
See the setup steps below to install dependencies and run the desktop app.
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
See the [user guide](user-guide.md) for current behavior and limits.
See the [interface design reference](ui-design.md) for shared controls, dimensions, and visual checks. Agent instructions 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.
Use the [plugin development reference](plugin-development.md) for build examples, package requirements, releases, and the API.
Use the [plugin host reference](plugin-host.md) for installation internals, recovery, and host checks.
## Product boundaries
RuneStone keeps workspace documents as ordinary local files.
Basic Markdown table editing and rendering belong in the core.
Users must retain access to workspace files when plugins are disabled.
Store workspace display order, pins, and bookmarks in `.runestone/`.
Store installed plugins and retained plugin settings in application data. See [plugin storage](plugin-host.md#storage-and-recovery).
Prefer a local Git clone. Do not use a live network share as the sync path.
Native file access, file watching, search, Git, and terminal services belong in Rust.
The [plugin development reference](plugin-development.md) defines the supported package format and host API.
The [built-in browser runtime](#built-in-browser-runtime) has its own architecture and setup requirements.
The following remain outside the product scope:
- A plugin marketplace
- Obsidian or VS Code plugin compatibility
- Cloud sync, live collaboration, or mobile
- A debugger or a full IDE
- Auto-commit on save
Track future work and roadmaps in RuneStone Project Management.
## Run from source
@@ -138,9 +163,10 @@ detected shell profile and check shell prompt integration.
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.
Clone [RuneStone_Table_Formulas](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas) beside RuneStone and install its dependencies first.
Set `RUNESTONE_TABLE_FORMULAS_ROOT` if that checkout is elsewhere.
Before tests that use plugin packages, build each required plugin with its own command.
Use the [Table Formulas example](plugin-development.md#example-table-formulas) and the [Terminal example](plugin-development.md#example-terminal).
`pnpm build:plugins` builds only Table Formulas.
See the [plugin host checks](plugin-host.md#modules-and-checks) for compiled package paths and overrides.
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.
@@ -202,3 +228,5 @@ Runtime compilation and staging do not produce a new RuneStone installer version
The installer includes the staged runtime from `src-tauri/browser-engine`. Follow the project version policy when creating that installer.
Use `scripts/browserInteraction.smoke.mjs` to check the host interface against a real runtime.
Keep its results separate from the native Tauri window checks.
Browser startup obtains a session token for its window. Native requests check that token, and cleanup revokes it.
+4 -61
View File
@@ -8,8 +8,6 @@
| Linux, Intel/AMD 64-bit | Supplied experimental Debian installer. Installation lifecycle remains untested. |
| macOS, Apple silicon | Supplied experimental DMG installer. Installation and desktop acceptance remain untested. |
No public download location is configured. Get a Windows, Linux, or macOS installer from the maintainer who supplied your test release.
Linux and macOS do not yet have a fully validated installation or supported operating-system version range.
The current macOS DMG targets Apple silicon only; Intel Macs are not covered.
## Install on Windows
@@ -18,11 +16,8 @@ The current macOS DMG targets Apple silicon only; Intel Macs are not covered.
2. Open the file.
3. Complete setup.
4. Open RuneStone from the Start menu.
5. Use the folder button to open or create a workspace.
Setup installs RuneStone for your Windows account. Keep the default destination unless you need another location.
You do not need a terminal or developer tools.
If WebView2 is missing, setup downloads the runtime. Keep your internet connection active until setup finishes.
## Update or reinstall on Windows
@@ -36,12 +31,12 @@ You do not need to uninstall first. Setup preserves workspace files and settings
## Install on Linux
The experimental unsigned Debian package includes the app and its Browser runtime.
The Debian package includes the app and its Browser runtime.
The current `0.1.42` package targets Intel/AMD 64-bit (`amd64`), was built on
Ubuntu 26.04.1 LTS, and requires GLIBC 2.39 or newer. Other distributions,
architectures, and older Ubuntu versions have not been validated.
1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS` from the maintainer.
1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.
2. Save both files to Downloads and open Terminal in that folder.
3. Verify the download, then install the package:
@@ -63,7 +58,7 @@ For an update, close RuneStone and run the install command with the newer file.
Installation, reinstall, upgrade, removal, and workspace/settings preservation
still need lifecycle testing; package-content checks alone do not establish them.
For source development, use the [Linux guide](linux.md), which contains the
For source development, use the [Linux development guide](linux.md), which contains the
prerequisites, Browser preparation, and native desktop checks.
## Install on macOS
@@ -72,13 +67,9 @@ prerequisites, Browser preparation, and native desktop checks.
2. Open the disk image and drag RuneStone into Applications.
3. Eject the disk image.
4. Open RuneStone from Applications.
5. Use the folder button to open or create a workspace outside the application bundle.
The experimental 0.1.42 installer targets Apple silicon and includes its Browser runtime.
You do not need a terminal or developer tools. The disk image and bundled signatures have been checked,
but installation, desktop launch, Browser rendering, and update acceptance remain untested.
The app has local ad hoc signatures, without Developer ID signing or Apple notarization.
If macOS blocks opening it, check the installer source with the maintainer and report the exact message.
You do not need a terminal or developer tools. The app has local ad hoc signatures, without Developer ID signing or Apple notarization.
## Update or reinstall on macOS
@@ -87,52 +78,4 @@ If macOS blocks opening it, check the installer source with the maintainer and r
3. Drag RuneStone into Applications and confirm replacement of the existing app.
4. Eject the disk image and open RuneStone from Applications.
Keep workspace folders outside the application bundle. You do not need to remove those folders or your user settings.
## Try the source on macOS
This route is also experimental. It does not establish Intel or Apple silicon support.
1. Install Node.js 24, pnpm 10, and stable Rust.
2. Install Xcode Command Line Tools with `xcode-select --install`.
3. Download or clone RuneStone into a macOS folder.
4. Open Terminal in that folder and run the commands below.
```sh
pnpm install --frozen-lockfile
npm ci --prefix browser-runtime
npm --prefix browser-runtime run package
pnpm browser:stage
pnpm tauri dev
```
Tauri permits Command Line Tools for desktop development. See its [macOS prerequisites](https://v2.tauri.app/start/prerequisites/#macos).
The supplied macOS installer is experimental; Developer ID signing and notarization remain unresolved.
The bundled Browser runtime also needs a build for the target platform. A successful frontend build does not establish Browser support.
See [experimental packaging](builds.md#experimental-platform-packages) before producing an application bundle.
## Remove RuneStone
On Windows, open Settings → Apps → Installed apps, select RuneStone, then select Uninstall.
Windows 10 calls this list Apps & features.
On macOS, quit RuneStone and move it from Applications to the Trash.
Keep workspace folders outside the application folder. Removal leaves those separate folders in place.
On Linux, close RuneStone and run `sudo apt remove rune-stone` to remove the Debian package.
Linux removal remains untested. Keep workspaces outside application directories.
An experimental source session stops with Ctrl+C in its terminal. It does not install a desktop package.
## Setup help
| Problem | Action |
| --- | --- |
| WebView2 download fails | Restore the internet connection, then run the installer again. |
| Windows shows an unknown publisher | Local builds are unsigned. Check the file source with the maintainer. |
| macOS blocks opening RuneStone | The experimental build is not Apple notarized. Check the installer source with the maintainer and report the exact message. |
| A workspace will not open | Choose a folder that your account can access. |
| Linux reports missing or incompatible dependencies | Check the package architecture and GLIBC requirement above. Keep the APT error text and ask the maintainer for a compatible build. |
| A source build fails | Check the platform prerequisites and the [development help](development.md#development-help). |
| A source launch lacks Browser support | Check whether the Browser runtime exists for that platform. |
The [user guide](user-guide.md#resolve-file-conflicts) covers document errors after launch.
+47 -216
View File
@@ -1,17 +1,25 @@
# Linux readiness
# Linux development
[Complete Ubuntu setup commands](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) · [Developer guide](development.md)
[Development guide](development.md) · [Linux installation and updates](installation.md#install-on-linux) · [Build Linux packages](builds.md#build-linux-packages)
Linux support is experimental. Limited native validation is recorded below;
the complete desktop and installer acceptance checks remain outstanding.
Voice typing is outside the Linux acceptance criteria.
The initial target is Ubuntu 24.04 LTS, x86_64, with a local workspace and Bash.
This is a validation target, not a claim of tested support. Record the actual host below;
results on another distribution do not establish Ubuntu compatibility.
This guide covers Linux source development, Browser preparation, and native desktop checks.
To install a supplied RuneStone package, use [Installation and updates](installation.md#install-on-linux).
Past build and test results are in the [Linux validation reference](archive/linux-validation-2026-10.md).
## 1. Record the target
## Development prerequisites
Run these commands on the Linux box:
Use a Linux source checkout with Node.js 24, pnpm 10, and a stable Rust toolchain.
See the [shared development requirements](development.md#requirements) for repository setup.
Use [Tauri's Linux prerequisites](https://v2.tauri.app/start/prerequisites/#linux) for native libraries, including GTK and WebKitGTK 4.1.
The first build needs internet access for dependencies.
Open a terminal with Node.js, pnpm, and Cargo available on its PATH.
If a command is missing, load the environment configured by its installer before you continue.
Do not copy Windows `node_modules`, `src-tauri/target`, or `browser-engine` folders into Linux.
## Record the development environment
Run these commands in the Linux session used for native checks:
```sh
cat /etc/os-release
@@ -19,43 +27,14 @@ uname -m
printf 'Desktop: %s\nSession: %s\n' "$XDG_CURRENT_DESKTOP" "$XDG_SESSION_TYPE"
```
Record the distribution, version, processor architecture, desktop, and session type with the test results.
Record the distribution, version, processor architecture, desktop, and session type with the source commit and test results.
Test the session you use first. Test both Wayland and X11 before claiming support for both.
An Intel/AMD build does not establish ARM support.
## 2. Prepare the Linux build environment
## Build and run from source
Use the [complete README setup](../README.md#linux-ubuntu-2404-lts-intelamd-64-bit) for a first Ubuntu 24.04 trial.
It includes every tool installation command, source download, Browser preparation, and native launch.
Close the app and press Ctrl+C before the checks below.
Do not copy Windows `node_modules` or `src-tauri/target` folders into Linux.
The commands use the project's configured private clone address.
Source access is required. No public source-download location is configured.
The first build needs internet access for tools and dependencies.
### Command sources
The setup instructions were checked against these primary sources on October 15, 2026:
- [Tauri Linux prerequisites](https://v2.tauri.app/start/prerequisites/#linux): native development libraries and Rust installation.
- [Node.js downloads](https://nodejs.org/en/download) and [nvm installation](https://github.com/nvm-sh/nvm#install--update-script): Node.js 24 and its per-user installer.
- [pnpm 10 installation](https://pnpm.io/10.x/installation#using-npm): the npm installation method.
- [Rust installation](https://rust-lang.github.io/rustup/installation/index.html): the Rust toolchain and account environment.
- [Ubuntu 24.04 packages](https://packages.ubuntu.com/noble/): distribution package names, including the `t64` runtime libraries.
Browser commands come from `browser-runtime/package.json` and its packaging and staging scripts in this repository.
The README commands were reviewed on Windows. They were not executed on a clean Ubuntu 24.04 system.
## 3. Check the source and open the app
Load the account tools and enter the source folder before these checks:
```sh
. "$HOME/.nvm/nvm.sh"
. "$HOME/.cargo/env"
cd "$HOME/RuneStone"
```
Run the commands below from the RuneStone repository root in a graphical Linux session.
Commands come from [package.json](../package.json) and [browser-runtime/package.json](../browser-runtime/package.json).
From the Linux checkout, install the project dependencies:
@@ -86,9 +65,13 @@ work around sandbox failures with `--no-sandbox` or by running RuneStone as root
Test the Browser on the intended distro, including its user-namespace policy.
The native host uses WebKitGTK and the Browser uses Electron; both need testing.
### Source checks
The full test suite needs the Table Formulas package.
Clone `RuneStone_Table_Formulas` beside RuneStone and install its dependencies, as described in the [plugin guide](plugins.md).
Then run these checks from RuneStone:
Clone `RuneStone_Table_Formulas` beside RuneStone.
Install its dependencies as described in the [Table Formulas build example](plugin-development.md#example-table-formulas).
`pnpm build:plugins` builds only Table Formulas. Run these checks from the RuneStone repository root:
```sh
pnpm build:plugins
@@ -98,21 +81,27 @@ pnpm build
cargo test --manifest-path src-tauri/Cargo.toml --lib --locked
```
### Development session
Run the desktop app in your graphical Linux session:
```sh
pnpm tauri dev
```
This command starts Vite and opens the native desktop app. Keep the terminal open during development.
Save your work and press Ctrl+C in that terminal to stop the session.
See the [daily workflow](development.md#daily-workflow) for source edits and rebuild behavior.
A successful build does not establish desktop compatibility.
Browser tests use mocked desktop calls and Chromium. They do not test Linux file access or WebKitGTK behavior.
## 4. Complete the desktop checks
## Desktop checks
Use a disposable workspace outside the installation folder.
Record each result, the source commit, and any error message.
The complete acceptance checks below remain unverified on Linux. The validation
record distinguishes the limited smoke checks already completed.
Use this checklist for native behavior after source changes. Voice typing is outside the Linux acceptance criteria.
Keep each result separate from the [historical validation records](archive/linux-validation-2026-10.md).
| Area | Pass criteria |
| --- | --- |
@@ -126,183 +115,25 @@ record distinguishes the limited smoke checks already completed.
| Terminal plugin | Install the Terminal ZIP. Bash starts in the workspace, accepts Unicode, resizes, and exits when its session closes. |
| Settings | Change preferences, restart, and confirm persistence. Check separate workspace windows. |
Install the Terminal package separately as described in the [plugin guide](plugins.md).
Build Terminal with the [Terminal example](plugin-development.md#example-terminal), then [install its ZIP](plugins.md#install-a-plugin).
Check terminal profiles after a desktop launch too. A desktop launcher can have a different `PATH` from an interactive shell.
Current filename rules reject some names that Linux permits, including colons and backslashes.
Use ordinary portable filenames for the first trial. Record unsupported names as a limitation.
Use ordinary portable filenames for baseline checks. Record unsupported names as a limitation.
Mounted network shares need separate tests because Linux mount paths do not reliably select the current polling fallback.
Do not claim network workspace support from a local-disk test.
## 5. Build and test a package
## Package builds
After the desktop checks pass, build on Linux for the target processor architecture.
Choose the package format that matches the trial:
Use [Build Linux packages](builds.md#build-linux-packages) for Debian and AppImage commands, release handling, and package checks.
```sh
# Ubuntu or Debian
pnpm tauri build --bundles deb -- --locked
# AppImage trial
pnpm tauri build --bundles appimage -- --locked
```
Do not use `pnpm build:installer` on Linux. That command selects the Windows installer.
These direct Tauri commands do not manage the project release version or archive a
release. Before making a distributable, select the next version using the
[version policy](../AGENTS.md#versioning), keep all four version fields consistent,
and restore them if packaging fails. Move completed packages into
`releases/<version>/` together with checksums and the recorded source/test results;
do not leave duplicate completed packages in the toolchain bundle directory.
Packages appear under `src-tauri/target/release/bundle/deb/` or `src-tauri/target/release/bundle/appimage/`.
Install the Debian package with the distribution package manager, or make the AppImage executable and open it.
Test launch without development tools, same-version reinstall, upgrade, and removal on a separate test account.
Reinstall and upgrade must preserve settings and workspace files. Removal must preserve workspaces outside the installation folder.
For shared packages, build on the oldest distribution you intend to support that supplies WebKitGTK 4.1.
A package built on a newer system can require libraries unavailable on an older system.
An AppImage does not remove this compatibility limit.
See [Tauri's AppImage guidance](https://v2.tauri.app/distribute/appimage/) and [Debian packaging guidance](https://v2.tauri.app/distribute/debian/).
Call a distribution supported only after its native tests and package checks pass.
Repeat the automated checks on a Linux runner before each Linux release.
No Linux automation is configured yet. Add it when the build host and target distribution are known.
## Setup help
## Development help
| Problem | Action |
| --- | --- |
| `sudo` asks for a password | Type your Ubuntu account password, then press Enter. The terminal does not show the characters. |
| Git cannot reach `10.0.0.5` | Connect to the maintainer's network, or request a reachable clone address. |
| Git requests a username or password | Use repository credentials from the maintainer. Source access is separate from your Ubuntu account. |
| `destination path 'RuneStone' already exists` | Keep that folder. For an existing checkout, use the later-launch commands in the README. |
| `node`, `pnpm`, or `cargo` is not found | Use the later-launch block to load the account environment. Check that the earlier tool installation completed. |
| A system package cannot be found | Check your Ubuntu version with `cat /etc/os-release`. This command list targets Ubuntu 24.04. |
| The Browser runtime is missing | From the source folder, repeat `npm ci --prefix browser-runtime`, then its `package` command and `pnpm browser:stage`. |
| Electron reports a sandbox or user-namespace error | Keep the sandbox enabled. Report the error and Ubuntu version to the maintainer. Do not run RuneStone as root. |
| The first build stops | Keep the first error text and failed command. Report them with your Ubuntu version and available memory/disk space. |
| Node.js, pnpm, or Cargo is missing | Load your toolchain environment and check the [development prerequisites](#development-prerequisites). |
| The Browser runtime is missing | From the repository root, repeat the Browser dependency, package, and staging commands in [Build and run from source](#build-and-run-from-source). |
| Electron reports a sandbox or user-namespace error | Keep the sandbox enabled. Record the error and distribution version. Run RuneStone as an ordinary desktop user. |
| A build stops | Record the first error, failed command, distribution version, and available memory and disk space. |
Use the [validation checks](#4-complete-the-desktop-checks) after the first launch.
## Validation record: 2026-10-14
Validated on `desk`: Ubuntu 26.04.1 LTS, x86_64, four CPUs, 7.2 GiB reported RAM,
XFCE/X11, Linux 7.0.0-38-generic. The execution environment reports a container
boundary and underlying KVM virtualization. This does not validate Ubuntu 24.04,
Wayland, ARM, or another distribution.
Source: base commit `edef2520afc92f7896454bf94a8ea15bbf4e1684` plus the Linux
readiness patch and the Browser window portability fix. The original transferred
source archive had SHA-256
`b16643bfc7a634e5a5d17a7c246e87d95a458c06fb8afb45899a28a460e03047`.
The first native compile found a Windows-only `drag_and_drop(false)` call in
`src-tauri/src/browser.rs`; it now uses the cross-platform
`disable_drag_drop_handler()` API already used by the settings window.
Toolchain: Node.js 24.22.0, pnpm 10.34.7, Rust/Cargo 1.93.1, GLib 2.88.0,
GTK 3.24.52, and WebKitGTK 4.1 version 2.52.6. Native builds used one job and
`CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0` to conserve RAM and disk.
| Check | Recorded result |
| --- | --- |
| `pnpm install --frozen-lockfile` and `npm ci --prefix browser-runtime` | Passed |
| `pnpm check` | Passed; zero errors and warnings |
| `pnpm build` | Passed; bundle-size warnings remain |
| `pnpm browser:check` and `pnpm browser:test` | Passed; 44 Browser unit tests |
| Browser Linux packaging and `pnpm browser:stage` | Passed; x86_64 runtime staged |
| `npm --prefix browser-runtime run test:packaged` | Passed; all 12 engine smoke checks, sandbox enabled |
| `pnpm test` | 238 passed, one skipped, two test files failed because the Table Formulas package was absent |
| `cargo test --manifest-path src-tauri/Cargo.toml --lib --locked --offline -j 1` | Passed after the portability fix; 92 passed, three ignored |
| `pnpm tauri build --debug --no-bundle -- --locked --offline -j 1` | Passed; native debug executable, version 0.1.34 |
| Tauri X11 launch | Visible 1400 by 900 window; rendered frontend verified with an internal capture |
| Host Browser integration | Open Browser opened a Browser tab with address and profile controls; no webpage-navigation claim |
GUI checks used isolated task-local XDG settings/data directories, and the test
processes were closed afterward. Virtual-GPU EGL/VAAPI warnings occurred; they did
not prevent these smoke checks. No sandbox, security, swap, or permission workaround
was used. Existing user settings and workspaces were not used.
No installer or release package was produced, versions were unchanged, and nothing
was published. Remaining work includes supplying/building `RuneStone_Table_Formulas`
and rerunning the full source suite, completing the desktop checks above, and
validating Debian/AppImage installation and lifecycle behavior on the intended
target distribution. These results do not establish full Linux support.
### Initial bounded release attempt
The normal release profile (`opt-level = 3`, full LTO, one codegen unit) was
attempted with one Cargo job, locked/offline dependencies, and the already-tested
frontend output. Before starting, desk had about 2.0 GiB available RAM, effectively
full 4.0 GiB swap, and 4.1 GiB free disk. A temporary user service bounded the
entire build to 1,677,721,600 bytes of RAM and no additional swap.
The release build reached the GTK Rust crate but exceeded that hard cap. The
service recorded `Result=oom-kill`, `MemoryPeak=1677721600`, and zero swap use after
14 minutes 47 seconds. Soft memory throttling was tried first; it caused repeated
reclaim, so the soft threshold was removed while retaining the hard cap. No larger
memory allowance was attempted. The temporary service was cleaned up; dependency
and build caches were preserved. About 3.3 GiB disk remained afterward.
No optimized executable, Debian package, or AppImage was produced. AppImage
bundling was not attempted because it needs the release executable. Package
contents, generated dependency metadata, and installation lifecycle therefore
remain unvalidated. `ldd` found no missing libraries for the previously tested
debug host and staged Browser on desk. In addition to host libraries, the Browser
needs NSPR/NSS, CUPS, and ALSA libraries; their Ubuntu 26.04 providers include
`libnspr4`, `libnss3`, `libcups2t64`, and `libasound2t64`. Check the eventual package
declares the appropriate runtime dependencies; the current machine having them
installed does not prove that package metadata is complete.
The smallest next step is to free more RAM on desk, or use a host with more
available memory, then retry the cached release build with a larger bounded
allowance. Starting with at least 3 GiB available RAM provides more headroom but
does not establish the required peak; measure it during the retry. Recheck disk
before bundling. Existing debug-build and smoke-test results above still stand.
### Release package validation: 2026-10-15
After desk returned with more headroom, a fresh resource check found 4,956,172 KiB
available RAM (about 4.73 GiB), nearly all 4 GiB swap free, and 47 GiB free disk.
No finite inherited user-cgroup memory limit was found. The cached release build
was retried with one job, a temporary 3.5 GiB memory cap, and no build-group swap.
It completed successfully in 12 minutes 32 seconds, with 3.5 GiB peak group memory
and no OOM event. The earlier failure establishes only that the chosen 1,600 MiB
cap was insufficient; it does not establish that the 8 GB VM cannot build.
The initial Debian bundle declared only GTK and WebKitGTK. Added
`src-tauri/tauri.linux.conf.json` to declare OpenSSL plus the Browser's NSS/NSPR and
ALSA dependencies. The release executable requires GLIBC 2.39, so the Debian
metadata also declares `libc6 (>= 2.39)`. Tauri retains its default GTK/WebKitGTK
dependencies. Recheck symbol requirements when changing the compiler or build host;
this floor is evidence from this build, not a permanent portability guarantee.
The Debian package was regenerated and its final dependency metadata verified.
| Release check | Recorded result |
| --- | --- |
| Normal optimized release profile and Debian bundling | Passed, using locked/offline Cargo dependencies and the previously validated frontend |
| Debian package | `RuneStone_0.1.34_amd64.deb`, package name `rune-stone`, version `0.1.34`, architecture `amd64` |
| Debian package checksums, desktop entry, resources and permissions | Passed; host and Browser executables are executable, Browser resource directory is traversable, packaged checksums match |
| Debian shared libraries on desk | All host and Browser libraries resolve |
| Extracted Debian GUI smoke | Host rendered a visible window, launched its own packaged Browser executable, and rendered an HTTPS page |
| AppImage bundling | Passed from the same optimized release executable; 2 minutes 18 seconds, about 1.6 GiB peak memory, no build-group swap |
| Extracted AppImage GUI smoke | AppRun launched, bundled WebKitGTK child processes were used, its packaged Browser launched, and an HTTPS page rendered |
Both package tests used isolated task-local settings/data and closed their test
processes afterward. AppImage's supported extraction route was used because the
VM does not expose `/dev/fuse`; FUSE-mounted execution was not tested. Virtual-GPU
acceleration warnings did not prevent rendering. Versions remain 0.1.34 under the
explicit validation-build instruction. These are unsigned experimental artifacts,
not published releases. Completed package files, metadata, test limits, and
checksums are archived under `releases/0.1.34/` outside Git.
No app was installed system-wide and no existing user workspace/settings were
used. Installation, same-version reinstall, upgrade, removal, the full desktop
acceptance matrix, Ubuntu 24.04, Wayland, and other architectures remain untested.
The Table Formulas external dependency remains absent. Native library resolution
on desk and successful extraction smoke checks do not prove clean-machine package
installation or compatibility with other distributions.
The AppImage's bundled WebKitGTK and JavaScriptCoreGTK libraries require GLIBC
2.43. The Debian executable's GLIBC 2.39 floor therefore does not describe the
AppImage's minimum runtime. Treat this AppImage as an Ubuntu 26.04 validation
artifact rather than a portable Ubuntu 24.04 build.
See [development help](development.md#development-help) for port conflicts, stale windows, and offline Cargo errors.
+458
View File
@@ -0,0 +1,458 @@
# Plugin development reference
[Development](development.md) · [Install and manage plugins](plugins.md)
This reference is for authors who develop, package, and release RuneStone plugins.
It covers the shared package contract, build examples, release requirements, and plugin APIs.
For installation internals and host tests, use the [plugin host reference](plugin-host.md).
For installation, updates, switches, and removal, use the [user guide for plugins](plugins.md).
All plugins use the same package and installation system.
- [Package contract](#package-contract)
- [Versioning](#versioning-for-plugin-authors-and-agents)
- [Build and release a plugin](#build-and-release-a-plugin)
- [Build examples](#build-examples)
- [Publishing releases](#publishing-releases)
- [Plugin API](#plugin-api)
- [Git API](#git-api)
- [Temporary background API](#temporary-background-api)
## Package contract
Place `plugin.json` at the root of the ZIP 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`.
RuneStone 0.1.5 adds optional `placement: "editor"` for views that belong beside documents.
These views open in the editor area with a tab. Document tabs retain their buffers when users switch views.
Closing the plugin tab or disabling the package disposes the view.
The default placement is `"dialog"`, so existing packages keep their current behavior.
Older hosts ignore the placement field. Plugins that require editor placement need RuneStone 0.1.5 or later.
All packages use one API and the same installation, enable, disable, and removal lifecycle.
Versions use three numeric parts with an optional lowercase hotfix suffix, such as `0.2.28a`.
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.
## Versioning for plugin authors and agents
Follow the shared [RuneStone versioning policy](../AGENTS.md#versioning). RuneStone and its plugins keep independent version numbers under this policy.
Use `zz.yy.xx` and keep routine implementation work in the current `zz.yy` series.
| Part | When to increase it |
| --- | --- |
| `xx` | Each new completed regular plugin ZIP build. Hotfixes increase the letter suffix. |
| `yy` | A deliberate release ready for build testing, with user direction. Reset `xx` to zero. |
| `zz` | A full release, with user direction. Reset `yy` and `xx` to zero. |
Keep the current version during source edits, fixes, improvements, documentation work, and automated checks.
Set the next version when producing the ZIP. Intermediate compilation output does not count as a new build.
If no build completes, restore the previous version fields. Failed attempts and retries do not consume version numbers.
Report a new version as available only after its ZIP exists. Publishing an existing artifact does not increase its version.
Passing automated checks alone does not authorize a `yy` or `zz` increase.
A hotfix fixes one item or a narrowly scoped problem in an existing release.
Use letters in the actual package version: `0.2.28` → `0.2.28a` → `0.2.28b`.
Keep the numeric base for hotfix builds.
Advance hotfix suffixes in this order: `a`, `b`, `c`, through `z`, then `aa`, `ab`, and later suffixes.
The next regular build increases `xx` and removes the suffix: `0.2.28b` → `0.2.29`.
Keep the package version, manifest version, build metadata, ZIP name, release notes, and tag consistent.
For example, package version `0.2.28a` produces `runestone.pm-0.2.28a.zip` and uses tag `v0.2.28a`.
The shared packager and updated native installer accept these suffixes. Older hosts with numeric-only validation reject suffixed packages.
Do not substitute a numeric increment for a hotfix. Add suffix support or report a format blocker before building.
Do not bypass validation or overwrite an existing release ZIP.
## Build and release a plugin
Use the same package contract for in-house and community plugins.
The ZIP is the release file. Its `plugin.json` describes the contents and is not a separate installer.
```text
org.example.hello-1.0.0.zip
plugin.json
main.js
assets/
README.md
LICENSE
```
The manifest and entry module are required. Assets, a README, and a license are optional package files.
Include a README with the host requirement, purpose, install steps, and help contact.
Keep JavaScript readable where practical. Avoid minification and obfuscation that make inspection harder.
1. Compile the plugin into a clean folder with `plugin.json`, its entry module, and the required assets.
2. Run `pnpm package:plugin <compiled-folder> [output-folder]` from the RuneStone repository.
3. Install the resulting ZIP in RuneStone and test its features, disable action, and uninstall action.
4. Share that same ZIP through the [publishing procedure](#publishing-releases).
Use Node.js 24 or later for the packaging command. The default output folder is `releases/` in the project that contains the compiled folder.
Keep plugin release ZIPs in that plugin project, including when the host calls the build.
Explicit output folders are for temporary checks or staging. Move completed releases into the owning project's `releases/` folder.
It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`.
It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder.
The output folder must be outside the input folder.
The command rejects an existing ZIP with different contents. Identical contents reuse the existing file.
Use the next build version for a changed release and preserve existing ZIPs.
Repeated runs with unchanged input produce the same archive bytes.
The native installer checks the package again before installation.
Other build tools can create the same ZIP layout. Do not add a parent folder above `plugin.json`.
Do not tell users to load JSON, select a build folder, rename a new release, or install dependencies.
Authors in other repositories can run `node <RuneStone-path>/scripts/packagePlugin.mjs <compiled-folder> <output-folder>`.
## Build examples
These examples are for plugin developers. To install an existing ZIP, use the [plugin installation guide](plugins.md#install-a-plugin).
Complete the [source setup](development.md#run-from-source) before using host build commands.
Each plugin has its own build command. Check that project's package scripts before building it.
Apply the [versioning policy](#versioning-for-plugin-authors-and-agents) before producing a new release ZIP.
### Example: Table Formulas
Source: [Table Formulas repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas).
The host's [build script](../scripts/buildPlugins.mjs) defines this example.
Despite its plural name, `pnpm build:plugins` builds only Table Formulas.
1. Clone the Table Formulas repository into `RuneStone_Table_Formulas` beside the RuneStone folder.
2. In that plugin folder, run `pnpm install --frozen-lockfile`.
3. In the RuneStone folder, run `pnpm build:plugins`.
4. Install the resulting ZIP through [Settings → Plug-ins](plugins.md#install-a-plugin).
The ZIP is `../RuneStone_Table_Formulas/releases/runestone.table-formulas-<version>.zip`, relative to RuneStone.
The host stages compiled files in `plugin-packages/table-formulas/` for inspection and tests.
Set `RUNESTONE_TABLE_FORMULAS_ROOT` when the plugin checkout is elsewhere.
The plugin also supports `pnpm package:plugin` from its own folder.
Set `RUNESTONE_ROOT` there if its host checkout is elsewhere.
### Example: Terminal
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal).
Its `package.json` and `scripts/build.mjs` define this example.
1. Clone the Terminal repository into `RuneStone_Terminal` beside the RuneStone folder.
2. In that plugin folder, run `pnpm install --frozen-lockfile`.
3. In the same folder, run `pnpm build`.
4. Install the resulting ZIP through [Settings → Plug-ins](plugins.md#install-a-plugin).
The ZIP is `releases/runestone.terminal-<version>.zip`, relative to the Terminal folder.
This build bundles its JavaScript dependencies and terminal styles.
The host supplies native pseudo-terminal services. The plugin supplies the interface, shortcuts, and session controls.
For session controls and appearance, use the [Terminal guide](guides/terminal.md).
### Example: Workspace overview
Source: the [Workspace overview fixture](../fixtures/plugins/workspace-overview/plugin.json) in this repository.
This small example already contains a JavaScript entry module.
1. From the RuneStone folder, run `pnpm package:plugin fixtures/plugins/workspace-overview`.
2. Install the resulting ZIP from the host's `releases/` folder.
3. Choose **Install and enable**.
4. Choose **Open tab or view → Workspace overview**.
You can also use **Commands → Show workspace overview**.
This fixture belongs to the host. Release ZIPs for separate plugin projects stay in each plugin's own `releases/` folder.
The RuneStone installer does not include optional plugin packages.
After source changes, build the affected package again and install its new ZIP.
## Publishing releases
These requirements apply to RuneStone plugins on any hosting service.
The hosting service stores the release files. RuneStone defines the package format, version policy, and installation checks.
Users can download a plugin ZIP from any service and install it through [Settings → Plug-ins](plugins.md#install-a-plugin).
Installation directly from a repository link depends on RuneStone's support for that service.
### Release standard for plugin writers and agents
Apply the [shared versioning rules](#versioning-for-plugin-authors-and-agents) when producing a new ZIP.
Use one plugin repository and one standard plugin ZIP per published release.
This is a RuneStone release requirement, independent of the hosting service.
No repository manifest or special branch layout is required.
1. Select the tested ZIP from the [shared build procedure](#build-and-release-a-plugin).
2. Create a release tag that identifies the source commit used for that ZIP.
3. Attach the tested `<id>-<version>.zip` and release notes to a release on your chosen service.
4. Publish the release and share its download page or package link.
5. Download the published ZIP and test its installation in RuneStone.
Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases.
Identify prereleases clearly on the release page and supply their explicit tags.
Keep the manifest, package, metadata, filename, release notes, and tag consistent with the version policy.
Each new regular ZIP advances the numeric build version. Each hotfix ZIP advances the lowercase letter suffix.
Publishing an existing ZIP does not change its version. Keep published release files unchanged.
Moving an unchanged release to another service does not require a new package or version.
The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies.
Do not use a repository source archive as the plugin package.
Keep the single plugin ZIP separate from any source archives that the service generates automatically.
Other attachments, such as checksums and release notes, can accompany the plugin ZIP.
Keep release notes short. State the required RuneStone version, plugin version, changes, and known limits.
Give users a link to the plugin ZIP and the [ZIP installation procedure](plugins.md#install-a-plugin).
For a private release, users need permission to download the package.
Test local ZIP installation before publication.
After publication, test download, review, disabled installation, enable, disable, and removal with the published ZIP.
Check that cancellation leaves no installed package.
Check that an existing plugin ID enters the reviewed update flow and retains its settings and enabled state.
If RuneStone supports direct installation from that service, also test its repository link and explicit release tag.
### GitHub Releases
Attach the tested plugin ZIP to a GitHub release for its source tag.
GitHub's automatic source archives do not replace the attached plugin package.
See [GitHub's release instructions](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository) for publication steps.
Users download the attached ZIP and install it through **Settings → Plug-ins → Install plugin ZIP**.
RuneStone does not yet support installation directly from a GitHub repository link.
That feature requires a GitHub download adapter and tests.
### Gitea releases
Attach the same standard plugin ZIP to a Gitea release for its source tag.
Users can download and install the ZIP, or use RuneStone's [experimental Gitea-link installation](plugins.md#install-from-a-gitea-link-experimental).
For direct installation, use a repository root link with an optional trailing `.git`.
The Gitea server must run at the host root. Use an explicit tag for a prerelease trial.
The latest-release route excludes drafts and prereleases. The downloader rejects drafts and releases without exactly one attached ZIP.
Automatic source archives do not count as release attachments.
Private repositories require read access to both the release metadata and the attachment.
Use HTTPS for remote releases. The metadata limit is 2 MiB, and the compressed ZIP limit is 100 MiB.
The [package limits](#package-contract) also apply to extracted files.
For credential handling, redirects, and staged file checks, see the [host download reference](plugin-host.md#gitea-downloads).
### Other hosting services
Publish the tested plugin ZIP and its release notes through your chosen service.
Users download the ZIP, then use the same local installation procedure.
RuneStone has no direct repository-link adapter for GitLab or other services.
## Plugin API
The current source adds an optional [completion API](completion.md) for local model providers and plugin-owned text fields.
This capability is not present in the existing 0.1.7 installer.
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
The 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 Commands in the toolbar |
| `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view |
| `registerView({ id, title, placement?, mount })` | Add a view in a dialog or the editor area |
| `registerView({ settings: true, ... })` | Add a configuration page to Settings |
| `registerView({ launcher: false, ... })` | Keep a dynamic view out of the launch menu |
| `registerView({ navigation: true, icon?, ... })` | Add an icon button to the ribbon left of the navigation pane |
| `registerDocumentType(type)` | Recognize document content, supply a navigation icon, and mount a document editor |
| `openDocument(path)` | Open a recognized document in its own tab |
| `renameDocument({ id, path }, name)` | Rename a recognized document and return its new workspace path. Optional API |
| `openView(id)` | Open one of the plugin's registered views |
| `openView(id, { split, relativeTo })` | Open an editor view beside another view. `split` accepts `right` or `down` |
| `closeView(id)` | Close an editor view owned by this plugin. Optional API |
| `registerView({ tabActions, find, pinned, ... })` | Supply tab actions, a Find handler, and the initial pin state |
| `registerView({ tabDragData, ... })` | Supply transfer data for a tab. The callback receives its pin state |
| `registerTabDrop(receive)` | Accept a tab from another window. Optional API |
| `onDispose(callback)` | Register synchronous or asynchronous cleanup |
| `workspace.list(path?)` | List a directory in this window's active workspace |
| `workspace.listMarkdown()` | Return sorted visible Markdown paths in one native request. Optional API |
| `workspace.read(path)` | Read a workspace text file |
| `workspace.readMany(paths)` | Optional batched text read. Accept at most 64 paths and return a source or error for each path |
| `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update |
| `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 |
| `workspace.create(path, contents)` | Create complete text without replacing an existing file. Added in 0.1.6 |
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
| `workspace.subscribe(listener)` | Receive workspace change notifications. Returns a cleanup function |
| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit |
| `settings.subscribe(listener)` | Receive saved settings changes across windows. Optional API |
| `assets.read(path)` | Read package bytes as a `Uint8Array` |
### Workspace reads
Check for `workspace.readMany` before calling it. Older hosts require individual reads.
Each result contains `path` and either `source` or `error`. One failed file does not discard the remaining results.
The native batch accepts at most 64 paths and 16 MiB of combined UTF-8 text.
Workspace path checks and plugin shutdown checks apply to these reads.
### Commands, views, and settings
Command and view IDs must be unique within their respective plugin collections.
Plugin commands can supply an optional `icon` from the shared action icon set in `src/lib/ui/actionIcons.ts`.
Use a recognizable action icon, such as `skip-forward` or `pause`, for each command. Older hosts can ignore this field.
Sidebar views belong in the left navigation. Views with a direct navigation button do not repeat in the plugin launch menu.
Plugin configuration appears in Settings under the plugin name.
Register a view with `settings: true` to add its configuration page.
The host mounts that view inside Settings and removes it from the launch menu.
Settings loads enabled plugins so their configuration pages remain available in the separate settings window.
The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`.
Older hosts can omit the context argument.
The language setting applies to RuneStone's interface. The host does not translate plugin interfaces or supply a plugin translation API.
Plugin authors can manage translations within their own packages.
The Open tab or view menu contains plugin views and commands with `category: "open"`.
Other commands appear in Commands.
Set `launcher: false` on dynamic views that already have tabs.
Existing packages can omit these optional fields.
Plugins can call `settings.subscribe(listener)` to receive notifications when their saved settings change.
The listener must read the new settings with `settings.read()`.
Notifications cross window boundaries and contain only the plugin ID.
The host removes subscriptions when the plugin stops.
Plugins must ignore pending reads after shutdown and prevent older reads from replacing newer settings.
### Document types
Document type IDs must also be unique within their collection.
Document types declare file extensions, an `identify` function, and a `mount` function.
The identify function returns a stable document ID or null. Invalid documents remain available through the text editor.
An optional creation action supplies complete file text. Creation never replaces an existing file.
Each document opens in its own editor tab. Opening the same document focuses its existing tab.
Closing one tab disposes only that mount. Disabling the plugin disposes all its mounts and removes its navigation entries.
The host rejects plugin writes when a note has unsaved editor changes.
These document APIs require the current host source. The earlier 0.1.6 installer does not include them.
The optional API method `renameDocument({ id, path }, name)` renames a recognized document and returns its new workspace path.
The host checks the document ID and plugin owner. It keeps the folder and extension, rejects name collisions, and updates open tabs.
Names can contain dots. Hidden names and reserved filename characters are invalid.
Unsaved text edits block plugin renames. This method requires the updated host source.
Binary document types set `content: "binary"`. Text remains the default.
For binary types, `identify(path, source)` receives an empty source string and recognizes the path without reading its contents.
The mount reads bytes with `workspace.readBytes(path)` and reports invalid document data in its own view.
This avoids UTF-8 conversion and full file reads while the file tree identifies binary documents.
The native read command checks the active window's workspace boundary and rejects directories and files larger than 64 MiB.
Binary document support requires the updated host source. The earlier 0.1.6 installer does not include it.
Check for `api.workspace.readBytes` during activation and report a clear host update error when it is absent.
### Sidebar views and tab replacement
Navigation views with `placement: "sidebar"` appear beside Files, Search, and Bookmarks in the top header.
Other navigation views appear as icon buttons in the ribbon left of the navigation pane.
The optional view `icon` accepts `list`, `kanban`, or `puzzle`. The default is `puzzle`.
Buttons show the view title in a tooltip on hover and keyboard focus.
The ribbon remains available when the navigation pane is closed.
The optional `openFile(path)` method opens a workspace file.
The optional `replaceView(currentId, nextId)` method changes the current tab while preserving its position and pin state.
For document tabs, `replaceDocumentWithView(document, nextId)` supplies the same behavior.
Both methods restrict the source and destination to the calling plugin.
### View launch defaults
Views can supply an optional `launch()` handler for entry through the plugin launcher or navigation button.
The handler can select a default view with `api.openView(id)`.
Explicit `api.openView` calls and restored tabs bypass the launch handler and retain their targets.
Views without a handler open as before. Older hosts ignore this optional field.
Example: [Project Management](../../RuneStone_Project_Management/development.md#workspace-default-board) uses this handler to open its fixed workspace default board.
### Cleanup and contributions
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.
## Git API
The optional `git` API supplies status, diff, stage, unstage, commit, and blame operations.
The current host source also supplies `push()`, `pull()`, and `graph()`.
These methods require an updated host and remain subject to plugin shutdown checks.
The host returns structured history from `git.graph()`:
```js
{ commits: [{ id, parents, refs, summary, author, date }] }
```
The history contains at most 100 commits. Parent IDs can refer to commits outside that history.
Example: the [Git plugin](../../RuneStone_Git/docs/usage.md#commit-graph) renders these commits and parent links as a graph.
For the native service and test setup, see the [Git development guide](../../RuneStone_Git/docs/development.md).
## Temporary background API
RuneStone 0.1.25 adds optional `api.backgrounds` with `version: 1`.
Example: [Background Slideshow](../../RuneStone_Background_Slideshow/docs/development.md#integration) publishes frames from local image folders.
Example: [Project Management](../../RuneStone_Project_Management/development.md#pm-0229-slideshow-backgrounds) consumes frames for board backgrounds.
| Method | Contract |
| --- | --- |
| `chooseFolder()` | Open the native folder picker. Return an absolute path or null on cancellation. |
| `defaultFolder()` | Optional. Create and return Pictures/RuneStone Backgrounds for new settings. |
| `list(folder)` | List PNG, JPEG, GIF, and WebP filenames directly inside the folder. |
| `read(folder, name)` | Read one raster image as bytes, with a 50 MiB limit. |
| `set(target, frame)` | Apply a temporary frame. Pass null to remove this plugin's frame. |
| `get(target)` | Read the active frame or null. |
| `subscribe(listener)` | Receive the changed target. Return a cleanup function. |
Targets are `app`, `pm-all`, and `pm-board:<board UUID>`.
A frame contains `url`, `overlay`, `position`, and `size`.
It can also contain `previous` with those four fields and `transitionMs` from 0 to 5000.
Renderers fade between these frames unless reduced motion is active. Keep both blob URLs valid until replacement or cleanup.
Use a blob URL. The publishing plugin owns the URL and must release it after replacement or cleanup.
Overlay ranges from -1 to 1. Negative values lighten the image, and positive values darken it.
Position and size use the same choices as custom image settings.
Frames belong to the plugin activation in the current window. They do not change saved background settings.
The last published frame wins. Removing it reveals an earlier active frame or the saved background.
Disable removes the plugin's frames and subscriptions before cleanup.
File access requires an active plugin lease. Pending reads fail after access is revoked.
Image reads reject path traversal, linked files, unsupported formats, and oversized files.
Use the plugin settings API to share saved configuration across windows. Temporary frames remain local to each window.
### Per-image background settings
The optional background API adds `readImageSettings` and `writeImageSettings`.
The sidecar file is `.runestone-backgrounds.json` beside the images, with schema 1, an `images` object, and a 1 MiB limit.
Writes compare the previous file text to preserve external changes.
Temporary frames can supply `blurredUrl`. Each target scales the foreground and blurred layer separately.
The plugin owns all frame URLs and releases them after replacement or shutdown.
See the [Slideshow image settings example](../../RuneStone_Background_Slideshow/docs/development.md#per-image-settings) for its storage and rendering behavior.
+148
View File
@@ -0,0 +1,148 @@
# Plugin host internals and checks
[Development](development.md) · [Plugin development](plugin-development.md) · [Install and manage plugins](plugins.md)
This reference is for developers who change RuneStone's plugin host.
It covers package storage, installation and removal transactions, remote downloads, source modules, and checks.
Plugin authors should use the [package and API reference](plugin-development.md).
- [Storage and recovery](#storage-and-recovery)
- [Gitea downloads](#gitea-downloads)
- [Modules and checks](#modules-and-checks)
## Storage and recovery
RuneStone resolves the root through Tauri's `app_data_dir()`. Settings shows the complete path.
```text
<application-data>/
plugins/<plugin-id>/
plugin.json
main.js
assets/
plugin-data/<plugin-id>/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.
An untracked destination blocks publication. Reviewed updates pin the installed package hash and retain a recovery journal.
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.
### Installation and update transactions
RuneStone copies source packages without modifying them. The review shows author, version, source, destination, and access.
Users can inspect the ZIP without extracting it for installation.
The picker accepts at most 100 ZIPs. Folders and loose manifests are not installation inputs.
Legacy `.runestone-plugin` archives use ZIP format and can be renamed to `.zip` for installation.
Installed packages and saved settings do not need migration.
Scanning and installation do not execute code, install dependencies, or run scripts.
Package metadata and hashes do not prove publisher identity. There is no permission sandbox or marketplace.
An installed ID selects the update flow. Updates retain settings and the previous enabled state.
Runtime cleanup must succeed in every window before replacement.
An interrupted update restores the old package unless the new catalog entry committed.
Each package succeeds or fails independently. A changed source requires a new review.
Canceling the review removes temporary copies. Automatic repository scans remain future work.
### Removal behavior
The uninstall dialog initially focuses Cancel. Escape cancels removal.
Each uninstall requires a new confirmation. Cancel preserves files and enabled state.
Disable instead stops the plugin and retains its installed files.
Confirmed removal deletes only the installed package after cleanup in every window.
Source downloads, settings, generated data, and workspace documents remain intact.
Loaded JavaScript can remain in memory until RuneStone closes, so the app requests a restart.
Cleanup failure blocks deletion. Interrupted deletion shows Removal incomplete and permits Retry cleanup.
Changed remaining files block further deletion. Reinstallation requires a new enable decision and can reuse retained settings.
## Gitea downloads
For publication on any service, use the [shared publishing guidance](plugin-development.md#publishing-releases).
This section describes the current Gitea download adapter.
Gitea repository links now supply ZIP packages to the existing review and installation flow.
This trial supports Gitea at the host root, including the personal Gitea server.
GitHub and GitLab support remain future work. Their release APIs need separate tests.
Use the [Gitea installation procedure](plugins.md#install-from-a-gitea-link-experimental) to test a published package.
For example, `https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal` is a repository root link.
That link works for installation only when its selected release contains a plugin ZIP.
The link can end in `.git`. SSH links, branch links, source archives, and links with credentials are not installation inputs.
Use an explicit tag for a prerelease trial. The latest-release route excludes drafts and prereleases.
RuneStone clears the token after each request and when the form closes. It does not save the token.
Use HTTPS. HTTP is available for trusted local servers, but it sends the token and package without encryption.
Credentials go only to the original API origin. Redirects to another origin do not receive the token.
A release attachment on another private host needs its own access method and is outside this trial.
The downloader reads release metadata, then downloads one attached ZIP.
It does not clone the repository, compile code, install dependencies, or run scripts.
Downloads have size limits, time limits, and a redirect limit.
The metadata limit is 2 MiB. The compressed ZIP limit is 100 MiB.
The [package limits](plugin-development.md#package-contract) still apply to the extracted files.
HTTPS links cannot redirect or select an attachment over HTTP.
The review shows the repository, release tag, attachment link, manifest, and destination.
It pins the downloaded content. Installation checks that the staged files still match the reviewed hash.
Changing a remote release after review does not change the pending installation.
The same duplicate-ID, enable, removal, and cleanup rules apply to local and remote packages.
## 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 |
| `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository |
| `../RuneStone_Table_Formulas/` | Table Formulas source, unit tests, and package build |
| `scripts/buildPlugins.mjs` | Table Formulas compilation and ZIP release in `../RuneStone_Table_Formulas/releases/` |
| `scripts/packagePlugin.mjs` | Shared checks and ZIP creation for plugin authors |
Complete the [host source setup](development.md#run-from-source) and the [plugin build prerequisites](plugin-development.md#build-examples) first.
Run host commands from the RuneStone repository root.
Use the [development checks](development.md#checks) for type checks, unit tests, frontend compilation, and native tests.
For Table Formulas, use its [build example](plugin-development.md#example-table-formulas).
For Terminal, run `pnpm check`, `pnpm test`, and `pnpm build` in `RuneStone_Terminal`.
Build Terminal before host browser tests. They read `../RuneStone_Terminal/dist/` by default.
Set `RUNESTONE_TERMINAL_DIST` to use another compiled terminal folder.
The Rust tests use real temporary files and archives. Browser tests mock desktop calls and exercise the real UI and module loader.
Complete the [browser test setup](development.md#browser-smoke-tests), then run these checks from the RuneStone repository root:
```powershell
node scripts/pluginInstall.smoke.mjs
node scripts/plugins.smoke.mjs
node scripts/settings.smoke.mjs
cargo test --manifest-path src-tauri/Cargo.toml --lib plugin
```
The installation smoke test covers the link form, download errors, token clearing, cancellation, focus, and disabled installation.
Native tests cover URL parsing, release selection, redirects, credential boundaries, size limits, changed staging files, and invalid ZIPs.
For the recorded four-package trial and its repeat command, see the [October 5 test record](archive/plugin-release-trial-2026-10-05.md).
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.
-32
View File
@@ -1,32 +0,0 @@
# Plugin names and source folders
Use these display names in Settings, manifests, help, and problem reports.
Each checkout sits beside `RuneStone`, except the built-in Browser.
| Display name | Source folder | Stable plugin ID |
| --- | --- | --- |
| Browser (built in) | `RuneStone/browser-runtime` | `runestone.browser` (legacy) |
| Background Slideshow | `RuneStone_Background_Slideshow` | `runestone.bg-slideshow` |
| CSV Viewer | `RuneStone_CSV_Viewer` | `runestone.csv-viewer` |
| Git | `RuneStone_Git` | `runestone.git` |
| Local Autocomplete | `RuneStone_Local_Autocomplete` | `runestone.local-autocomplete` |
| PDF Viewer | `RuneStone_PDF_Viewer` | `runestone.pdf-viewer` |
| Project Management | `RuneStone_Project_Management` | `runestone.pm` |
| Table Formulas | `RuneStone_Table_Formulas` | `runestone.table-formulas` |
| Terminal | `RuneStone_Terminal` | `runestone.terminal` |
## Stable package and data names
Display names describe the plugins. Stable IDs connect installed packages to their settings and saved data.
The packager uses each stable plugin ID and version for the ZIP filename.
For example, Project Management uses `runestone.pm-<version>.zip`.
Changing capitalization does not change plugin IDs, settings, or saved workspace data.
Project Management retains `.runestone/pm/`, `runestone_pm`, and its preview storage key.
Existing view IDs and document IDs retain their names too.
Local folder names can differ from remote repository names.
Keep existing remote URLs when a local checkout moves.
Set `RUNESTONE_ROOT` when a plugin's packager needs a different host checkout.
The [plugin package reference](plugins.md) explains packaging and installation.
+88 -532
View File
@@ -1,563 +1,119 @@
# Plugins
# Install and manage plugins
[Back to development](development.md)
[RuneStone](../README.md) · [User guide](user-guide.md)
RuneStone installs JavaScript plugins from local ZIP files and experimental Gitea release downloads.
Open Settings → Plug-ins to install, enable, disable, or uninstall them.
See [plugin names and source folders](plugin-names.md) for display names, stable IDs, and checkout locations.
Terminal and Table Formulas use the same installed package system as all other plugins.
## Build and install the feature packages
1. Clone `RuneStone_Table_Formulas` beside RuneStone and run `pnpm install --frozen-lockfile` in that checkout.
2. Run `pnpm build:plugins` from the RuneStone repository root for Table Formulas.
3. In Settings → Plug-ins, choose Install plugin ZIP.
4. Select the ZIP files in `../RuneStone_Table_Formulas/releases/`, then choose Install and enable.
The build creates `runestone.table-formulas-<version>.zip` in that plugin's `releases/` folder.
Table Formulas is a development package in its [own repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_TableFormulas).
Set `RUNESTONE_TABLE_FORMULAS_ROOT` to use a different checkout location.
That repository also supports `pnpm package:plugin`, with `RUNESTONE_ROOT` selecting the host packager.
The folders beside them contain build output for inspection and tests.
Use the ZIP files for installation and releases.
Terminal development lives in the separate [RuneStone_Terminal repository](https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal).
In that repository, run `pnpm install --frozen-lockfile`, then `pnpm build`.
Install `releases/runestone.terminal-<version>.zip` through the same plugin ZIP installer.
The local source folder is `../RuneStone_Terminal/` when both repositories share a parent directory.
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 select the new ZIP through Install plugin ZIP.
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.
Plugins add optional features such as Terminal, Table Formulas, Git, and PDF Viewer.
Use **Settings → Plug-ins** to install, update, enable, disable, or uninstall them.
The Browser is included with RuneStone and needs no plugin.
## Install a plugin
1. In Settings → Plug-ins, choose Install plugin ZIP.
2. Select one or more `.zip` files, then review the packages.
3. Choose Install to keep them disabled, or Install and enable to run them.
Get the plugin's release ZIP. Keep the file compressed.
Each ZIP installs one plugin. You can select up to 100 ZIPs at once.
Each ZIP contains one plugin, with `plugin.json` at its root.
You can open the ZIP with an archive tool to read its manifest, JavaScript, and other files.
You do not need to extract it before installation.
The picker accepts at most 100 ZIP files at once.
Folders and loose `plugin.json` files are not installation inputs.
1. Open **Settings → Plug-ins**.
2. Choose **Install plugin ZIP**.
3. Select the ZIP files.
4. Review each plugin's name, author, version, source, destination, and access level.
5. Choose **Install and enable** to use the plugins, or **Install** to keep them disabled.
Earlier `.runestone-plugin` files already used ZIP format. Rename those files to `.zip` before installation.
Installed plugins keep working. This change does not alter their files or saved settings.
For example, a Terminal package uses the filename `runestone.terminal-<version>.zip`.
The version in the filename identifies the release. Select the actual ZIP you received.
Use the same steps for other plugins.
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.
Plugins run with RuneStone's application access. Enable only code you trust.
The author field does not prove the publisher's identity. Plugins have no permission sandbox.
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.
RuneStone copies the packages into its application data folder. It keeps your downloaded ZIPs unchanged.
The review and installation steps do not run plugin code or installation scripts.
Each package succeeds or fails separately. Check the result for any failed packages.
A package with an installed ID updates that plugin after review. Choose Apply packages to replace its files.
The review shows the current and new versions. Updates keep plugin settings and the previous enabled state.
RuneStone stops the plugin in every window and waits for cleanup before replacement. Cleanup failure blocks replacement.
An interrupted update restores the old package unless the new catalog entry committed.
Automatic repository scans remain future work.
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.
## Enable or disable a plugin
Try the example with `pnpm package:plugin fixtures/plugins/workspace-overview`.
Install the resulting ZIP from `releases/`, then choose Install and enable.
Use Open tab or view beside New tab to open Workspace overview.
Use Commands in the toolbar to run Show workspace overview.
Use the switch beside the plugin in **Settings → Plug-ins**.
The **Enabled** or **Disabled** status shows your choice.
That choice applies across RuneStone windows and persists after restart.
No optional plugin starts automatically in a fresh installation.
## Uninstall with one confirmation
Disabling stops the plugin and keeps its installed files, settings, and workspace documents.
If RuneStone asks for a restart, close all RuneStone windows and open the app again.
Some loaded code can remain in memory until the app closes.
1. Choose Uninstall on the plugin's row.
2. Check its name, author, version, folder, and deletion message, then choose Uninstall and delete files.
## Update a plugin
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.
1. Get the new release ZIP for the plugin.
2. Open **Settings → Plug-ins → Install plugin ZIP**.
3. Select the ZIP.
4. Review the current and new versions.
5. Choose **Apply packages**.
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.
RuneStone recognizes an update by the plugin ID.
Updates keep the plugin's settings and its previous enabled or disabled state.
RuneStone stops the plugin in every window before replacing its files.
If cleanup fails, the update stops. Restart RuneStone before you try again.
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.
## Uninstall a plugin
```mermaid
flowchart LR
installed("Installed plugin") --> confirm("Confirm file deletion")
confirm --> cleanup("Stop in all windows")
cleanup --> removed("Delete package; retain data")
```
1. Open **Settings → Plug-ins**.
2. Choose **Uninstall** beside the plugin.
3. Check the plugin details and deletion message.
4. Choose **Uninstall and delete files**.
## Storage and recovery
Uninstall removes the installed package after the plugin stops in every window.
It keeps downloaded ZIPs, plugin settings, generated data, and workspace documents.
For example, Table Formulas leaves formula source in your Markdown files.
Installing the plugin again can reuse its retained settings, but you must choose whether to enable it.
RuneStone resolves the root through Tauri's `app_data_dir()`. Settings shows the complete path.
**Cancel** leaves the plugin unchanged. **Disable instead** stops it and keeps the package installed.
If RuneStone asks for a restart, close all RuneStone windows and open the app again.
```text
<application-data>/
plugins/<plugin-id>/
plugin.json
main.js
assets/
plugin-data/<plugin-id>/settings.json
plugin-state.json
plugin-staging/
plugin-removals/
```
## Install from a Gitea link (experimental)
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.
Use this route when the publisher supplies a Gitea repository link with a plugin ZIP attached to a release.
GitHub and GitLab links are not supported.
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.
1. Open **Settings → Plug-ins → Install from Git link**.
2. Enter the repository root link supplied by the publisher.
3. Enter a specific release tag, or leave it empty for the latest stable release.
4. For a private repository, enter a Gitea token with repository read access.
5. Choose **Review release**.
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.
An untracked destination blocks publication. Reviewed updates pin the installed package hash and retain a recovery journal.
A crash cannot enable a partial installation.
Review the package, then choose **Install** or **Install and enable**.
For an existing plugin, choose **Apply packages**.
Use an explicit tag for a prerelease. A source archive or branch link cannot install a plugin.
The release must contain exactly one attached plugin ZIP.
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.
Use HTTPS for a remote server. RuneStone clears the token after the request and does not save it.
RuneStone downloads a package through this route. It does not clone or build the repository.
## Package contract
## Feature guides
Place `plugin.json` at the root of the ZIP archive:
Use these guides for plugin features after installation:
```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"
}
```
- [Terminal sessions and shortcuts](guides/terminal.md)
- [Git controls, push, pull, and history](../../RuneStone_Git/docs/usage.md)
- [Background Slideshow images and board targets](../../RuneStone_Background_Slideshow/docs/usage.md)
- [Local Autocomplete trial and settings](../../RuneStone_Local_Autocomplete/docs/trial-guide.md)
- [Project Management tasks and boards](../../RuneStone_Project_Management/project-management.md)
The package API is version 1. Its interface lives in `src/lib/plugins/sdk.ts`.
RuneStone 0.1.5 adds optional `placement: "editor"` for views that belong beside documents.
These views open in the editor area with a tab. Document tabs retain their buffers when users switch views.
Closing the plugin tab or disabling the package disposes the view.
The default placement is `"dialog"`, so existing packages keep their current behavior.
Older hosts ignore the placement field. Plugins that require editor placement need RuneStone 0.1.5 or later.
All packages use one API and the same installation, enable, disable, and removal lifecycle.
Versions use three numeric parts with an optional lowercase hotfix suffix, such as `0.2.28a`.
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.
Links outside this repository require the corresponding sibling source checkout.
For the included browser, use the [built-in browser guide](user-guide.md#use-the-built-in-browser).
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.
## Plugin help
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.
## Versioning for plugin authors and agents
Follow the shared [RuneStone versioning policy](../AGENTS.md#versioning). RuneStone and its plugins keep independent version numbers under this policy.
Use `zz.yy.xx` and keep routine implementation work in the current `zz.yy` series.
| Part | When to increase it |
| Problem | Action |
| --- | --- |
| `xx` | Each new completed regular plugin ZIP build. Hotfixes increase the letter suffix. |
| `yy` | A deliberate release ready for build testing, with user direction. Reset `xx` to zero. |
| `zz` | A full release, with user direction. Reset `yy` and `xx` to zero. |
Keep the current version during source edits, fixes, improvements, documentation work, and automated checks.
Set the next version when producing the ZIP. Intermediate compilation output does not count as a new build.
If no build completes, restore the previous version fields. Failed attempts and retries do not consume version numbers.
Report a new version as available only after its ZIP exists. Publishing an existing artifact does not increase its version.
Passing automated checks alone does not authorize a `yy` or `zz` increase.
A hotfix fixes one item or a narrowly scoped problem in an existing release.
Use letters in the actual package version: `0.2.28` → `0.2.28a` → `0.2.28b`.
Keep the numeric base for hotfix builds.
Advance hotfix suffixes in this order: `a`, `b`, `c`, through `z`, then `aa`, `ab`, and later suffixes.
The next regular build increases `xx` and removes the suffix: `0.2.28b` → `0.2.29`.
Keep the package version, manifest version, build metadata, ZIP name, release notes, and tag consistent.
For example, package version `0.2.28a` produces `runestone.pm-0.2.28a.zip` and uses tag `v0.2.28a`.
The shared packager and updated native installer accept these suffixes. Older hosts with numeric-only validation reject suffixed packages.
Do not substitute a numeric increment for a hotfix. Add suffix support or report a format blocker before building.
Do not bypass validation or overwrite an existing release ZIP.
## Build and release a plugin
Use the same package contract for in-house and community plugins.
The ZIP is the release file. Its `plugin.json` describes the contents and is not a separate installer.
```text
org.example.hello-1.0.0.zip
plugin.json
main.js
assets/
README.md
LICENSE
```
The manifest and entry module are required. Assets, a README, and a license are optional package files.
Include a README with the host requirement, purpose, install steps, and help contact.
Keep JavaScript readable where practical. Avoid minification and obfuscation that make inspection harder.
1. Compile the plugin into a clean folder with `plugin.json`, its entry module, and the required assets.
2. Run `pnpm package:plugin <compiled-folder> [output-folder]` from the RuneStone repository.
3. Install the resulting ZIP in RuneStone and test its features, disable action, and uninstall action.
4. Share that same ZIP as the release file.
Use Node.js 24 or later for the packaging command. The default output folder is `releases/` in the project that contains the compiled folder.
Keep plugin release ZIPs in that plugin project, including when the host calls the build.
Explicit output folders are for temporary checks or staging. Move completed releases into the owning project's `releases/` folder.
It checks the manifest, paths, entry module, and size limits before it writes `<id>-<version>.zip`.
It includes every file in the input folder. Keep dependencies, credentials, and unrelated build files outside that folder.
The output folder must be outside the input folder.
The command can replace an existing ZIP with the same ID and version. Use the next build version and preserve existing ZIPs.
Repeated runs with unchanged input produce the same archive bytes.
The native installer checks the package again before installation.
Other build tools can create the same ZIP layout. Do not add a parent folder above `plugin.json`.
Do not tell users to load JSON, select a build folder, rename a new release, or install dependencies.
Authors in other repositories can run `node <RuneStone-path>/scripts/packagePlugin.mjs <compiled-folder> <output-folder>`.
## Experimental installation from a Gitea link
Gitea repository links now supply ZIP packages to the existing review and installation flow.
This trial supports Gitea at the host root, including the personal Gitea server.
GitHub and GitLab support remain future work. Their release APIs need separate tests.
1. In Settings → Plug-ins, choose Install from Git link.
2. Enter the repository root link, such as `https://git.knottywyvern.com/kwyvern-gitea/RuneStone_Terminal`.
3. Enter a release tag for a specific version, or leave it empty for the latest release.
4. For a private repository, enter a Gitea access token with repository read access.
5. Choose Review release, then choose Install or Install and enable after you review the package.
The link can end in `.git`. SSH links, branch links, source archives, and links with credentials are not installation inputs.
Use an explicit tag for a prerelease trial. The [Gitea latest-release endpoint](https://docs.gitea.com/api/operations/repo-get-latest-release/) excludes drafts and prereleases.
RuneStone clears the token after each request and when the form closes. It does not save the token.
Use HTTPS. HTTP is available for trusted local servers, but it sends the token and package without encryption.
Credentials go only to the original API origin. Redirects to another origin do not receive the token.
A release attachment on another private host needs its own access method and is outside this trial.
The downloader reads release metadata, then downloads one attached ZIP.
It does not clone the repository, compile code, install dependencies, or run scripts.
Downloads have size limits, time limits, and a redirect limit.
The metadata limit is 2 MiB. The compressed ZIP limit is 100 MiB.
The existing package limits still apply to the extracted files.
HTTPS links cannot redirect or select an attachment over HTTP.
The review shows the repository, release tag, attachment link, manifest, and destination.
It pins the downloaded content. Installation checks that the staged files still match the reviewed hash.
Changing a remote release after review does not change the pending installation.
The same duplicate-ID, enable, removal, and cleanup rules apply to local and remote packages.
### Release standard for plugin writers and agents
Apply the [shared versioning rules](#versioning-for-plugin-authors-and-agents) before choosing a release version.
Use one plugin repository and one standard plugin ZIP per release for this trial.
Keep the package contract above. No repository manifest or special branch layout is required.
1. Build the plugin from the source commit that you intend to tag.
2. Run `pnpm package:plugin <compiled-folder> [output-folder]` from RuneStone.
3. Attach the resulting `<id>-<version>.zip` to a Gitea release.
4. Publish the release with a tag that identifies its source commit.
5. Test its repository link and explicit tag in RuneStone.
Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases.
Keep the manifest version and package version equal. Keep published release files unchanged.
Increase the version when building a new ZIP, before publication.
Prerelease builds follow the same version policy. Each new regular ZIP gets the next numeric build version.
Each hotfix ZIP gets the next letter suffix. Use an explicit trial tag for prereleases.
The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies.
Do not attach a source ZIP as the plugin package. Gitea's automatic source archives do not count as release attachments.
The installer rejects releases with no attached ZIP or more than one attached ZIP.
Other attachments, such as checksums and release notes, can accompany the single ZIP.
The installer rejects drafts. Private repositories require read access to the metadata and attachment.
Test local ZIP installation before publication. After publication, test download, review, disabled installation, enable, disable, and removal.
Check that cancellation leaves no installed package. Check that an existing plugin ID blocks another installation.
Keep release notes short. State the host requirement, plugin version, changes, and known limits.
### Trial checks
The four local packages passed a simulated Gitea release download and isolated native installation on October 5, 2026.
The test checked the installed hashes and kept all four plugins disabled.
| Plugin | Package version |
| --- | --- |
| Terminal | 0.1.0 |
| Table Formulas | 0.1.0 |
| PDF Viewer | 0.0.1 |
| Project management | 0.2.3 |
The authenticated check of the personal Gitea server found no releases in these four repositories.
Live Gitea installation still needs published release attachments. No releases or tags were created during this check.
The browser smoke test covers the link form, download errors, token clearing, cancellation, focus, and disabled installation.
Native tests cover URL parsing, release selection, redirects, credential boundaries, size limits, changed staging files, and invalid ZIPs.
Run the focused native checks with `cargo test --manifest-path src-tauri/Cargo.toml --lib plugin`.
To repeat the four-package trial, place exactly these four ZIPs in a folder and set `RUNESTONE_GIT_TRIAL_PACKAGES` to its absolute path.
Then run `cargo test --manifest-path src-tauri/Cargo.toml --lib four_plugin_release_trial -- --ignored --nocapture`.
Run `node scripts/pluginInstall.smoke.mjs` against the development server for the browser checks.
## Plugin API
The current source adds an optional [completion API](completion.md) for local model providers and plugin-owned text fields.
This capability is not present in the existing 0.1.7 installer.
The entry exports `activate(api)`. Activation can return a cleanup function or a promise for that function.
The 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 Commands in the toolbar |
| `registerCommand({ category: "open", ... })` | Add a launch action to Open tab or view |
| `registerView({ id, title, placement?, mount })` | Add a view in a dialog or the editor area |
| `registerView({ settings: true, ... })` | Add a configuration page to Settings |
| `registerView({ launcher: false, ... })` | Keep a dynamic view out of the launch menu |
| `registerView({ navigation: true, icon?, ... })` | Add an icon button to the ribbon left of the navigation pane |
| `registerDocumentType(type)` | Recognize document content, supply a navigation icon, and mount a document editor |
| `openDocument(path)` | Open a recognized document in its own tab |
| `renameDocument({ id, path }, name)` | Rename a recognized document and return its new workspace path. Optional API |
| `openView(id)` | Open one of the plugin's registered views |
| `openView(id, { split, relativeTo })` | Open an editor view beside another view. `split` accepts `right` or `down` |
| `closeView(id)` | Close an editor view owned by this plugin. Optional API |
| `registerView({ tabActions, find, pinned, ... })` | Supply tab actions, a Find handler, and the initial pin state |
| `registerView({ tabDragData, ... })` | Supply transfer data for a tab. The callback receives its pin state |
| `registerTabDrop(receive)` | Accept a tab from another window. Optional API |
| `onDispose(callback)` | Register synchronous or asynchronous cleanup |
| `workspace.list(path?)` | List a directory in this window's active workspace |
| `workspace.listMarkdown()` | Return sorted visible Markdown paths in one native request. Optional API |
| `workspace.read(path)` | Read a workspace text file |
| `workspace.readMany(paths)` | Optional batched text read. Accept at most 64 paths and return a source or error for each path |
| `workspace.readBytes(path)` | Read workspace bytes as a Uint8Array, with a 64 MiB limit. Requires the binary document host update |
| `workspace.readOptional(path)` | Read text, or return null when the file is absent. Added in 0.1.6 |
| `workspace.create(path, contents)` | Create complete text without replacing an existing file. Added in 0.1.6 |
| `workspace.write(path, contents, expected)` | Save only if the file still matches the original text |
| `workspace.subscribe(listener)` | Receive workspace change notifications. Returns a cleanup function |
| `settings.read()` / `settings.write(value)` | Read or write retained JSON settings, with a 1 MiB limit |
| `settings.subscribe(listener)` | Receive saved settings changes across windows. Optional API |
| `assets.read(path)` | Read package bytes as a `Uint8Array` |
Check for `workspace.readMany` before calling it. Older hosts require individual reads.
Each result contains `path` and either `source` or `error`. One failed file does not discard the remaining results.
The native batch accepts at most 64 paths and 16 MiB of combined UTF-8 text.
Workspace path checks and plugin shutdown checks apply to these reads.
Command and view IDs must be unique within their respective plugin collections.
Plugin commands can supply an optional `icon` from the shared action icon set in `src/lib/ui/actionIcons.ts`.
Use a recognizable action icon, such as `skip-forward` or `pause`, for each command. Older hosts can ignore this field.
Sidebar views belong in the left navigation. Views with a direct navigation button do not repeat in the plugin launch menu.
Plugin configuration appears in Settings under the plugin name.
Register a view with `settings: true` to add its configuration page.
The host mounts that view inside Settings and removes it from the launch menu.
Settings loads enabled plugins so their configuration pages remain available in the separate settings window.
The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`.
Older hosts can omit the context argument.
The language setting applies to RuneStone's interface. The host does not translate plugin interfaces or supply a plugin translation API.
Plugin authors can manage translations within their own packages.
Local Autocomplete keeps temporary reference text in its editor view because that text belongs to one window.
Open Commands → Configure Local Autocomplete in that window to use reference text.
The Open tab or view menu contains plugin views and commands with `category: "open"`.
Other commands appear in Commands.
Set `launcher: false` on dynamic views that already have tabs.
Existing packages can omit these optional fields.
Plugins can call `settings.subscribe(listener)` to receive notifications when their saved settings change.
The listener must read the new settings with `settings.read()`.
Notifications cross window boundaries and contain only the plugin ID.
The host removes subscriptions when the plugin stops.
Plugins must ignore pending reads after shutdown and prevent older reads from replacing newer settings.
Local Autocomplete uses this subscription so changes in Settings apply to the editor window.
Document type IDs must also be unique within their collection.
Document types declare file extensions, an `identify` function, and a `mount` function.
The identify function returns a stable document ID or null. Invalid documents remain available through the text editor.
An optional creation action supplies complete file text. Creation never replaces an existing file.
Each document opens in its own editor tab. Opening the same document focuses its existing tab.
Closing one tab disposes only that mount. Disabling the plugin disposes all its mounts and removes its navigation entries.
The host rejects plugin writes when a note has unsaved editor changes.
These document APIs require the current host source. The earlier 0.1.6 installer does not include them.
The optional API method `renameDocument({ id, path }, name)` renames a recognized document and returns its new workspace path.
The host checks the document ID and plugin owner. It keeps the folder and extension, rejects name collisions, and updates open tabs.
Names can contain dots. Hidden names and reserved filename characters are invalid.
Unsaved text edits block plugin renames. This method requires the updated host source.
Binary document types set `content: "binary"`. Text remains the default.
For binary types, `identify(path, source)` receives an empty source string and recognizes the path without reading its contents.
The mount reads bytes with `workspace.readBytes(path)` and reports invalid document data in its own view.
This avoids UTF-8 conversion and full file reads while the file tree identifies binary documents.
The native read command checks the active window's workspace boundary and rejects directories and files larger than 64 MiB.
Binary document support requires the updated host source. The earlier 0.1.6 installer does not include it.
Check for `api.workspace.readBytes` during activation and report a clear host update error when it is absent.
Navigation views with `placement: "sidebar"` appear beside Files, Search, and Bookmarks in the top header.
Other navigation views appear as icon buttons in the ribbon left of the navigation pane.
The optional view `icon` accepts `list`, `kanban`, or `puzzle`. The default is `puzzle`.
Buttons show the view title in a tooltip on hover and keyboard focus.
The ribbon remains available when the navigation pane is closed.
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 |
| `../RuneStone_Terminal/src/` | Terminal plugin source in its own repository |
| `../RuneStone_Table_Formulas/` | Table Formulas source, unit tests, and package build |
| `scripts/buildPlugins.mjs` | Table Formulas compilation and ZIP release in `../RuneStone_Table_Formulas/releases/` |
| `scripts/packagePlugin.mjs` | Shared checks and ZIP creation for plugin authors |
Run `pnpm build:plugins`, `pnpm check`, `pnpm test`, `pnpm build`, and `cargo test --manifest-path src-tauri/Cargo.toml --lib --offline`.
Run `pnpm check`, `pnpm test`, and `pnpm build` in `RuneStone_Terminal` for terminal checks.
Build Terminal before host browser tests. They read `../RuneStone_Terminal/dist/` by default.
Set `RUNESTONE_TERMINAL_DIST` to use another compiled terminal folder.
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.
## Built-in browser
Browser now belongs to RuneStone. The installer includes its interface and native Chromium runtime.
Users can open browser tabs, manage profiles in Settings, and use web bookmarks without a plugin ZIP.
The existing browser data directory stays the same. Profiles, bookmarks, cookies, and settings remain available.
An old Browser package can be removed from Settings. The host does not load it alongside the built-in browser.
The interface source lives in `src/lib/browser/`. The runtime source lives in `browser-runtime/`.
Run `pnpm browser:stage` after packaging that runtime and before creating an installer.
The main Tauri configuration includes `src-tauri/browser-engine/` as an installer resource.
Browser startup obtains a session token for its window. Native requests check that token, and cleanup revokes it.
## Git and sidebar views
The Git plugin adds source control to the left pane. It supports file diffs, staging, unstaging, commits, and line history.
Git must be installed, and the workspace must be the repository root. Linked worktrees are not supported yet.
Commit hooks still run. A failed commit keeps the message and shows the error.
Plugins can register `placement: "sidebar"` views with a navigation icon.
The optional `openFile(path)` method opens a workspace file.
The optional `git` API supplies status, diff, stage, unstage, commit, and blame operations.
The optional `replaceView(currentId, nextId)` method changes the current tab while preserving its position and pin state.
For document tabs, `replaceDocumentWithView(document, nextId)` supplies the same behavior.
Both methods restrict the source and destination to the calling plugin.
The Git plugin also supports push, fast-forward-only pull, and a collapsible graph of the latest 100 commits.
Changes and Graph collapse independently. The graph shows branches, tags, commit IDs, authors, dates, and commit messages.
Push and pull use the current branch's configured upstream and existing Git authentication.
Pull stops when local changes or diverging commits prevent a fast-forward update. The plugin does not force-push or create an upstream automatically.
The optional Git API adds `push()`, `pull()`, and `graph()` in the current host source.
These methods require an updated host and remain subject to plugin shutdown checks.
The Git graph uses graphical commit nodes and parent links. It shows forks, merges, branches, tags, commit IDs, authors, dates, and messages.
The host returns structured history from `git.graph()`: `{ commits: [{ id, parents, refs, summary, author, date }] }`.
The graph keeps the latest 100 commits. Dashed links mark parents outside that history.
The updated Git package requires the matching host build. An older host shows an update message instead of a graph.
## Temporary background API
RuneStone 0.1.25 adds optional `api.backgrounds` with `version: 1`.
Background Slideshow uses it for local image folders and temporary backgrounds.
Project Management 0.2.29 uses it for board backgrounds.
| Method | Contract |
| --- | --- |
| `chooseFolder()` | Open the native folder picker. Return an absolute path or null on cancellation. |
| `defaultFolder()` | Optional. Create and return Pictures/RuneStone Backgrounds for new settings. |
| `list(folder)` | List PNG, JPEG, GIF, and WebP filenames directly inside the folder. |
| `read(folder, name)` | Read one raster image as bytes, with a 50 MiB limit. |
| `set(target, frame)` | Apply a temporary frame. Pass null to remove this plugin's frame. |
| `get(target)` | Read the active frame or null. |
| `subscribe(listener)` | Receive the changed target. Return a cleanup function. |
Targets are `app`, `pm-all`, and `pm-board:<board UUID>`.
A frame contains `url`, `overlay`, `position`, and `size`.
It can also contain `previous` with those four fields and `transitionMs` from 0 to 5000.
Renderers fade between these frames unless reduced motion is active. Keep both blob URLs valid until replacement or cleanup.
Use a blob URL. The publishing plugin owns the URL and must release it after replacement or cleanup.
Overlay ranges from -1 to 1. Negative values lighten the image, and positive values darken it.
Position and size use the same choices as custom image settings.
Frames belong to the plugin activation in the current window. They do not change saved background settings.
The last published frame wins. Removing it reveals an earlier active frame or the saved background.
Project Management checks a temporary board frame first, then `pm-all`, then the saved board image.
Disable removes the plugin's frames and subscriptions before cleanup.
File access requires an active plugin lease. Pending reads fail after access is revoked.
Image reads reject path traversal, linked files, unsupported formats, and oversized files.
Each window keeps its own sequence. The plugin settings API shares folder and playback settings across windows.
### Per-image background settings
Slideshow stores per-image fit, position, and overlay in .runestone-backgrounds.json beside the images. The sidecar uses schema 1 and an images object. Settings saves compare the previous file text to preserve external changes. The sidecar has a 1 MiB limit.
Portrait images show the full image over a blurred cover layer by default. Each target scales the foreground and blurred layer separately. The image editor shows a preview and lets users save or reset an override. Global settings remain the fallback for other images.
The optional background API adds readImageSettings and writeImageSettings. Temporary frames can supply blurredUrl. The plugin owns all frame URLs and releases them after replacement or shutdown.
### View launch defaults
Views can supply an optional `launch()` handler for entry through the plugin launcher or navigation button.
The handler can select a default view with `api.openView(id)`.
Explicit `api.openView` calls and restored tabs bypass the launch handler and retain their targets.
Views without a handler open as before. Older hosts ignore this optional field.
Project Management uses this handler for its fixed workspace default board.
| The ZIP fails review | Read the reported error. Get a complete release ZIP from the plugin author. |
| You received source code or a loose manifest | Get the release ZIP. Users do not need to build the plugin. |
| The plugin is installed but unavailable | Check its switch and any error beside it in **Settings → Plug-ins**. |
| Changed plugin files need another enable decision | Review the changed package before enabling it again. |
| An update or uninstall reports a cleanup failure | Restart RuneStone, then repeat the action. |
| The plugin shows **Removal incomplete** | Choose **Retry cleanup** to finish the confirmed removal. |
| Retry cleanup reports changed files | Check the path in the error before retrying. |
| A Gitea release has no usable package | Check the release tag and ask the publisher for a release with one attached plugin ZIP. |
Use **Show files** beside a plugin to inspect its installed folder.
Include the plugin name, version, RuneStone version, and error text when you report a problem.
To create a plugin, use the [plugin development reference](plugin-development.md).
It covers build examples, package requirements, releases, and the API.
-122
View File
@@ -1,122 +0,0 @@
# Product scope
[Back to RuneStone](../README.md)
This reference preserves intended capabilities and design constraints. Some features already exist.
See the [interface design reference](ui-design.md) for shared controls, dimensions, and visual checks.
See the [roadmap](roadmap.md) for goals and milestones, and the [user guide](user-guide.md) for current behavior and limitations.
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.
- 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, 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
- Use one editor engine for notes and code.
- Switch chrome between Writer and IDE. Autodetect from the file type. Allow a per-file override.
- Writer chrome uses wrapped text, a document preview, and image hover previews.
- IDE chrome uses line numbers, a minimap, and a terminal dock.
- Left-click a file in the navigation pane to open it in the current tab; middle-click to open it in a new tab. Tabs with unsaved edits stay open. Already-open files select their existing tab. Close a tab with the close control or the middle mouse button.
- Support Markdown, Python, JavaScript, TypeScript, JSON, YAML, TOML, and shell at first.
- Parse CommonMark, GFM tasks and tables, YAML frontmatter, wiki links, and tags.
## Navigator
- Show a left activity bar with Files, Search, and Bookmarks.
- Click the active item again to hide the sidebar.
- Right-click empty space to create a folder or a note.
- Right-click a file for copy, bookmark, path copy, reveal, pin, rename, and delete.
- Drag files and folders to move them or to set display order.
- Save display order. Do not reorder inodes for sort.
- Show a ribbon with new file, new folder, sort, and collapse all or expand all.
## Panes
- Show an outline of headings and symbols on the right. Allow collapse.
- Show a minimap of the open buffer.
- Open a terminal whose working directory is the workspace root.
- Allow more than one terminal. Add a session and kill that session from a rail on the right of the dock.
- Show a document preview that renders Markdown images.
## 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 standard ZIP packages and stores copies in the application data directory.
Experimental Gitea repository links download one release ZIP into the same review flow.
Local trials passed with four plugin packages. Live Gitea testing still needs published releases.
GitHub and GitLab support remain future work.
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
- [x] Standardize plugin releases and installation on readable ZIP packages.
- [x] Add experimental Gitea release downloads and test the four plugin packages locally.
- [ ] Complete the live Gitea release trial.
- [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.
- [x] Add one Project Management plugin with connected Kanban, Gantt, and Calendar views.
- [ ] Add a virtual tabletop system plugin.
Keep basic Markdown table editing and rendering in the core. Users must retain access to workspace files when plugins are disabled.
Kanban, Gantt, and Calendar belong to one optional Project Management package with shared items.
The Project Management plugin has a separate development project. See its [design and scope](../../RuneStone_Project_Management/project-management.md).
### Planned plugin lineup
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.
- Git. Status, stage, commit, pull, push, log, and diff. Use the system `git` binary.
- Sort. Per-folder order, pin, and hide. Flexplorer is a reference for behavior, not a source of code.
Planned plugins disabled by default:
- Project Management. Connected Kanban, Gantt, and Calendar views within one package.
- Virtual tabletop. Tools for tabletop play within the workspace.
- Graph. Draw wiki-link edges from the file index.
- Canvas. Store `.canvas` files in JSON Canvas 1.0.
- Browser. Open a page in an in-app webview. Block ads with EasyList and EasyPrivacy.
## Later work
- Background Git for people who do not want to run Git by hand. Timed commit, pull, and push. A history limit is not designed yet.
- Extend the existing live Markdown preview. See the [user guide](user-guide.md) for current behavior.
- Language servers for diagnostics and go-to-definition.
- Wiki-link jump and backlinks from a rebuildable index.
- A command palette for every command.
## Out of scope
- A plugin marketplace
- Obsidian or VS Code plugin compatibility
- Cloud sync, live collaboration, or mobile
- A debugger or a full IDE
- Auto-commit on save
## Architecture goals
Dark is the primary theme.
Privileged operations belong in Rust: disk access, file watching, search, Git, terminal sessions, and adblock matching.
Git, terminal sessions, spreadsheet operations, and adblock matching belong to planned plugins.
-63
View File
@@ -1,63 +0,0 @@
# Product roadmap
[Back to RuneStone](../README.md)
**Goal:** Make RuneStone a dependable place to write, understand, and run a project
while keeping its files portable and under the user's control.
## Direction
This is a proposed progression from the existing editor to a broader workspace.
No release dates are assigned.
```mermaid
flowchart LR
accTitle: RuneStone product direction
accDescr: First make daily work dependable, then help users understand connected projects, then let users choose optional workflows.
daily("1. Trust daily work<br/>Write, run, and resume")
understand("2. Understand the project<br/>Follow ideas and code")
adapt("3. Choose your workflow<br/>Add only the tools you need")
daily --> understand --> adapt
```
## 1. Trust daily work
**Objective:** Make RuneStone dependable enough to serve as the everyday home for notes and scripts.
The current editor, local files, autosave, and terminals provide the foundation.
Session restoration and crash recovery would let users resume work after an interruption.
**Milestone:** A user can write a note, run its companion script, restart the app,
and resume the workspace with recoverable edits.
## 2. Understand the project
**Objective:** Help users move from a question to the related notes and code without losing context.
Reliable note links and backlinks would connect explanations.
Code navigation and diagnostics would help users understand the scripts those explanations describe.
**Milestone:** A user can follow a note to related material, locate a code definition,
and identify a reported code problem within the workspace.
## 3. Choose your workflow
**Objective:** Support different ways of working while keeping the core editor simple.
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.
Project Management plugin planning lives in the separate [Project Management roadmap](../../RuneStone_Project_Management/roadmap.md).
## Why this order?
Reliable daily work establishes trust. Better navigation then helps users understand larger projects.
Optional workflows build on that foundation while preserving a focused core.
Detailed capabilities and boundaries live in the [product scope](product-scope.md).
The [user guide](user-guide.md) describes what works today.
+28 -4
View File
@@ -12,6 +12,7 @@ Check its release notes if a control is missing.
| Work with images, diagrams, or tables | [Document tools](guides/document-tools.md) |
| Save a reusable note | [Templates](#use-note-templates) |
| Change colors | [Appearance](guides/themes.md) |
| Browse websites and manage browser profiles | [Built-in browser](#use-the-built-in-browser) |
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
| Resolve a changed or missing file | [File conflicts](#resolve-file-conflicts) |
@@ -51,11 +52,19 @@ Writer edits preserve Markdown source, frontmatter, and Windows line endings.
Read displays frontmatter in a collapsed Properties section.
Ctrl+click opens links in Writer and IDE mode. Workspace file links open a tab and retain the source document.
Links to document sections scroll to the heading in Writer, IDE, Read, and Split views.
Use a Markdown heading fragment, such as `#install-and-start`, after the file path or by itself for the current document.
Read mode follows links with an ordinary click. Wiki links, note callouts, and Mermaid diagrams work in document views.
Wiki links resolve note names across the workspace. Use a relative or workspace path when names repeat.
The Backlinks section below the outline lists notes that link to the current note. Select an entry to open its source.
Collapse the section to hide it. Use Rebuild note index to scan the workspace again.
The index follows note changes and link edits. Markdown files remain readable without the index.
Code blocks remain editable on the first click. Their Copy code button copies the body without the Markdown fences.
Click the note title in Writer to rename its file. Enter or leaving the field saves the name, and Escape cancels.
The rename keeps the folder, Markdown extension, contents, and editing history.
Press F2 in the file navigator to rename an item. File names select the stem and keep the extension outside the selection.
Folder names select the complete name.
### Format text
@@ -93,9 +102,16 @@ Right-click a tab for Move tab left or Move tab right.
With a tab focused, Alt+Shift+Left or Alt+Shift+Right moves it. Arrow keys, Home, and End select tabs.
Drag a tab outside the tab strip to move it into a new window.
Drop a tab near another window's tab ribbon to add it at the end.
Drop over an existing tab to choose its position.
You can also right-click the tab and choose Open in new window.
RuneStone transfers the current buffer, including unsaved text. It closes the source tab after the new window accepts the transfer.
If the transfer fails or the source buffer changes before acceptance, the source tab remains open.
Move a plugin tab between existing windows of the same workspace, or tear it into a new window.
The source tab stays open if the destination cannot accept it or already contains the view.
A normal application restart restores document tabs in their saved order, with the active tab and pins.
Missing or renamed files do not block the remaining tabs. RuneStone reads document contents from disk.
## Save your work
@@ -105,7 +121,7 @@ Settings → General accepts an interval from 1 to 300 seconds or turns auto-sav
The interval changes when you leave the field. Restore defaults enables the five-second interval again.
Closing a dirty tab or desktop window asks before it discards edits or ends terminal sessions.
Open tabs and unsaved buffers do not restore after an application restart.
Unsaved buffers, terminal sessions, and plugin views without a document do not restore after restart. Crash recovery remains planned.
## Resolve file conflicts
@@ -135,6 +151,13 @@ No optional plugin starts automatically in a fresh installation. Enable choices
Disabling Terminal ends its sessions. Disabling Table Formulas preserves formulas and basic table editing.
Uninstall removes the installed package after confirmation and retains its settings and workspace documents.
## Use the built-in browser
The RuneStone installer includes the browser interface and its native Chromium runtime. No plugin ZIP is required.
Use **New browser tab** to open a browser tab. Manage profiles in Settings and use web bookmarks to return to saved sites.
The browser keeps the existing data directory, including profiles, bookmarks, cookies, and settings.
You can uninstall an old Browser package through **Settings → Plug-ins**. The host does not load it alongside the built-in browser.
## Keyboard reference
These are the Windows/Linux shortcuts. macOS desktop behavior still needs native tests.
@@ -156,10 +179,11 @@ The [Terminal guide](guides/terminal.md) lists plugin shortcuts.
Press F1 or use the question mark beside the workspace selector for Help and about.
It shows the app version, basic instructions, and shortcuts. Escape or the close button returns to the document.
Vault-wide wiki-link resolution, backlinks, and math rendering still need work.
Language servers, restricted plugin permissions, persistent tabs after restart, and crash recovery remain planned.
Math rendering still needs work.
Crash recovery and restricted plugin permissions remain planned.
Language-server support belongs to a future optional plugin because of its technical requirements.
Git controls are available through the optional Git plugin. Git is no longer only a planned feature.
Unsaved buffers and terminal sessions last only for the current application session.
For setup failures, use [installation help](installation.md#setup-help).
For installation and update steps, use the [installation guide](installation.md).
For a reproducible problem, record the app version, operating system, steps, expected result, and error text.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.42",
"version": "0.1.44",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
+90
View File
@@ -0,0 +1,90 @@
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
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 page = await browser.newPage({ viewport: { width: 720, height: 640 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const output = ".audit/backlinks";
await mkdir(output, { recursive: true });
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
<aside id="fixture" style="width:320px;height:500px;display:flex;flex-direction:column;background:var(--rs-bg-elevated);margin:24px"></aside>
<script type="module">
import '/src/app.css';
import {mount,unmount} from '/node_modules/.vite/deps/svelte.js';
import Backlinks from '/src/lib/layout/Backlinks.svelte';
import {applyAppearance} from '/src/lib/theme/appearance.ts';
let component;
window.renderBacklinks = async ({mode='dark',width=320,entries=[],busy=false,error=null}={}) => {
if(component) await unmount(component);
applyAppearance({theme:'default',mode});
document.querySelector('#fixture').style.width=width+'px';
component=mount(Backlinks,{target:document.querySelector('#fixture'),props:{entries,busy,error,onOpen:entry=>window.openedBacklink=entry,onRebuild:()=>window.rebuildCount=(window.rebuildCount||0)+1}});
};
await window.renderBacklinks();
window.backlinksReady=true;
</script></body></html>` }));
const entries = Array.from({ length: 28 }, (_, index) => ({
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
line: index + 3, from: index * 100, to: index * 100 + 10,
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
kind: "wiki", target: "Target",
}));
const measurements = [];
try {
await page.goto(`${process.env.SMOKE_URL || "http://127.0.0.1:1420"}/__backlinks__`);
await page.waitForFunction(() => window.backlinksReady);
const panel = page.getByRole("region", { name: "Backlinks", exact: true });
await panel.getByText("No other notes link to this file.").waitFor();
await page.screenshot({ path: `${output}/empty-dark.png` });
for (const mode of ["light", "dark"]) {
for (const width of [320, 180]) {
await page.evaluate(args => window.renderBacklinks(args), { mode, width, entries });
const toggle = panel.getByRole("button", { name: "Backlinks 28", exact: true });
await toggle.focus();
await page.keyboard.press("Enter");
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
assert.equal(await panel.locator(".source").first().isVisible(), false);
await page.keyboard.press("Space");
assert.equal(await toggle.getAttribute("aria-expanded"), "true");
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.ok(await page.evaluate(() => window.rebuildCount > 0));
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.openedBacklink.sourcePath), entries[0].sourcePath);
const metrics = await panel.evaluate(node => {
const source = node.querySelector(".source"), title = node.querySelector(".source-title"), content = node.querySelector(".content");
const style = getComputedStyle(source);
const color = value => value.match(/[\d.]+/g).slice(0, 3).map(Number);
const luminance = rgb => rgb.map(value => value / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126,.7152,.0722][index], 0);
const contrast = (a,b) => { const l1=luminance(color(a)),l2=luminance(color(b));return (Math.max(l1,l2)+.05)/(Math.min(l1,l2)+.05); };
const background = getComputedStyle(document.querySelector("#fixture")).backgroundColor;
return { text: style.color, accent: getComputedStyle(title).color, background,
textContrast: contrast(style.color,background), linkContrast:contrast(getComputedStyle(title).color,background),
width:node.clientWidth,scrollWidth:node.scrollWidth,scrollable:content.scrollHeight>content.clientHeight,
focusStyle:style.outlineStyle,focusColor:style.outlineColor,opacity:style.opacity };
});
assert.ok(metrics.textContrast >= 4.5, `Text contrast: ${mode} ${width}`);
assert.ok(metrics.linkContrast >= 4.5, `Link contrast: ${mode} ${width}`);
assert.ok(metrics.scrollWidth <= metrics.width, "The panel must not scroll horizontally");
assert.ok(metrics.scrollable, "Long lists must scroll inside the panel");
assert.equal(metrics.focusStyle, "solid");
assert.equal(metrics.opacity, "1");
measurements.push({ mode, width, ...metrics });
await page.screenshot({ path: `${output}/${mode}-${width}-focus.png` });
}
}
await page.evaluate(() => window.renderBacklinks({ busy:true, error:"Could not read one note. Rebuild the index to try again." }));
assert.equal(await panel.getByRole("button", { name:"Rebuild note index", exact:true }).isDisabled(), true);
await panel.getByText("Reading workspace links…").waitFor();
await page.screenshot({ path:`${output}/busy-error-dark.png` });
assert.deepEqual(errors, []);
await writeFile(`${output}/measurements.json`, JSON.stringify(measurements,null,2));
console.log("Backlinks smoke passed: themes, narrow panels, long lists, keyboard, empty, busy, error, and contrast.");
} finally { await browser.close(); }
+29
View File
@@ -0,0 +1,29 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentSessionKey, parseDocumentSession, restoreDocumentSession } from "../src/lib/workspace/documentSession.ts";
test("document sessions isolate workspaces and discard unsafe or duplicate paths", () => {
assert.notEqual(documentSessionKey("C:\\one"), documentSessionKey("C:\\two"));
assert.equal(parseDocumentSession("invalid"), null);
assert.equal(parseDocumentSession('{"version":2,"documents":[]}'), null);
assert.deepEqual(parseDocumentSession(JSON.stringify({ version: 1, activePath: "b.md", documents: [
{ path: "b.md", pinned: true, contents: "unsaved" }, { path: "a.md" }, { path: "b.md" },
{ path: "../outside.md" }, { path: "C:\\outside.md" }, { path: "empty:test" }, null,
] })), { version: 1, activePath: "b.md", documents: [{ path: "b.md", pinned: true }, { path: "a.md", pinned: false }] });
});
test("restoration keeps order and active tab when a missing file fails", async () => {
const opened: string[] = [];
const session = parseDocumentSession(JSON.stringify({ version: 1, activePath: "c.md",
documents: ["b.md", "missing.md", "c.md", "a.md"].map(path => ({ path })) }))!;
const active = await restoreDocumentSession(session, async item => {
if (item.path === "missing.md") throw new Error("Not found");
opened.push(item.path);
});
assert.deepEqual(opened, ["b.md", "c.md", "a.md"]);
assert.equal(active, "c.md");
assert.equal(await restoreDocumentSession({ ...session, activePath: "missing.md" }, async item => {
if (item.path === "missing.md") throw new Error("Not found");
}), "b.md");
assert.equal(await restoreDocumentSession(session, async () => { throw new Error("Unavailable"); }), null);
});
+121
View File
@@ -0,0 +1,121 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/editor-preview-links';
await mkdir(output, { recursive: true });
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
async function resetFile(text) {
await page.locator('.cm-content').evaluate(async (node, text) => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
}, text);
}
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
await resetFile(installation);
const preview = page.locator('.writer-preview').filter({ has: page.locator('ol') });
await preview.waitFor();
if (theme === 'dark' && width === 1440) {
await preview.evaluate(element => { element.style.whiteSpace = 'pre-wrap'; });
const gap = await preview.locator('li').first().evaluate(item => item.querySelector('p').getBoundingClientRect().top - item.getBoundingClientRect().top);
assert.ok(gap > 15, 'Inherited editor whitespace reproduces the reported blank line');
await page.screenshot({ path:`${output}/ordered-list-before-dark-1440.png` });
await preview.evaluate(element => { element.style.removeProperty('white-space'); });
}
const metrics = await preview.evaluate(element => {
const item = element.querySelector('li'), paragraph = item.querySelector('p');
return { whiteSpace: getComputedStyle(element).whiteSpace, itemTop: item.getBoundingClientRect().top, paragraphTop: paragraph.getBoundingClientRect().top, firstHeight: item.getBoundingClientRect().height, lineHeight: parseFloat(getComputedStyle(paragraph).lineHeight) };
});
assert.equal(metrics.whiteSpace, 'normal');
assert.ok(Math.abs(metrics.paragraphTop - metrics.itemTop) < 2, 'Number and first paragraph share one line');
assert.ok(metrics.firstHeight < metrics.lineHeight * 3, 'Short list item has no blank formatting lines');
assert.equal(await preview.locator('li').count(), 5);
assert.match(await preview.locator('code').last().innerText(), /sha256sum --check SHA256SUMS\n/);
await page.screenshot({ path:`${output}/ordered-list-${theme}-${width}.png` });
const fixture = '# Links\n\nOutside.\n\n| Task | Link |\n| --- | --- |\n| Plugin setup | [Plugin installation](<docs/plugins.md#install-a-plugin>) |\n| Wiki | [[docs/plugins.md\\|Plugin guide]] |\n';
await resetFile(fixture);
await page.evaluate(() => window.tabMenuTest.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
const localLink = page.locator('.writer-table a').filter({ hasText:'Plugin installation' });
await localLink.click({ modifiers:[width === 620 ? 'Meta' : 'Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
assert.equal(page.url(), process.env.SMOKE_URL || 'http://127.0.0.1:1420/');
assert.equal(browser.contexts().flatMap(context => context.pages()).length, 1, 'Local link cannot open a browser tab');
assert.equal(await page.evaluate(() => window.tabMenuTest.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
await page.screenshot({ path:`${output}/local-link-tab-${theme}-${width}.png` });
await page.getByRole('tab', { name:'a.md', exact:true }).click();
const wiki = page.locator('.writer-table a').filter({ hasText:'Plugin guide' });
await wiki.click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.equal(await page.getByRole('tab', { name:'plugins.md', exact:true }).count(), 1, 'Duplicate link focuses its existing document');
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await page.locator('.writer-table a').filter({ hasText:'Plugin installation' }).click();
const source = page.locator('.is-source-editing .writer-cell-editor');
await source.waitFor();
await page.screenshot({ path:`${output}/source-link-${theme}-${width}.png` });
await source.locator('.writer-link-target').click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
}
assert.deepEqual(errors, []);
console.log('PASS: nested fenced-code list spacing, preserved code newlines, rendered/table-source/wiki local links open document tabs, duplicate target focus, both themes, narrow and wide windows. Native WebView acceptance remains open.');
} catch (error) {
await page.screenshot({ path:`${output}/failure.png` });
throw error;
} finally { await browser.close(); }
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { documentHeadings, headingLinkLine, linkFragment } from "../src/lib/workspace/headingLinks.ts";
test("section links decode fragments without changing the file path", () => {
assert.equal(linkFragment("notes/a%23b.md#Caf%C3%A9%20setup"), "Café setup");
assert.equal(linkFragment("#literal%"), "literal%");
assert.equal(linkFragment("a.md"), null);
assert.equal(headingLinkLine("# Title", ""), 1);
});
test("headings use rendered text, Unicode, and unique slugs", () => {
const source = "# **Windows** setup!\n\n## Café `setup`\n\n## Windows setup!\n\n## Windows setup-1\n\n## Windows setup!\n";
assert.deepEqual(documentHeadings(source).map(({ slug }) => slug),
["windows-setup", "café-setup", "windows-setup-1", "windows-setup-1-1", "windows-setup-2"]);
assert.equal(headingLinkLine(source, "windows-setup-2"), 9);
assert.equal(headingLinkLine(source, "Café setup"), 3);
assert.equal(headingLinkLine(source, "missing"), null);
});
test("section lines exclude properties and code, and include Setext headings", () => {
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
assert.deepEqual(documentHeadings(source), [
{ text: "Install", slug: "install", line: 9 },
{ text: "Real", slug: "real", line: 12 },
]);
assert.equal(headingLinkLine(source, "fake"), null);
});
+164
View File
@@ -0,0 +1,164 @@
import test from "node:test";
import assert from "node:assert/strict";
import { WorkspaceNoteIndex, type NoteIndexIO } from "../src/lib/workspace/noteIndex.ts";
function workspace(files: Map<string, string>): NoteIndexIO {
return {
async list(folder) {
const prefix = folder ? `${folder}/` : "";
const entries = new Map<string, { rel_path: string; kind: "file" | "folder" }>();
for (const path of files.keys()) {
if (!path.startsWith(prefix)) continue;
const suffix = path.slice(prefix.length), separator = suffix.indexOf("/");
const rel_path = separator < 0 ? path : prefix + suffix.slice(0, separator);
entries.set(rel_path, { rel_path, kind: separator < 0 ? "file" : "folder" });
}
return [...entries.values()];
},
async read(path) {
if (!files.has(path)) throw new Error("File missing");
return files.get(path)!;
},
};
}
test("wiki names resolve anywhere and duplicate names require a path", async () => {
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(new Map([
["deep/source.md", "[[Elsewhere]]\n[[Root]]"], ["unrelated/nested/Elsewhere.md", ""], ["Root.md", ""],
])));
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "resolved", path: "unrelated/nested/Elsewhere.md" });
assert.deepEqual(index.resolve("deep/source.md", "Root#Heading", "wiki"), { status: "resolved", path: "Root.md" });
index.update("deep/Elsewhere.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "ambiguous", candidates: ["deep/Elsewhere.md", "unrelated/nested/Elsewhere.md"] });
assert.equal(index.backlinks("deep/Elsewhere.md").length, 0);
assert.deepEqual(index.resolve("deep/source.md", "./Elsewhere", "wiki"), { status: "resolved", path: "deep/Elsewhere.md" });
index.update("documents/Other.mdown", "[[Root]]");
assert.deepEqual(index.resolve("deep/source.md", "Other", "wiki"), { status: "resolved", path: "documents/Other.mdown" });
assert.equal(index.backlinks("Root.md").length, 2);
index.update("documents/Version 1.2.md", "");
assert.deepEqual(index.resolve("deep/source.md", "Version 1.2", "wiki"), { status: "resolved", path: "documents/Version 1.2.md" });
});
test("explicit relative links do not fall back and cannot escape the workspace", () => {
const index = new WorkspaceNoteIndex();
for (const path of ["source.md", "deep/source.md", "Target.md", "deep/folder/Target.md", "folder/Target.md", "deep/Name with spaces.md"]) index.update(path, "");
assert.deepEqual(index.resolve("deep/source.md", "./Target", "wiki"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "./Target.md", "md"), { status: "missing" });
assert.deepEqual(index.resolve("deep/source.md", "../Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.deepEqual(index.resolve("deep/source.md", "/Target", "wiki"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "folder/Target", "wiki").status, "ambiguous");
assert.deepEqual(index.resolve("deep/source.md", "Name%20with%20spaces.md#part", "md"), { status: "resolved", path: "deep/Name with spaces.md" });
assert.deepEqual(index.resolve("deep/source.md", "..\\Target.md", "md"), { status: "resolved", path: "Target.md" });
assert.equal(index.resolve("deep/source.md", "../../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "../Target", "wiki").status, "missing");
assert.equal(index.resolve("source.md", "https://example.test", "md").status, "external");
assert.equal(index.resolve("source.md", "//example.test/Target", "md").status, "external");
});
test("backlinks index wiki aliases, inline and reference Markdown links with source lines", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("source.md", [
"[[Target|Alias]]", "[Target](Target.md#Section)", "[Named][id]", "[id][]", "[id]", "", "[id]: Target.md", "",
"`[[Target]]`", "![picture](Target.md)", "![[Target]]", "\\[[Target]]", "<!-- [[Target]] -->", "```md", "[[Target]]", "```",
].join("\n"));
assert.deepEqual(index.backlinks("Target.md").map(link => [link.sourcePath, link.line, link.kind]), [
["source.md", 1, "wiki"], ["source.md", 2, "md"], ["source.md", 3, "md"], ["source.md", 4, "md"], ["source.md", 5, "md"],
]);
index.update("Target.md", "[Local section](#Heading)");
assert.equal(index.backlinks("Target.md").length, 5);
});
test("backlinks follow edits, create, file and folder moves, rename, and deletion", () => {
const index = new WorkspaceNoteIndex();
index.update("folder/source.md", "[[Target]]\n[Target](../Target.md)");
assert.deepEqual(index.backlinks("Target.md"), []);
index.update("Target.md", "");
assert.equal(index.backlinks("Target.md").length, 2);
index.update("folder/source.md", "[[Target]]");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("folder", "other/deep");
assert.equal(index.backlinks("Target.md")[0].sourcePath, "other/deep/source.md");
index.rename("Target.md", "notes/Target.md");
assert.equal(index.backlinks("notes/Target.md").length, 1);
index.rename("notes/Target.md", "notes/Renamed.md");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.update("other/deep/source.md", "[[Renamed]]");
assert.equal(index.backlinks("notes/Renamed.md").length, 1);
index.remove("other");
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
index.remove("notes/Renamed.md");
assert.equal(index.resolve("", "Renamed", "wiki").status, "missing");
});
test("moving a relative-link source changes its target without rewriting Markdown", () => {
const index = new WorkspaceNoteIndex();
index.update("Target.md", "");
index.update("folder/Target.md", "");
index.update("source.md", "[Target](./Target.md)");
assert.equal(index.backlinks("Target.md").length, 1);
index.rename("source.md", "folder/source.md");
assert.equal(index.backlinks("Target.md").length, 0);
assert.equal(index.backlinks("folder/Target.md").length, 1);
});
test("rebuild replaces deleted paths and uses live drafts", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const index = new WorkspaceNoteIndex();
await index.rebuild(workspace(files));
assert.equal(index.backlinks("Target.md").length, 1);
files.delete("source.md");
files.set("elsewhere/source.md", "Old content");
const result = await index.rebuild(workspace(files), new Map([["elsewhere/source.md", "[[Target]]"]]));
assert.equal(result.committed, true);
assert.equal(result.indexed, 2);
assert.deepEqual(result.errors, []);
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["elsewhere/source.md"]);
index.clear();
assert.equal(index.size, 0);
await index.rebuild(workspace(files));
assert.equal(index.size, 2);
});
test("updates during a rebuild survive its disk snapshot", async () => {
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
const io = workspace(files);
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const rebuild = index.rebuild({ ...io, read: async path => { await barrier; return io.read(path); } });
await Promise.resolve();
index.update("source.md", "No link");
index.update("new.md", "[[Target]]");
index.rename("new.md", "moved.md");
release();
await rebuild;
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["moved.md"]);
});
test("workspace clear and a newer rebuild reject stale async results", async () => {
let release!: () => void;
const barrier = new Promise<void>(resolve => release = resolve);
const index = new WorkspaceNoteIndex();
const slow = index.rebuild({ list: async () => { await barrier; return [{ rel_path: "old.md", kind: "file" }]; }, read: async () => "" });
index.clear();
await index.rebuild(workspace(new Map([["new.md", ""]])));
release();
assert.equal((await slow).committed, false);
assert.equal(index.resolve("", "old", "wiki").status, "missing");
assert.deepEqual(index.resolve("", "new", "wiki"), { status: "resolved", path: "new.md" });
});
test("read and list failures report incomplete coverage and remain rebuildable", async () => {
const index = new WorkspaceNoteIndex();
const io = workspace(new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["blocked/note.md", ""]]));
const result = await index.rebuild({
list: async folder => { if (folder === "blocked") throw new Error("Folder unavailable"); return io.list(folder); },
read: async path => { if (path === "source.md") throw new Error("File unavailable"); return io.read(path); },
});
assert.deepEqual(result.errors.map(error => [error.path, error.operation]), [["blocked", "list"], ["source.md", "read"]]);
assert.equal(index.backlinks("Target.md").length, 0);
await index.rebuild(io);
assert.equal(index.backlinks("Target.md").length, 1);
});
+132
View File
@@ -0,0 +1,132 @@
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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tree-actions-test";
const files = new Map([
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
]);
const calls = [];
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
let sequence = 0;
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence,
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|unlisten") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tree-actions-test", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") {
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_delete") {
if (args.rel === state.fail) throw new Error("Access denied");
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
return;
}
if (command === "workspace_copy") {
const to = args.rel + "-copy";
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
}
if (command === "workspace_rename") {
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
for (const [path, text] of [...files]) if (contains(args.from, path)) {
files.delete(path);
files.set(args.to + path.slice(args.from.length), text);
}
return;
}
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
if (command === "workspace_reveal") return;
if (command === "workspace_search") return [];
if (command === "plugin:dialog|message") return state.answer;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = state;
});
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
async function reset() {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await row("notes").waitFor();
}
async function action(path, name) {
await row(path).click({ button: "right" });
await page.getByRole("menuitem", { name, exact: true }).click();
await settle();
}
async function selectFiles() {
await row("a.md").click();
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
await settle();
await row("b.md").click({ modifiers: ["Control"] });
await settle();
}
async function drag(sourcePath, targetPath, place = "inside") {
const source = await row(sourcePath).boundingBox();
const target = await row(targetPath).boundingBox();
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
await page.mouse.down();
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
await page.mouse.up();
await settle();
}
try {
await reset();
for (const [theme, width] of [['dark',1440],['light',620]]) {
await page.setViewportSize({width,height:850});
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = 'default'; },theme);
await row('a.md').click();
await row('a.md').focus();
await page.keyboard.press('F2');
const input=row('a.md').locator('input');
await input.waitFor();
assert.deepEqual(await input.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await page.screenshot({path:'.audit/rename-selection-'+theme+'.png'});
await input.press('Escape');
await row('notes').click();
await row('notes').focus();
await page.keyboard.press('F2');
const folder=row('notes').locator('input');
await folder.waitFor();
assert.deepEqual(await folder.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,5,'notes']);
await folder.press('Escape');
await page.getByRole('tab',{name:'a.md',exact:true}).click();
await page.getByRole('tab',{name:'a.md',exact:true}).click({button:'right'});
await page.getByRole('menuitem',{name:'Rename…',exact:true}).click();
const dialogInput=page.locator('#text-request');
await dialogInput.waitFor();
assert.deepEqual(await dialogInput.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
await dialogInput.press('Escape');
}
assert.deepEqual(errors,[]);
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
} finally { await browser.close(); }
+175
View File
@@ -0,0 +1,175 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-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_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/section-links';
await mkdir(output, { recursive: true });
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420/';
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 });
await page.goto(url);
await page.evaluate(({ source, other }) => {
window.tabMenuTest.files.set('a.md', source);
window.tabMenuTest.files.set('other.md', other);
}, { source, other });
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('macOS setup', await jumpLine('## macOS installer'));
await top();
await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
await top();
await page.locator('.writer-link').filter({ hasText:'Missing section' }).click({ modifiers:['Control'] });
await page.getByText('Could not open #no-such-section', { exact:true }).waitFor();
await top();
await page.locator('.writer-link').filter({ hasText:'Other document' }).click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'other.md', exact:true }).waitFor();
await page.waitForFunction(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
});
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top();
await choose('Document view', 'read');
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'split');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await choose('Document view', 'edit');
await choose('Editor layout', 'Ide');
await page.locator('.monaco-editor').waitFor();
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'edit');
await page.waitForFunction(() => {
const node = document.querySelector('.monaco-editor .view-lines');
return node?.textContent.includes('Linux');
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
assert.equal(page.url(), url);
assert.equal(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), source);
}
await page.goto(url);
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
await page.evaluate(text => window.tabMenuTest.files.set('a.md', text), folded);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await top();
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
await readerJump('Jump to nested', 'Nested');
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
assert.deepEqual(errors, []);
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
} finally { await browser.close(); }
+167
View File
@@ -0,0 +1,167 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const pluginCode = `export function activate(api) {
let state = "Board state";
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
saveTabState: () => state, restoreTabState: value => { state = value; },
mount(container) {
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
return () => input.remove();
}
});
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
identify: (path, source) => source === "board document" ? { id: path } : null,
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const params = new URLSearchParams(location.search);
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
files.set("saved.board", "board document");
if (params.has("missing")) files.delete("a.md");
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("plugin:window|")) return;
if (command === "plugin:dialog|message") return window.lifecycle.answer;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, { pluginCode });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const dragSources = new Map();
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
async function create(query = "") {
const page = await context.newPage(); page.setDefaultTimeout(15000);
page.on("pageerror", error => errors.push(error.message));
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
}
async function open(page, name) {
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
}
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
async function start(page, name) {
const data = await tab(page, name).evaluate(node => {
assertDraggable(node);
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
dragSources.set(data, { page, name });
return data;
}
async function drop(page, data) {
await bar(page).evaluate((node, data) => {
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
}, data);
const source = dragSources.get(data);
if (source) {
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
}
}
async function screenshots(page, prefix) {
await mkdir("output/tab-lifecycle", { recursive: true });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-${mode}.png` });
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-narrow.png` });
await page.setViewportSize({ width: 1400, height: 900 });
}
try {
const page = await create();
for (const name of ["a.md", "b.md", "c.md"]) await open(page, name);
await tab(page, "c.md").focus(); await page.keyboard.press("Alt+Shift+ArrowLeft"); await page.keyboard.press("Alt+Shift+ArrowLeft");
await pin(page, "b.md"); await tab(page, "b.md").click();
await page.evaluate(() => window.lifecycle.close());
const session = await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`)));
assert.deepEqual(session.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
assert.equal(session.activePath, "b.md"); assert.equal(session.documents[2].pinned, true);
assert.ok(!JSON.stringify(session).includes("Saved text"));
await page.goto(url + "?missing"); await tab(page, "b.md").waitFor();
assert.deepEqual(await bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["c.md", "b.md"]);
assert.equal(await tab(page, "b.md").getAttribute("aria-selected"), "true");
await tab(page, "b.md").click({ button: "right" }); await page.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await page.keyboard.press("Escape");
await screenshots(page, "restored-documents");
await page.locator(".cm-content").fill("Unsaved draft");
await page.evaluate(() => window.lifecycle.close());
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`))), session);
await page.evaluate(() => { window.lifecycle.answer = "Ok"; return window.lifecycle.close(); });
page.on("dialog", dialog => dialog.accept());
await page.reload(); await tab(page, "b.md").waitFor();
assert.match(await page.locator(".cm-content").innerText(), /Saved text/);
await open(page, "saved.board"); await page.getByText("Saved board document", { exact: true }).waitFor();
await page.evaluate(() => window.lifecycle.close()); await page.reload();
await tab(page, "saved").waitFor(); await page.getByText("Saved board document", { exact: true }).waitFor();
const source = await create("?plugins"), target = await create("?plugins"), other = await create("?other"), disabled = await create("?plugins&disabled");
assert.equal(await tab(other, "New tab").count(), 1);
await openBoard(source); await source.getByRole("textbox", { name: "Board state" }).fill("Transferred board state"); await pin(source, "Board");
let data = await start(source, "Board"); assert.ok(JSON.parse(data).tabTransfer);
await drop(other, data); await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
await drop(disabled, data); await disabled.getByText("Enable this tab's plugin before moving it to this window.").waitFor();
assert.equal(await tab(source, "Board").count(), 1);
await drop(target, data); await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
await tab(target, "Board").click({ button: "right" }); await target.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await target.keyboard.press("Escape");
await screenshots(target, "joined-plugin");
data = await start(target, "Board"); await drop(source, data); await tab(target, "Board").waitFor({ state: "detached" });
await openBoard(target); await target.getByRole("textbox", { name: "Board state" }).fill("Destination state");
data = await start(source, "Board"); await drop(target, data);
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Destination state"); assert.equal(await tab(source, "Board").count(), 1);
await tab(source, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
await tab(source, "Board").click({ button: "right" }); await source.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
const token = await source.evaluate(() => window.lifecycle.transfer); assert.ok(token);
const detached = await create(`?plugins&tabTransfer=${token}`); await detached.getByRole("textbox", { name: "Board state" }).waitFor();
await tab(source, "Board").waitFor({ state: "detached" });
data = await start(detached, "Board"); await drop(source, data); await tab(detached, "Board").waitFor({ state: "detached" });
assert.equal(await source.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
assert.deepEqual(errors, []);
console.log("PASS: normal-close restore, order, active tab, pins, missing files, workspace isolation, canceled close, disk-only restore, plugin documents, plugin join, duplicate protection, disabled plugin, and tear-out return");
} catch (reason) {
for (const page of context.pages()) console.error(page.url(), (await page.locator("body").innerText()).slice(-1000));
throw reason;
} finally { await browser.close(); }
+183
View File
@@ -0,0 +1,183 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
const pluginCode = `export function activate(api) {
let state = "Board state";
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
saveTabState: () => state, restoreTabState: value => { state = value; },
mount(container) {
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
return () => input.remove();
}
});
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
identify: (path, source) => source === "board document" ? { id: path } : null,
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
});
}`;
await context.addInitScript(({ pluginCode }) => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const params = new URLSearchParams(location.search);
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
files.set("saved.board", "board document");
if (params.has("missing")) files.delete("a.md");
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("plugin:window|")) return;
if (command === "plugin:dialog|message") return window.lifecycle.answer;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
if (command === "plugins_load") return pluginCode;
if (command === "plugins_data") return "null";
if (command === "plugins_release") return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, { pluginCode });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
async function create(query = "") {
const page = await context.newPage(); page.setDefaultTimeout(15000);
page.on("pageerror", error => errors.push(error.message));
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
}
async function open(page, name) {
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
}
async function openBoard(page) {
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
await page.getByRole("textbox", { name: "Board state" }).waitFor();
}
async function pin(page, name) {
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
}
async function start(page, name) {
const data = await tab(page, name).evaluate(node => {
assertDraggable(node);
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
return transfer.getData("application/x-runestone-tab");
});
return data;
}
async function screenshots(page, prefix) {
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const mode of ["dark", "light"]) {
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-${mode}.png` });
}
await page.setViewportSize({ width: 700, height: 700 });
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-narrow.png` });
await page.setViewportSize({ width: 1400, height: 900 });
}
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
return page.evaluate(({ data, point, type, mime }) => {
const transfer = new DataTransfer(); transfer.setData(mime, data);
const node = document.elementFromPoint(point.x, point.y) || document.body;
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
node.dispatchEvent(event);
return event.defaultPrevented;
}, { data, point, type, mime });
}
async function receive(page, data, point) {
assert.equal(await eventAt(page, data, point), true);
assert.equal(await eventAt(page, data, point, "drop"), true);
}
async function point(page, kind) {
return page.locator(".header").evaluate((header, kind) => {
const bounds = header.getBoundingClientRect();
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
const first = header.querySelector('.tab').getBoundingClientRect();
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
}, kind);
}
try {
const source = await create("?plugins"), target = await create("?plugins");
await open(target, "b.md");
await open(source, "a.md"); await pin(source, "a.md");
await source.locator(".cm-content").fill("Unsaved ribbon transfer");
let data = await start(source, "a.md •");
const broad = await point(target, "blank");
assert.equal(await eventAt(target, data, broad), true, "Blank titlebar space accepts transferred tabs");
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), true);
assert.equal(await eventAt(target, data, await point(target, "outside")), false, "The document body stays outside the drop target");
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), false);
assert.equal(await eventAt(target, data, await point(target, "controls")), false, "Window controls stay outside the drop target");
assert.equal(await eventAt(target, data, broad, "dragover", "text/plain"), false, "Ordinary file and text drags retain their behavior");
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const mode of ["light", "dark"]) {
await target.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
await eventAt(target, data, broad);
await target.screenshot({ path: `output/tab-ribbon-drop/${mode}-blank-receiving.png` });
}
await receive(target, data, broad);
await tab(target, "a.md •").waitFor(); await tab(source, "a.md •").waitFor({ state: "detached" });
assert.deepEqual(await order(target), ["b.md", "a.md •"]);
assert.match(await target.locator(".cm-content").innerText(), /Unsaved ribbon transfer/);
assert.ok(await tab(target, "a.md •").getAttribute("aria-describedby"));
await open(source, "c.md"); data = await start(source, "c.md");
await receive(target, data, await point(target, "precise"));
await tab(target, "c.md").waitFor(); await tab(source, "c.md").waitFor({ state: "detached" });
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •"]);
await openBoard(source); await pin(source, "Board"); await source.getByRole("textbox", { name: "Board state" }).fill("Plugin ribbon state");
data = await start(source, "Board");
await target.setViewportSize({ width: 700, height: 700 });
const nearby = await point(target, "near");
await eventAt(target, data, nearby);
await bar(target).and(target.locator('.receiving')).waitFor();
await target.screenshot({ path: "output/tab-ribbon-drop/narrow-near-receiving.png" });
await receive(target, data, nearby);
await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •", "Board"]);
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Plugin ribbon state");
assert.ok(await tab(target, "Board").getAttribute("aria-describedby"));
await screenshots(target, "ribbon-plugin-pinned");
data = await start(target, "Board");
assert.equal(await eventAt(target, data, await point(target, "near")), false, "Same-window reordering stays precise");
await receive(target, data, await point(target, "precise"));
assert.deepEqual(await order(target), ["Board", "c.md", "b.md", "a.md •"]);
await tab(target, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
assert.deepEqual(errors, []);
console.log("PASS: broad titlebar and nearby ribbon drops, exact tab ordering, rejection outside the ribbon and over window controls, ordinary drag isolation, pinned unsaved documents, narrow plugin transfers, and source acknowledgement");
} catch (error) {
await mkdir("output/tab-ribbon-drop", { recursive: true });
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `output/tab-ribbon-drop/failure-${index}.png` });
throw error;
} finally { await browser.close(); }
+154
View File
@@ -0,0 +1,154 @@
// 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 page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
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.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_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); 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 window.__TEST__.answer ?? "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 page.addInitScript(() => {
localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false}));
const {files}=window.__TEST__; files.clear();
files.set('projects/source.md','# Source\n\n[[Target]]\n');
files.set('archive/deep/Target.md','# Target\n');
files.set('other.md','# Other\n\n[Target](archive/deep/Target.md)\n');
});
async function openNote(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.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
}
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
try {
await page.goto(process.env.SMOKE_URL||'http://127.0.0.1:1420');
await page.getByText('smoke-workspace',{exact:true}).waitFor();
await openNote('projects/source.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.getByRole('tab',{name:'Target.md',exact:true}).waitFor();
await backlink('projects/source.md').waitFor();
await backlink('other.md').waitFor();
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
await page.screenshot({path:'.audit/workspace-links-dark.png'});
await backlink('projects/source.md').click();
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='projects/source.md');
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
await writer.focus(); await page.keyboard.press('Control+Home'); await page.keyboard.press('Control+a'); await page.keyboard.type('# Source\n\nNo links now.');
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.waitForFunction(()=>!document.querySelector('button[aria-label="Open projects/source.md, line 3"]'));
await backlink('other.md').waitFor();
await page.evaluate(()=>{
window.__TEST__.files.set('duplicates/Target.md','# Another target');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await openNote('other.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await page.evaluate(()=>{
window.__TEST__.files.set('wiki.md','# Wiki\n\n[[Target]]\n');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['wiki.md']});
});
await openNote('wiki.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.locator('.status').filter({hasText:'More than one note matches Target'}).waitFor();
assert.equal(await page.locator('.breadcrumb').textContent(),'wiki.md');
await page.evaluate(()=>{
window.__TEST__.files.delete('duplicates/Target.md');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'remove',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await backlink('wiki.md').waitFor();
await page.evaluate(()=>{
const {files,emit,root}=window.__TEST__;
files.set('moved/wiki.md',files.get('wiki.md')); files.delete('wiki.md');
emit('workspace-event',{root,kind:'rename',paths:['wiki.md','moved/wiki.md']});
});
await backlink('moved/wiki.md').waitFor();
assert.equal(await backlink('wiki.md').count(),0);
await page.evaluate(()=>{window.__TEST__.answer='Ok';});
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).click();
await page.keyboard.press('Control+w');
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).waitFor({state:'detached'});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await backlink('projects/source.md').waitFor();
await page.setViewportSize({width:620,height:850});
await page.evaluate(()=>{document.documentElement.dataset.theme='light';});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.screenshot({path:'.audit/workspace-links-narrow.png'});
assert.deepEqual(errors,[]);
console.log('Workspace link integration passed: workspace wiki resolution, new tabs, backlinks navigation, live edits, discarded drafts, creation, move, deletion and duplicate guard.');
}finally{await browser.close();}
+1 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.42"
version = "0.1.44"
dependencies = [
"base64 0.23.1",
"dunce",
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "runestone"
version = "0.1.42"
version = "0.1.44"
description = "Writing workspace plus script editor"
authors = ["you"]
edition = "2021"
@@ -44,4 +44,4 @@ panic = "abort"
strip = true
[package.metadata.runestone]
version = "0.1.42"
version = "0.1.44"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.42",
"version": "0.1.44",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
+5 -2
View File
@@ -8,6 +8,7 @@
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
import { writerHistory, historyKeymap } from "./writerHistory";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { foldedRanges, unfoldEffect } from "@codemirror/language";
import { noteFormats } from "./noteFormats";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
@@ -409,7 +410,9 @@
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
view.dispatch({ selection: { anchor }, effects: EditorView.scrollIntoView(anchor, { y: "center" }) });
const effects = [EditorView.scrollIntoView(anchor, { y: "center" })];
foldedRanges(view.state).between(anchor, anchor, (from, to) => { effects.push(unfoldEffect.of({ from, to })); });
view.dispatch({ selection: { anchor }, effects });
view.focus();
});
});
@@ -461,7 +464,7 @@
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; }
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; white-space: normal; }
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
.live-writer :global(.writer-preview img) { max-width: 100%; }
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
+13
View File
@@ -121,6 +121,19 @@ class Preview extends WidgetType {
previewFormulas.set(dom, this.formulas);
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run.
dom.addEventListener("mousedown", event => {
if (event.button !== 0 || (!event.ctrlKey && !event.metaKey)) return;
const link = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-href], a[href]") : null;
if (!link) return;
event.preventDefault();
event.stopPropagation();
void this.actions.linkActions?.().open?.({ kind: link.dataset.kind === "wiki" ? "wiki" : "md", target: link.dataset.href ?? link.getAttribute("href") ?? "" });
}, { capture: true });
// Cancel native anchor navigation even when an ordinary click reveals source.
dom.addEventListener("click", event => {
if (event.target instanceof Element && event.target.closest("a[href], [data-href]")) event.preventDefault();
}, { capture: true });
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
this.measure(dom, view);
+7
View File
@@ -1,5 +1,12 @@
export type Locale = 'en' | 'fr' | 'ja' | 'zh-CN';
export const messageRows: [string, string, string, string][] = [
["Backlinks", "Liens entrants", "バックリンク", "反向链接"],
["Rebuild note index", "Reconstruire l’index des notes", "ノート索引を再構築", "重建笔记索引"],
["Reading workspace links…", "Lecture des liens de l’espace de travail…", "ワークスペースのリンクを読み込み中…", "正在读取工作区链接…"],
["No other notes link to this file.", "Aucune autre note ne pointe vers ce fichier.", "このファイルへのリンクがある他のノートはありません。", "没有其他笔记链接到此文件。"],
["Open {path}, line {line}", "Ouvrir {path}, ligne {line}", "{path} の {line} 行目を開く", "打开 {path},第 {line} 行"],
["Could not read all workspace links. Rebuild the index to retry.", "Impossible de lire tous les liens. Reconstruisez l’index pour réessayer.", "一部のリンクを読み込めませんでした。索引を再構築して再試行してください。", "无法读取所有工作区链接。请重建索引以重试。"],
["More than one note matches {path}. Use its workspace path: {candidates}", "Plusieurs notes correspondent à {path}. Utilisez le chemin dans l’espace de travail : {candidates}", "{path} に一致するノートが複数あります。ワークスペース内のパスを指定してください: {candidates}", "多个笔记与 {path} 匹配。请使用其工作区路径:{candidates}"],
["{name}: package applied.", "{name} : paquet appliqué.", "{name}: パッケージを適用しました。", "{name}:已应用软件包。"],
["To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.", "Pour mettre à jour un plug-in, sélectionnez son nouveau ZIP ou lien de version. Ses paramètres et son état restent identiques.", "プラグインを更新するには、新しいZIPまたはリリースリンクを選択してください。設定と有効状態は保持されます。", "要更新插件,请选择新的 ZIP 或发行链接。设置和启用状态保持不变。"],
["Update {current} → {next}. Settings and enabled state stay the same.", "Mise à jour {current} → {next}. Les paramètres et l’état restent identiques.", "{current} → {next} に更新します。設定と有効状態は保持されます。", "更新 {current} → {next}。设置和启用状态保持不变。"],
+79
View File
@@ -0,0 +1,79 @@
<script lang="ts">
import { t } from "$lib/i18n";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import type { Backlink } from "$lib/workspace/noteIndex";
type Props = {
entries: Backlink[];
busy?: boolean;
error?: string | null;
onOpen: (entry: Backlink) => void;
onRebuild?: () => void;
};
let { entries, busy = false, error = null, onOpen, onRebuild }: Props = $props();
let expanded = $state(true);
const contentId = $props.id();
function collapseTooltip(node: HTMLElement) {
return { destroy: attachTooltip(node, () => $t(expanded ? "Collapse backlinks" : "Expand backlinks")) };
}
</script>
<section class="backlinks" aria-label={$t("Backlinks")} aria-busy={busy}>
<div class="heading">
<button class="toggle" type="button" aria-expanded={expanded} aria-controls={contentId} use:collapseTooltip onclick={() => expanded = !expanded}>
<span class:collapsed={!expanded}><Icon icon="chevron-down" /></span>
<Icon icon="link" />
<span>{$t("Backlinks")}</span>
<span class="count">{entries.length}</span>
</button>
{#if onRebuild}
<IconButton icon="refresh" label={$t("Rebuild note index")} disabled={busy} onclick={onRebuild} />
{/if}
</div>
<div id={contentId} class="content" hidden={!expanded}>
{#if error}
<p class="error" role="status">{error}</p>
{/if}
{#if busy}
<p class="placeholder" role="status">{$t("Reading workspace links…")}</p>
{:else if entries.length === 0}
<p class="placeholder">{$t("No other notes link to this file.")}</p>
{/if}
{#if entries.length > 0}
<ul>
{#each entries as entry (entry.sourcePath + ":" + entry.from)}
<li>
<button class="source" type="button" aria-label={$t("Open {path}, line {line}", { path: entry.sourcePath, line: entry.line })} onclick={() => onOpen(entry)}>
<span class="source-title"><Icon icon="text" /><span>{entry.sourcePath}</span><span class="line">{entry.line}</span></span>
<span class="excerpt">{entry.text}</span>
</button>
</li>
{/each}
</ul>
{/if}
</div>
</section>
<style>
.backlinks { min-height: 0; border-top: 1px solid var(--rs-border); display: flex; flex-direction: column; }
.heading { display: flex; align-items: center; gap: 2px; padding: 2px 6px; }
.toggle { display: flex; align-items: center; gap: 6px; flex: 1; min-width: 0; min-height: 28px; padding: 2px 4px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; font: inherit; }
.toggle > span:first-child { display: flex; }
.collapsed { transform: rotate(-90deg); }
.count { margin-left: auto; font-variant-numeric: tabular-nums; color: var(--rs-text-dim); }
.content { min-height: 0; overflow: auto; }
.content[hidden] { display: none; }
ul { list-style: none; padding: 2px 6px 6px; margin: 0; }
.source { width: 100%; display: block; padding: 6px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); text-align: left; font: inherit; }
.source-title { display: flex; align-items: center; gap: 6px; color: var(--rs-accent); }
.source-title > span:first-of-type { min-width: 0; overflow-wrap: anywhere; }
.line { margin-left: auto; color: var(--rs-text-dim); font-variant-numeric: tabular-nums; }
.excerpt { display: -webkit-box; line-clamp: 2; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; margin-top: 3px; font-size: 12px; overflow-wrap: anywhere; }
.toggle:hover, .source:hover { background: var(--rs-bg-active); }
.toggle:focus-visible, .source:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
.placeholder, .error { margin: 8px 12px; font-size: 12px; overflow-wrap: anywhere; }
.placeholder { color: var(--rs-text-dim); }
.error { color: var(--rs-error); }
</style>
+1 -1
View File
@@ -227,7 +227,7 @@
{#if reading && canPreview}
{#key buffer.id}
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {focusLine} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
</div>
{/key}
{/if}
+15 -1
View File
@@ -8,6 +8,7 @@
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import { documentHeadings } from "$lib/workspace/headingLinks";
import "$lib/editor/headingFolding.css";
import { readingMenu } from "$lib/editor/readingMenu";
@@ -16,6 +17,7 @@
type Props = {
noteRel: string;
contents: string;
focusLine?: number | null;
linkActions?: DocumentLinkActions;
onSearch?: (text: string) => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
@@ -24,7 +26,7 @@
blockEditor?: Snippet;
};
let { noteRel, contents, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
let { noteRel, contents, focusLine = null, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let menuError = $state("");
let sections = $state<MarkdownSection[]>([]);
@@ -82,6 +84,8 @@
void html;
void sections;
void editing;
const line = focusLine;
const headings = documentHeadings(contents);
const el = root;
let cancelled = false;
let releaseImages: (() => void) | undefined;
@@ -90,6 +94,16 @@
if (cancelled) return;
releaseImages = imageControls(el);
headingControls = currentHeadings = readerHeadingFolding(el, collapsedHeadings);
if (line !== null) requestAnimationFrame(() => {
if (cancelled) return;
const index = headings.findIndex(heading => heading.line === line);
const target = line === 1 && index < 0 ? el.querySelector<HTMLElement>(".document-title") :
[...el.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6")].filter(heading => !heading.classList.contains("document-title"))[index];
if (!target) return;
currentHeadings?.reveal(target);
target.scrollIntoView({ block: "center" });
el.focus({ preventScroll: true });
});
return renderDiagrams(el, () => cancelled);
});
return () => { cancelled = true; releaseImages?.(); currentHeadings?.destroy(); };
+45 -2
View File
@@ -89,6 +89,44 @@
cancelAnimationFrame(transferFrame); transferFrame = 0;
}
function clearTransferTarget() {
receiving = false; dropBefore = dropAfter = null;
cancelAnimationFrame(transferFrame); transferFrame = 0;
}
function nearRibbon(event: DragEvent) {
if (dragged || !onDropTab || !event.dataTransfer?.types.includes(transferType)) return false;
const header = bar?.closest(".header");
if (!header || (event.target instanceof Element && event.target.closest(".window-controls"))) return false;
const bounds = header.getBoundingClientRect();
return event.clientX >= bounds.left && event.clientX <= bounds.right
&& event.clientY >= bounds.top && event.clientY <= bounds.bottom + 24;
}
function ribbonDragOver(event: DragEvent) {
if (event.defaultPrevented) {
if (!(event.target instanceof Node) || !bar.contains(event.target)) clearTransferTarget();
return;
}
if (!nearRibbon(event)) { clearTransferTarget(); return; }
event.preventDefault();
event.dataTransfer!.dropEffect = "move";
clearTransferTarget();
receiving = true;
// The wider target accepts a transfer at the end. Tabs retain precise ordering.
dropAfter = tabs.at(-1)?.relPath ?? null;
}
function ribbonDrop(event: DragEvent) {
if (event.defaultPrevented || !nearRibbon(event)) { clearTransferTarget(); return; }
const data = event.dataTransfer?.getData(transferType);
if (!data) { clearTransferTarget(); return; }
event.preventDefault(); event.stopPropagation();
const index = tabs.length;
finishTabTransfer();
onDropTab?.(data, index);
}
function dropTab(event: DragEvent) {
const data = event.dataTransfer?.getData(transferType);
if (!data) return;
@@ -101,6 +139,8 @@
$effect(() => {
if (menuPath && !tabs.some(tab => tab.relPath === menuPath)) closeMenu();
// A successful transfer can remove the drag source before dragend arrives.
if (dragged && !tabs.some(tab => tab.relPath === dragged)) finishTabTransfer();
});
function tabButton(path: string) {
@@ -276,7 +316,10 @@
}
</script>
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()}
ondragover={ribbonDragOver} ondrop={ribbonDrop}
ondragleave={(event) => { if (!event.relatedTarget) clearTransferTarget(); }}
ondragend={clearTransferTarget} />
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label={$t("Working tabs")} tabindex="-1"
ondragover={dragOver} ondrop={dropTab}
@@ -338,7 +381,7 @@
box-shadow: inset 0 -1px var(--rs-border);
}
.tabs:empty { min-width: 80px; }
.tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); }
.tabs.receiving, .tabs.receiving .tab { box-shadow: inset 0 -2px var(--rs-accent); }
.tab {
position: relative;
+3 -1
View File
@@ -5,7 +5,9 @@
let input: HTMLInputElement | undefined = $state();
$effect(() => {
if (dialogs.text && element && input) {
element.showModal(); input.focus(); input.select();
element.showModal(); input.focus();
if (dialogs.text.selection) input.setSelectionRange(...dialogs.text.selection);
else input.select();
}
});
</script>
+2 -1
View File
@@ -4,6 +4,7 @@
import type { DropTarget } from "$lib/workspace/treeDrop";
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
import { treeFileParts } from "$lib/workspace/chrome";
import { renameSelection } from "$lib/workspace/renamePath";
import TreeNode from "./TreeNode.svelte";
import Icon from "$lib/ui/Icon.svelte";
import { pluginDocuments } from "$lib/plugins/external";
@@ -64,7 +65,7 @@
function focusSelect(node: HTMLInputElement) {
node.focus();
node.select();
node.setSelectionRange(...renameSelection(node.value, entry.kind));
}
function edgeWidth(steps: number | null | undefined) {
+169 -18
View File
@@ -4,7 +4,7 @@
import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab } from "$lib/plugins/external";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, waitForPluginStartup } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, onDestroy, tick, untrack } from "svelte";
@@ -21,6 +21,7 @@
import { confirm } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener";
import { Documents } from "$lib/workspace/documents";
import { documentSessionKey, parseDocumentSession, restoreDocumentSession, type DocumentSession } from "$lib/workspace/documentSession";
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import { orderWorkbenchTabs, type WorkbenchTab } from "$lib/workspace/workbenchTabs";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
@@ -38,6 +39,8 @@
import EditorPane from "./EditorPane.svelte";
import TabBar from "./TabBar.svelte";
import OutlinePane from "./OutlinePane.svelte";
import Backlinks from "./Backlinks.svelte";
import { WorkspaceNoteIndex, type Backlink } from "$lib/workspace/noteIndex";
import IconButton from "$lib/ui/IconButton.svelte";
import WindowControls from "$lib/ui/WindowControls.svelte";
import SearchPane from "./SearchPane.svelte";
@@ -62,9 +65,10 @@
workspaceWriteBytes,
} from "$lib/workspace/api";
import { detectChrome } from "$lib/workspace/chrome";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
import { planRename, planMarkdownTitleRename, planDocumentTitleRename, renameSelection } from "$lib/workspace/renamePath";
import { attachmentRel, isImagePath, isMarkdownPath } from "$lib/workspace/media";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { headingLinkLine, linkFragment } from "$lib/workspace/headingLinks";
import type { Chrome, OpenBuffer, TreeEntry, WorkspaceInfo } from "$lib/workspace/types";
let workspace = $state<WorkspaceInfo | null>(null);
@@ -90,6 +94,62 @@
let status = $state($t("Open a workspace folder"));
let error = $state<string | null>(null);
let refreshToken = $state(0);
const noteIndex = new WorkspaceNoteIndex();
let noteIndexRoot: string | null = null;
let noteIndexRevision = $state(0);
let noteIndexBusy = $state(false);
let noteIndexError = $state<string | null>(null);
let noteIndexPending: Promise<void> = Promise.resolve();
let noteIndexRequest = 0;
const backlinks = $derived.by(() => {
void noteIndexRevision;
return activePath && !editorPluginVisible ? noteIndex.backlinks(activePath) : [];
});
function rebuildNoteIndex() {
const root = workspace?.root ?? null;
if (root !== noteIndexRoot) {
noteIndex.clear(); noteIndexRoot = root; noteIndexRevision = noteIndex.revision;
}
const request = ++noteIndexRequest;
noteIndexBusy = !!root;
noteIndexError = null;
if (!root) return noteIndexPending = Promise.resolve();
const drafts = new Map((documents?.buffers ?? []).filter(tab => tab.kind === "text" && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
return noteIndexPending = noteIndex.rebuild({ list: workspaceList, read: workspaceRead }, drafts).then(result => {
if (request !== noteIndexRequest || workspace?.root !== root) return;
noteIndexRevision = noteIndex.revision;
noteIndexBusy = false;
if (result.errors.length) noteIndexError = $t("Could not read all workspace links. Rebuild the index to retry.");
}).catch(reason => {
if (request !== noteIndexRequest) return;
noteIndexBusy = false; noteIndexError = String(reason);
});
}
$effect(() => {
void workspace?.root; void refreshToken;
untrack(() => { void rebuildNoteIndex(); });
});
let indexedDrafts = new Map<string, string>();
let draftsRoot: string | null = null;
$effect(() => {
const root = workspace?.root ?? null;
const drafts = new Map(tabs.filter(tab => tab.kind === "text" && isMarkdownPath(tab.relPath) && tab.contents !== tab.saved && !tab.diskError).map(tab => [tab.relPath, tab.contents]));
untrack(() => {
if (draftsRoot !== root) { indexedDrafts = new Map(); draftsRoot = root; }
const removed = [...indexedDrafts.keys()].some(path => !drafts.has(path));
for (const [path, contents] of drafts) if (indexedDrafts.get(path) !== contents) noteIndex.update(path, contents);
indexedDrafts = drafts;
noteIndexRevision = noteIndex.revision;
if (removed) void rebuildNoteIndex();
});
});
async function openBacklink(entry: Backlink) {
await openFile({ name: entry.sourcePath.split("/").pop()!, rel_path: entry.sourcePath, kind: "file" }, entry.line, "new");
}
let view = $state<Chrome>("Writing");
let layoutReady = $state(false);
let leftWidth = $state(DEFAULT_WORKBENCH_LAYOUT.leftWidth);
@@ -237,10 +297,9 @@
});
function workingTabDragData(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
if (view) return pluginTabDragData(view);
const item = workingTabs.find(item => item.id === tab.id);
if (!item || !workspace || !desktop) return;
try { return JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
try { return (view && pluginTabDragData(view)) || JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
catch (reason) { error = String(reason); return; }
}
async function receiveTab(data: string, index: number) {
@@ -253,14 +312,21 @@
if (!raw) throw new Error("This tab transfer expired. Drag the tab again.");
const transfer = JSON.parse(raw);
if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace.");
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000
|| !transfer.buffer || typeof transfer.buffer.relPath !== "string" || typeof transfer.buffer.contents !== "string"
|| typeof transfer.buffer.saved !== "string") throw new Error("Invalid tab transfer.");
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000) throw new Error("Invalid tab transfer.");
let path: string;
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string"
&& typeof transfer.buffer.saved === "string") {
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
selectTab(transfer.buffer.relPath);
path = transfer.buffer.relPath;
selectTab(path);
} else if (transfer.plugin) {
if (!await restorePluginTab(transfer.plugin)) throw new Error("Enable this tab's plugin before moving it to this window.");
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
path = `plugin:${$pluginView.key}`;
} else throw new Error("Invalid tab transfer.");
setReading(transfer.reading === true);
await tick();
moveWorkingTab(transfer.buffer.relPath, index);
moveWorkingTab(path, index);
localStorage.setItem(key + ".accepted", "true");
localStorage.removeItem(key);
error = null;
@@ -358,6 +424,51 @@
await workspacePicker.show();
}
function saveDocumentTabs() {
if (!workspace || !workbenchReady || transferredWindow) return;
const documents = workingTabs.flatMap(tab => "buffer" in tab && tab.buffer.kind !== "empty"
? [{ path: tab.buffer.relPath, pinned: !!tab.pinned }]
: "plugin" in tab && tab.plugin.document ? [{ path: tab.plugin.document.path, pinned: !!tab.pinned, plugin: true }] : []);
const active = workingTabs.find(tab => tab.relPath === activeTabPath);
const activeDocument = active && ("buffer" in active ? active.buffer.relPath : active.plugin.document?.path);
const session: DocumentSession = { version: 1, documents, activePath: activeDocument ?? activePath };
try { localStorage.setItem(documentSessionKey(workspace.root), JSON.stringify(session)); }
catch (reason) { console.warn("Could not save document tabs.", reason); }
}
async function restoreDocumentTabs() {
const current = documents;
if (!current || !workspace) return;
const session = parseDocumentSession(localStorage.getItem(documentSessionKey(workspace.root)));
if (!session) return;
if (session.documents.some(tab => tab.plugin)) await waitForPluginStartup();
const order: string[] = [];
const paths = new Map<string, string>();
const active = await restoreDocumentSession(session, async tab => {
if (tab.plugin) {
const entries = await workspaceList(tab.path.split("/").slice(0, -1).join("/"));
if (!entries.some(entry => entry.kind === "file" && entry.rel_path === tab.path)) throw new Error("Missing document.");
}
if (tab.plugin && await openPluginDocument(tab.path)) {
await tick();
const opened = $pluginEditors.find(view => view.document?.path === tab.path);
if (!opened) throw new Error("The plugin did not open this document.");
if (tab.pinned !== !!opened.pinned) pinPluginEditor(opened.key);
order.push(opened.key);
paths.set(tab.path, `plugin:${opened.key}`);
} else {
await current.open({ name: tab.path.split("/").pop()!, rel_path: tab.path, kind: "file" }, "background");
if (tab.pinned) current.togglePin(tab.path);
const opened = current.buffers.find(buffer => buffer.relPath === tab.path)!;
order.push(opened.tabId ?? opened.id);
paths.set(tab.path, tab.path);
}
});
await tick();
tabOrder = order;
if (active) selectWorkingTab(paths.get(active)!);
}
async function restoreLast() {
switching = true;
try {
@@ -391,7 +502,7 @@
localStorage.removeItem(key);
}
}
}
} else await restoreDocumentTabs();
}
} catch (err) { error = String(err); }
finally { switching = false; workbenchReady = true; }
@@ -835,6 +946,8 @@
function applyPathRename(from: string, to: string) {
documents?.rename(from, to);
renamePluginDocuments(from, to);
noteIndex.rename(from, to);
noteIndexRevision = noteIndex.revision;
}
async function renameNoteTitle(id: string, title: string) {
@@ -859,7 +972,8 @@
}
const current = documents;
const from = activePath;
const typed = await requestText($t("Rename to"), from.split("/").pop() ?? from);
const name = from.split("/").pop() ?? from;
const typed = await requestText($t("Rename to"), name, { selection: renameSelection(name) });
if (typed == null || documents !== current || switching) {
return;
}
@@ -887,7 +1001,11 @@
const current = documents, currentWorkspace = workspace;
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
const entry = async () => {
for (const path of linkCandidates(origin, link.target, link.kind)) {
await noteIndexPending;
const resolution = noteIndex.resolve(origin, link.target, link.kind);
if (resolution.status === "ambiguous") throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: resolution.candidates.join(", ") }));
const paths = resolution.status === "resolved" ? [resolution.path] : link.kind === "wiki" ? [] : linkCandidates(origin, link.target, link.kind);
for (const path of paths) {
if (!valid()) throw new Error("The workspace changed. Open the link menu again.");
const parent = path.split("/").slice(0, -1).join("/");
let files: TreeEntry[];
@@ -901,7 +1019,8 @@
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
};
async function rename(file: TreeEntry, move = false) {
const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name);
const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name,
move ? undefined : { selection: renameSelection(file.name) });
if (!typed || !valid()) return;
let to = typed.trim().replaceAll("\\", "/");
if (move) {
@@ -956,12 +1075,33 @@
} catch (err) { error = String(err); }
return;
}
const rels = linkCandidates(origin, target, kind);
const current = documents, root = workspace?.root;
await noteIndexPending;
if (documents !== current || workspace?.root !== root) return;
const resolution = noteIndex.resolve(origin, target, kind);
if (resolution.status === "ambiguous") {
error = $t("More than one note matches {path}. Use its workspace path: {candidates}", { path: target, candidates: resolution.candidates.join(", ") });
return;
}
const rels = resolution.status === "resolved" ? [resolution.path] : kind === "wiki" ? [] : linkCandidates(origin, target, kind);
const fragment = linkFragment(target);
focusDocumentPane(paneId);
for (const rel of rels) {
try {
await documents?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" });
await current?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" }, "new");
if (documents !== current || workspace?.root !== root) return;
pluginEditorActive.set(false);
error = null;
focusLine = null;
if (fragment !== null) {
const opened = current?.buffers.find(buffer => buffer.relPath === rel);
const line = opened?.kind === "text" ? headingLinkLine(opened.contents, fragment) : null;
if (line === null) error = $t("Could not open {path}", { path: target });
else {
await tick();
if (documents === current && workspace?.root === root && documentPanes.active === paneId) focusLine = line;
}
}
return;
} catch { /* Try the workspace-root candidate after the note-relative path. */ }
}
@@ -1065,13 +1205,16 @@
}).then(register).catch(err => error = String(err));
let closing = false;
void getCurrentWindow().onCloseRequested(async event => {
if (!hasDirty && !terminalStarted) return;
if (!hasDirty && !terminalStarted) { saveDocumentTabs(); return; }
event.preventDefault();
if (closing) return;
closing = true;
try {
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n");
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) await getCurrentWindow().destroy();
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) {
saveDocumentTabs();
await getCurrentWindow().destroy();
}
} finally { closing = false; }
}).then(register).catch(err => error = String(err));
const focus = () => { void documents?.refresh(); refreshToken++; };
@@ -1211,7 +1354,7 @@
status = message;
error = null;
}}
onEntryGone={(path) => { removePluginDocuments(path); void documents?.refresh(); }}
onEntryGone={(path) => { removePluginDocuments(path); noteIndex.remove(path); noteIndexRevision = noteIndex.revision; void documents?.refresh(); refreshToken++; }}
onEntryRenamed={applyPathRename}
/>
</div>
@@ -1346,6 +1489,7 @@
onpointerdown={() => (dragging = "right")}
></div>
<aside class="right">
<div class="outline-area">
<OutlinePane
items={outlineItems}
onJump={(line) => {
@@ -1357,6 +1501,10 @@
});
}}
/>
</div>
{#if buffer?.kind === "text" && isMarkdownPath(buffer.relPath) && !editorPluginVisible}
<Backlinks entries={backlinks} busy={noteIndexBusy} error={noteIndexError} onOpen={entry => void openBacklink(entry)} onRebuild={() => void rebuildNoteIndex()} />
{/if}
</aside>
{/if}
@@ -1370,6 +1518,9 @@
</div>
<style>
.right { display: flex; flex-direction: column; }
.outline-area { flex: 1; min-height: 80px; overflow: hidden; }
.right > :global(.backlinks) { flex: 0 1 auto; max-height: 50%; }
.terminal-hidden { display: none !important; }
.terminal-maximized > .center, .terminal-maximized > .gutter-h { display: none; }
.terminal-maximized > .bottom { flex: 1; height: auto; }
+11 -2
View File
@@ -28,8 +28,16 @@ export function pluginTabState(view: OpenPluginView) {
state: sessions.get(view.owner)?.session.views.get(view.id)?.saveTabState?.() };
}
export async function restorePluginTab(transfer: ReturnType<typeof pluginTabState>): Promise<boolean> {
if (!transfer || typeof transfer.owner !== "string" || typeof transfer.id !== "string"
|| (transfer.document && (typeof transfer.document.path !== "string" || typeof transfer.document.id !== "string"))) {
throw new Error("Invalid tab transfer.");
}
const session = sessions.get(transfer.owner)?.session;
if (!session) return false;
if (get(pluginEditors).some(view => view.owner === transfer.owner && view.id === transfer.id
&& (transfer.document ? view.document?.path === transfer.document.path : !view.document))) {
throw new Error("This tab is already open in this window. The source tab remains open.");
}
if (transfer.document) {
if (!await openPluginDocument(transfer.document.path)) return false;
} else {
@@ -73,6 +81,7 @@ const failures = new Map<string, string>();
const errors: Record<string, string> = {};
const restarted = new Set<string>();
let queue: Promise<void> = Promise.resolve();
export function waitForPluginStartup() { return queue; }
let started = false;
let allowedPlugins: string[] | undefined;
let generation = 0;
@@ -158,7 +167,7 @@ export async function openPluginDocument(path: string, current: () => boolean =
const { owner, type, document } = match;
const existing = get(pluginEditors).find(view => view.owner === owner && view.id === type.id && view.document?.path === path && view.document.id === document.id);
if (existing) { selectPluginEditor(existing); return true; }
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon };
const view: OpenPluginView = { key: crypto.randomUUID(), owner, id: type.id, title: documentTitle(path), placement: "editor", document, icon: type.icon, draggable: true };
pluginEditors.update(views => [...views, view]); selectPluginEditor(view);
return true;
}
@@ -206,7 +215,7 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
}
if (placement === "editor") {
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: true, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
if (!existing && options) {
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
+3 -3
View File
@@ -1,9 +1,9 @@
type TextRequest = { title: string; value: string; resolve: (value: string | null) => void };
type TextRequest = { title: string; value: string; selection?: [number, number]; resolve: (value: string | null) => void };
export const dialogs = $state<{ text: TextRequest | null }>({ text: null });
export function requestText(title: string, value = ""): Promise<string | null> {
export function requestText(title: string, value = "", options: { selection?: [number, number] } = {}): Promise<string | null> {
dialogs.text?.resolve(null);
return new Promise(resolve => { dialogs.text = { title, value, resolve }; });
return new Promise(resolve => { dialogs.text = { title, value, ...options, resolve }; });
}
export function finishText(value: string | null) {
+32
View File
@@ -0,0 +1,32 @@
export type SessionDocument = { path: string; pinned: boolean; plugin?: boolean };
export type DocumentSession = { version: 1; documents: SessionDocument[]; activePath: string | null };
export const documentSessionKey = (root: string) => `runestone.document-session.${encodeURIComponent(root)}`;
const validPath = (path: unknown): path is string => typeof path === "string" && path.length > 0
&& !/[\\:\u0000-\u001f]/.test(path) && !path.startsWith("/")
&& path.split("/").every(part => !!part && part !== "." && part !== "..");
export function parseDocumentSession(raw: string | null): DocumentSession | null {
try {
const value = JSON.parse(raw ?? "null");
if (value?.version !== 1 || !Array.isArray(value.documents)) return null;
const seen = new Set<string>();
const documents = value.documents.flatMap((item: unknown) => {
if (!item || typeof item !== "object" || !("path" in item) || !validPath(item.path) || seen.has(item.path)) return [];
seen.add(item.path);
return [{ path: item.path, pinned: "pinned" in item && item.pinned === true,
...("plugin" in item && item.plugin === true ? { plugin: true } : {}) }];
});
return { version: 1, documents, activePath: seen.has(value.activePath) ? value.activePath : null };
} catch { return null; }
}
/** Reopen disk files independently so a missing file does not stop the session. */
export async function restoreDocumentSession(session: DocumentSession, open: (document: SessionDocument) => Promise<void>) {
const opened: string[] = [];
for (const document of session.documents) {
try { await open(document); opened.push(document.path); }
catch { /* Missing, renamed, or unreadable files do not block later tabs. */ }
}
return session.activePath && opened.includes(session.activePath) ? session.activePath : opened[0] ?? null;
}
+46
View File
@@ -0,0 +1,46 @@
import MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
const markdown = new MarkdownIt({ html: false });
export function linkFragment(target: string): string | null {
const index = target.indexOf("#");
if (index < 0) return null;
const fragment = target.slice(index + 1);
try { return decodeURIComponent(fragment); } catch { return fragment; }
}
function headingText(tokens: Token[]): string {
return tokens.map(token => token.children ? headingText(token.children) :
["text", "code_inline"].includes(token.type) ? token.content :
["softbreak", "hardbreak"].includes(token.type) ? " " : "").join("");
}
export function headingSlug(text: string): string {
return text.toLowerCase().replace(/[^\p{L}\p{M}\p{N}_\-\s]/gu, "").replace(/\s/g, "-");
}
/** Match rendered heading text and unique Markdown slugs, excluding code and properties. */
export function documentHeadings(contents: string): { text: string; slug: string; line: number }[] {
const source = contents.replace(/\r\n/g, "\n");
const properties = /^\uFEFF?---\n[\s\S]*?\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(source)?.[0] ?? "";
const offset = (properties.match(/\n/g) ?? []).length;
const tokens = markdown.parse(source.slice(properties.length), {});
const used = new Set<string>();
return tokens.flatMap((token, index) => {
if (token.type !== "heading_open" || !token.map) return [];
const text = headingText(tokens[index + 1]?.children ?? []);
const base = headingSlug(text);
let slug = base, suffix = 0;
while (used.has(slug)) slug = `${base}-${++suffix}`;
used.add(slug);
return [{ text, slug, line: token.map[0] + offset + 1 }];
});
}
export function headingLinkLine(contents: string, fragment: string): number | null {
if (!fragment) return 1;
const headings = documentHeadings(contents);
return (headings.find(heading => heading.slug === fragment) ??
headings.find(heading => heading.text.toLowerCase() === fragment.toLowerCase()))?.line ?? null;
}
+271
View File
@@ -0,0 +1,271 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
import { documentLinks, type DocumentLink } from "../editor/documentLinks.ts";
export type NoteLinkResolution =
| { status: "resolved"; path: string }
| { status: "ambiguous"; candidates: string[] }
| { status: "missing" | "external" };
export type Backlink = {
sourcePath: string;
line: number;
from: number;
to: number;
text: string;
target: string;
kind: "md" | "wiki";
};
export type NoteIndexIO = {
list: (folder: string) => Promise<{ rel_path: string; kind: "file" | "folder" }[]>;
read: (path: string) => Promise<string>;
};
export type NoteIndexIssue = { path: string; operation: "list" | "read"; error: string };
type IndexedNote = { contents: string; links: Backlink[] };
type Snapshot = { files: Set<string>; notes: Map<string, IndexedNote> };
type Change = (snapshot: Snapshot) => void;
export function isIndexedNote(path: string): boolean {
return /\.(?:md|markdown|mdown)$/i.test(path);
}
function normalizePath(value: string): string | null {
const parts: string[] = [];
for (const part of value.replaceAll("\\", "/").split("/")) {
if (!part || part === ".") continue;
if (part === "..") {
if (!parts.length) return null;
parts.pop();
} else parts.push(part);
}
return parts.join("/");
}
function referenceLabel(label: string): string {
return label.replace(/^\[|\]$/g, "").trim().replace(/\s+/g, " ").toLowerCase();
}
/** Read link ranges without changing the Markdown file or requiring a sidecar. */
function noteLinks(sourcePath: string, contents: string): Backlink[] {
const definitions = new Map<string, string>();
const references: { from: number; to: number; label: string }[] = [];
const comments: { from: number; to: number }[] = [];
markdownLanguage.parser.parse(contents).iterate({ enter(node) {
if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) return false;
if (["CommentBlock", "HTMLBlock", "HTMLTag"].includes(node.name)) {
comments.push({ from: node.from, to: node.to });
return false;
}
if (node.name === "LinkReference") {
const label = node.node.getChild("LinkLabel"), url = node.node.getChild("URL");
if (label && url) {
const key = referenceLabel(contents.slice(label.from, label.to));
if (!definitions.has(key)) definitions.set(key, contents.slice(url.from, url.to).replace(/^<|>$/g, ""));
}
return false;
}
if (node.name !== "Link" || node.node.getChild("URL")) return;
const label = node.node.getChild("LinkLabel");
const raw = contents.slice(node.from, node.to);
const explicit = label ? contents.slice(label.from, label.to) : "";
references.push({ from: node.from, to: node.to, label: referenceLabel(explicit && explicit !== "[]" ? explicit : raw.match(/^\[([^\]]+)\]/)?.[0] ?? "") });
return false;
} });
const links: DocumentLink[] = documentLinks(contents);
for (const reference of references) {
const target = definitions.get(reference.label);
if (target) links.push({ ...reference, target, kind: "md", targetFrom: reference.from, targetTo: reference.to });
}
const lineStarts = [0];
for (let offset = 0; offset < contents.length; offset++) if (contents[offset] === "\n") lineStarts.push(offset + 1);
return links.filter(link => {
if (comments.some(comment => link.from < comment.to && link.to > comment.from)) return false;
if (link.kind !== "wiki") return true;
let escapes = 0;
for (let offset = link.from - 1; offset >= 0 && contents[offset] === "\\"; offset--) escapes++;
return escapes % 2 === 0;
}).sort((a, b) => a.from - b.from).map(link => {
let low = 0, high = lineStarts.length;
while (low + 1 < high) {
const middle = (low + high) >>> 1;
if (lineStarts[middle] <= link.from) low = middle;
else high = middle;
}
const end = contents.indexOf("\n", link.from);
return { sourcePath, line: low + 1, from: link.from, to: link.to, target: link.target, kind: link.kind,
text: contents.slice(lineStarts[low], end < 0 ? contents.length : end).trim() };
});
}
/** An in-memory index. The workspace files remain the source of truth. */
export class WorkspaceNoteIndex {
#snapshot: Snapshot = { files: new Set(), notes: new Map() };
#revision = 0;
#generation = 0;
#changes: Change[] | null = null;
#backlinksRevision = -1;
#backlinks = new Map<string, Backlink[]>();
#pathsRevision = -1;
#paths = new Map<string, string[]>();
#names = new Map<string, string[]>();
get revision(): number { return this.#revision; }
get size(): number { return this.#snapshot.notes.size; }
clear(): void {
this.#generation++;
this.#changes = null;
this.#snapshot = { files: new Set(), notes: new Map() };
this.#revision++;
}
#change(change: Change): void {
change(this.#snapshot);
this.#changes?.push(change);
this.#revision++;
}
update(path: string, contents: string): void {
const normalized = normalizePath(path);
if (!normalized) return;
const note = isIndexedNote(normalized) ? { contents, links: noteLinks(normalized, contents) } : null;
this.#change(snapshot => {
snapshot.files.add(normalized);
if (note) snapshot.notes.set(normalized, note);
});
}
remove(path: string): void {
const normalized = normalizePath(path);
if (!normalized) return;
this.#change(snapshot => {
for (const file of snapshot.files) if (file === normalized || file.startsWith(`${normalized}/`)) {
snapshot.files.delete(file);
snapshot.notes.delete(file);
}
});
}
rename(from: string, to: string): void {
const oldPath = normalizePath(from), newPath = normalizePath(to);
if (!oldPath || !newPath || oldPath === newPath) return;
this.#change(snapshot => {
const moved = [...snapshot.files].filter(path => path === oldPath || path.startsWith(`${oldPath}/`));
for (const path of moved) {
const replacement = newPath + path.slice(oldPath.length);
const note = snapshot.notes.get(path);
snapshot.files.delete(path);
snapshot.notes.delete(path);
snapshot.files.add(replacement);
if (note && isIndexedNote(replacement)) snapshot.notes.set(replacement, { contents: note.contents, links: noteLinks(replacement, note.contents) });
}
});
}
async rebuild(io: NoteIndexIO, drafts: ReadonlyMap<string, string> = new Map()): Promise<{ committed: boolean; indexed: number; errors: NoteIndexIssue[] }> {
const generation = ++this.#generation;
const changes: Change[] = [];
this.#changes = changes;
const snapshot: Snapshot = { files: new Set(), notes: new Map() };
const errors: NoteIndexIssue[] = [];
const folders = [""];
const visited = new Set<string>();
while (folders.length && generation === this.#generation) {
const folder = folders.pop()!;
if (visited.has(folder)) continue;
visited.add(folder);
try {
for (const entry of await io.list(folder)) {
const path = normalizePath(entry.rel_path);
if (!path || (folder && !path.startsWith(`${folder}/`))) continue;
if (entry.kind === "folder") folders.push(path);
else snapshot.files.add(path);
}
} catch (error) { errors.push({ path: folder, operation: "list", error: String(error) }); }
}
const files = [...snapshot.files].filter(isIndexedNote);
for (let start = 0; start < files.length && generation === this.#generation; start += 8) {
await Promise.all(files.slice(start, start + 8).map(async path => {
try {
const contents = drafts.get(path) ?? await io.read(path);
snapshot.notes.set(path, { contents, links: noteLinks(path, contents) });
} catch (error) { errors.push({ path, operation: "read", error: String(error) }); }
}));
}
if (generation !== this.#generation) return { committed: false, indexed: snapshot.notes.size, errors };
for (const [path, contents] of drafts) {
const normalized = normalizePath(path);
if (!normalized || !isIndexedNote(normalized)) continue;
snapshot.files.add(normalized);
snapshot.notes.set(normalized, { contents, links: noteLinks(normalized, contents) });
}
for (const change of changes) change(snapshot);
this.#changes = null;
this.#snapshot = snapshot;
this.#revision++;
return { committed: true, indexed: snapshot.notes.size, errors };
}
resolve(origin: string, target: string, kind: "md" | "wiki"): NoteLinkResolution {
let path = target.trim().split("#")[0];
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
try { path = decodeURIComponent(path); } catch { /* A literal percent can occur in a file name. */ }
path = path.replaceAll("\\", "/");
if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith("//")) return { status: "external" };
const source = normalizePath(origin);
if (!path) return source && this.#snapshot.files.has(source) ? { status: "resolved", path: source } : { status: "missing" };
const folder = source?.split("/").slice(0, -1).join("/") ?? "";
const bareWiki = kind === "wiki" && !path.includes("/") && path !== "." && path !== "..";
if (this.#pathsRevision !== this.#revision) {
this.#paths = new Map();
this.#names = new Map();
for (const file of this.#snapshot.files) {
const key = file.toLowerCase(), matches = this.#paths.get(key) ?? [];
matches.push(file);
this.#paths.set(key, matches);
if (isIndexedNote(file)) {
const name = file.split("/").pop()!.toLowerCase(), names = this.#names.get(name) ?? [];
names.push(file);
this.#names.set(name, names);
}
}
this.#pathsRevision = this.#revision;
}
const withExtension = (value: string) => kind === "wiki" && !isIndexedNote(value) ? [value, `${value}.md`, `${value}.markdown`, `${value}.mdown`] : [value];
let candidates: string[];
if (bareWiki) {
const names = new Set(withExtension(path).map(name => name.toLowerCase()));
candidates = [...names].flatMap(name => this.#names.get(name) ?? []);
} else {
const relative = path.startsWith("/") ? path.slice(1) : `${folder}/${path}`;
const bases = [relative];
// A wiki folder path can name a workspace folder. Dot paths are always relative.
if (kind === "wiki" && !path.startsWith("/") && !/^\.{1,2}\//.test(path)) bases.push(path);
const paths = new Set(bases.flatMap(base => {
const normalized = normalizePath(base);
return normalized ? withExtension(normalized) : [];
}).map(value => value.toLowerCase()));
candidates = [...paths].flatMap(path => this.#paths.get(path) ?? []);
}
candidates.sort((a, b) => a.localeCompare(b));
if (candidates.length > 1) return { status: "ambiguous", candidates };
return candidates.length ? { status: "resolved", path: candidates[0] } : { status: "missing" };
}
backlinks(path: string): Backlink[] {
if (this.#backlinksRevision !== this.#revision) {
this.#backlinks = new Map();
for (const note of this.#snapshot.notes.values()) for (const link of note.links) {
const resolution = this.resolve(link.sourcePath, link.target, link.kind);
if (resolution.status !== "resolved" || resolution.path === link.sourcePath) continue;
const links = this.#backlinks.get(resolution.path) ?? [];
links.push(link);
this.#backlinks.set(resolution.path, links);
}
for (const links of this.#backlinks.values()) links.sort((a, b) => a.sourcePath.localeCompare(b.sourcePath) || a.from - b.from);
this.#backlinksRevision = this.#revision;
}
return [...(this.#backlinks.get(normalizePath(path) ?? "") ?? [])];
}
}
+5
View File
@@ -3,6 +3,11 @@ export type RenamePlan =
| { action: "error"; message: string }
| { action: "rename"; to: string };
export function renameSelection(name: string, kind: "file" | "folder" = "file"): [number, number] {
const dot = name.lastIndexOf(".");
return [0, kind === "file" && dot > 0 ? dot : name.length];
}
function parentOf(rel: string): string {
const idx = rel.lastIndexOf("/");
if (idx <= 0) {