Update editor, workspace, Git services, appearance, and project guides

This commit is contained in:
Knotty Wyvern
2026-10-11 09:41:16 -07:00
parent a8b1defb9d
commit 909894b9c8
153 changed files with 7967 additions and 775 deletions
+26
View File
@@ -79,6 +79,13 @@ Apply them automatically without requiring the user to repeat them.
For UI reviews, check changed controls against these rules.
## UI work: use shared dimensions
Use `--rs-titlebar-height` for custom window headers in the main app and settings.
Use the shared `--rs-settings-*` tokens for settings spacing, control height, headings, and descriptions.
Keep related plugin metadata and actions in compact rows. Preserve readable labels, focus indicators, and comfortable click targets.
Wrap controls at narrow widths and scroll the content area. Long settings navigation must leave room for the selected settings.
Check both themes, narrow windows, and long plugin lists after changes to shared dimensions.
## UI work: use rounded corners
Apply these rules whenever designing, implementing, modifying, or reviewing RuneStone UI.
@@ -140,3 +147,22 @@ Apply them automatically when you add, change, or review a menu.
Rich pickers and dialogs can use their own layouts when they contain search fields, descriptions, or forms.
Plugin menus should use these rules where the host API permits shared components.
## Project Management skill
For RuneStone boards and cards, use the global `runestone-project-management` skill.
Find it at `$CODEX_HOME/skills/runestone-project-management/SKILL.md`.
When `CODEX_HOME` is unset, use `~/.codex/skills/runestone-project-management/SKILL.md`.
The skill supports multiple boards and workspaces with a read-only helper.
Discover boards before task selection when the request does not identify a board.
Each plugin has its own board. Use board membership to select the project, not tags or labels.
Use board placement to select a list. Card status alone does not identify its list.
Read priority from the separate `runestone_pm.priority` detail field, never from labels or tags.
## UI work: keep attention on the work
Use the principles in [Interface design](docs/ui-design.md#design-principles) for all interface work.
Use quiet active states. Reserve strong borders and accents for controls that need attention.
Show board and view names once where possible. Keep switching and renaming as separate actions.
Use familiar icons and visual previews. Keep labels when they prevent ambiguity.
Keep accessible names, keyboard focus, and tooltips on icon controls.
+36 -55
View File
@@ -1,75 +1,56 @@
# RuneStone
A desktop workspace for writing and code.
A desktop workspace for notes, code, and project work stored in ordinary local files.
RuneStone brings Markdown notes, scripts, images, and optional plugins into one window.
Open a folder and work with the files already inside it.
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/`.
## Why RuneStone?
## What you can do
Notes and code often belong to the same project. RuneStone keeps them together,
so you can write an explanation, edit a script, and run it in the same workspace.
- Write Markdown with live formatting, editable tables, images, and Mermaid diagrams.
- Switch between Writer, source editing, Read, and Split views.
- Find files, search a workspace, and resolve changes made by other tools.
- Use the bundled Browser to view web pages beside your documents.
- Install optional Terminal, Git, Project Management, Table formulas, and other plugin ZIPs.
Your documents stay as ordinary files on disk. You can open them in other editors
and use your own tools to manage them. Workspace settings live separately in `.runestone/`.
RuneStone is under development. Windows has local test installers, but no public download location is configured.
Linux and macOS builds remain unvalidated. Language servers, crash recovery, and restoring open tabs after restart remain planned.
Plugin features require their matching packages. See the [user guide](docs/user-guide.md) for current behavior and limits.
## Features
## Install and start
- **Markdown writing:** Live formatting, source editing, split view, and read view.
- **Code editing:** A source editor for scripts, with file navigation and workspace search.
- **Images and diagrams:** Image insertion and previews, plus Mermaid diagrams.
- **Tables:** Editable Markdown tables with optional calculations through the Table formulas plugin.
- **Terminal plugin:** Shell sessions, split panes, and commands beside your documents.
- **File handling:** Adjustable auto-save and controls to resolve changes from other tools.
## Project status
RuneStone is under development, with Windows as its first target.
Local [plugin packages](docs/plugins.md) are available. Git controls, language servers,
session restoration, and crash recovery remain planned.
The [roadmap](docs/roadmap.md) shows the proposed direction, goals, and milestones.
The [user guide](docs/user-guide.md) covers current features and limitations.
## Get started
RuneStone runs on Windows 10 and 11 (64-bit). There is no public installer download yet.
If you have a supplied installer:
If the maintainer supplied a Windows installer:
1. Open `RuneStone_<version>_x64-setup.exe`.
2. Follow the setup steps.
3. Open **RuneStone** from the Windows Start menu.
4. Use the folder button to open a workspace or create one.
2. Complete setup, then open RuneStone from the Start menu.
3. Use the folder button to open a workspace.
4. Press Ctrl+N to create a file, or Ctrl+P to find an existing file.
The installer sets up RuneStone for your Windows account. You do not need a terminal or developer tools.
If Microsoft Edge WebView2 is missing, setup downloads and installs it, which needs an internet connection.
The installer needs no developer tools. It downloads WebView2 if that runtime is missing.
Keep workspace folders outside the application folder.
Press Ctrl+N to create a note or script, Ctrl+P to find a file, and Ctrl+S to save.
[Installation and updates](docs/installation.md) covers Windows setup and experimental Linux and macOS source setup.
[Release history](docs/releases.md) records the local test builds and their acceptance limits.
See the [installation guide](docs/installation.md) for setup help, updates, and removal.
To run from source, see the [Developer README](docs/development.md#run-from-source).
For feature tests, use `pnpm tauri dev` after setup.
It reloads interface changes without a full rebuild.
See [the development workflow](docs/development.md#test-changes-without-a-full-rebuild) for commands and rebuild limits.
## Find help
## Documentation
| Need | Guide |
| --- | --- |
| 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) |
Documentation lives in this repository:
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.
- [User guide](docs/user-guide.md): Editing, images, tables, terminals, and shortcuts.
- [Installation guide](docs/installation.md): Windows setup and troubleshooting.
- [Developer README](docs/development.md): Source setup, live updates, rebuild limits, and tests.
- [Release guide](docs/releases.md): Build and package the Windows installer.
- [Roadmap](docs/roadmap.md): Product direction, goals, and milestones.
## Contribute
## Contributing
Contributions can include code, documentation, reproducible bug reports, and feature proposals.
Read the [development guide](docs/development.md) for the build and test workflow,
and the [product scope](docs/product-scope.md) for detailed capabilities and boundaries.
Bug reports should include the operating system, steps to reproduce the problem,
the expected result, and any error message.
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.
## Maintainer
+13
View File
@@ -0,0 +1,13 @@
# Documentation archive
[User guide](../user-guide.md) · [Development](../development.md) · [Release history](../releases.md)
These records preserve past checks, decisions, and proposals. They do not define current behavior or authorize planned work.
| Record | Purpose |
| --- | --- |
| [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 |
| [App updating draft](app-updating-draft.md) | Unaccepted proposal for installer repair and later update checks |
| [Development notes, 0.1.8](development-0.1.8.md) | Settings windows and pasted Markdown |
+111
View File
@@ -0,0 +1,111 @@
# App updating draft
Status: Draft for review. The App updating card stays in Backlog until the user accepts this scope.
RuneStone needs an update flow that keeps workspace files, settings, plugins, and browser profiles.
Users must not uninstall RuneStone before an update or a same-version repair.
The proposed first milestone makes the installer reliable and clear. A later milestone adds update checks inside RuneStone.
## Current state
The card reports an uninstall and reinstall workflow. The project rules already require direct reinstall and update.
The Windows configuration uses a per-user NSIS installer and blocks downgrades.
The 0.1.15 release notes tell users to run the installer directly, but also identify native installer behavior as untested.
This difference needs reproduction on an installed copy before implementation.
Sources: [project rules](../../AGENTS.md#windows-installer), [Windows configuration](../../src-tauri/tauri.windows.conf.json), and [0.1.15 release notes](../release-0.1.15.md).
## Proposed first milestone
The installer detects an existing installation and defaults to reinstall or update.
It shows the installed version, package version, and destination before it changes files.
The primary action reads Update for a newer version and Reinstall for the same version.
An older package stops with a clear downgrade message.
If RuneStone is open, setup asks the user to close it after saving work.
The app must not discard unsaved files or end active terminal work without a user decision.
The installer keeps the existing installation path and application identity.
It replaces program files and bundled browser files without deleting user data.
After success, setup offers Open RuneStone.
After failure, setup identifies the failed step and offers a retry or a recovery instruction.
A retry must not require manual removal of the application or its data.
## Proposed update screen
Settings gains an Updates category with a recognizable icon and a visible label.
It shows the installed version, last check, available version, release notes, and download state.
Check for updates is a manual action in the first implementation.
Background checks remain a later option. Downloads and installation require explicit user actions.
| State | User action | Result |
| --- | --- | --- |
| No check yet | Check for updates | Read the selected release channel |
| Current version | Check again | Show that no newer release exists |
| Update available | Download update | Show progress and allow cancellation |
| Download complete | Restart and update | Save work and close the app before setup |
| Open work prevents restart | Return to RuneStone | Keep the downloaded package for later |
| Offline or failed download | Retry | Keep the installed app usable |
| Invalid package | Download again | Do not run the invalid package |
The update service must compare numeric version parts, including build numbers above 99.
It must not mistake a same-version repair for a newer release.
The default channel excludes trial releases. A future trial channel requires an explicit choice.
## Release source and package checks
The in-app milestone needs a chosen release source, stable metadata format, and publisher verification method.
The proposed source is the existing Gitea service, with a dedicated application release contract.
Plugin download support does not establish an application update contract.
The contract must identify the version, Windows architecture, installer URL, file size, digest, release notes, and release channel.
The app validates the downloaded bytes and publisher before execution.
Transport security and a digest alone do not prove the publisher when the source itself changes.
Signing keys and credentials stay outside the repository. The build process must document key recovery and rotation.
The app rejects a mismatched version, architecture, digest, or signature.
It does not run an arbitrary URL as an installer.
If private releases need authentication, the credential flow requires a separate design before implementation.
## Data and plugin behavior
| Data | Required result |
| --- | --- |
| Workspace files and hidden workspace metadata | Preserve all files and paths |
| Application settings and recent workspaces | Preserve values and reopen behavior |
| Installed plugins and plugin settings | Preserve packages, enable states, and stored data |
| Browser profiles, cookies, history, and bookmarks | Preserve data and profile identity |
| Unsaved documents and active terminals | Resolve before restart, without silent data loss |
Application updates do not silently replace third-party plugins.
Plugin update support stays outside this card. Existing plugin ZIP installation remains separate.
An incompatible plugin should remain installed but inactive, with a clear explanation, if compatibility checks become necessary.
That compatibility policy requires defined host requirements before enforcement.
## Acceptance checks
| Scenario | Pass condition |
| --- | --- |
| Clean installation | Setup installs and opens RuneStone |
| Same-version reinstall | Reinstall is the default action and restores program files |
| Upgrade from the previous build | Setup updates directly without an uninstall step |
| Older installer | Setup blocks the downgrade |
| Custom installation path | Setup uses the existing path |
| Populated workspace and user data | Before and after file hashes and settings match |
| App open with unsaved work | The user can return to work without losing edits |
| Failure or cancellation | User data remains intact and retry is possible |
| Download or publisher check failure | The app does not execute the package |
| Successful update | The app reports the installed version and opens normally |
Test the installer in a disposable Windows profile with representative workspace, plugin, and browser data.
Automated source checks do not replace the native installer checks.
## Decisions before To Do
1. Approve installer repair as the first milestone, or include the update screen in the first card.
2. Choose the application release source and its public or private access model.
3. Choose the publisher verification and signing process before an in-app installer launch.
The recommended first card covers installer repair and native regression checks.
The update screen can follow after the release source and signing decisions.
This draft does not authorize updater implementation or move the card into To Do.
+19
View File
@@ -0,0 +1,19 @@
# Historical development notes: 0.1.8
[Archive](README.md) · [Current development guide](../development.md)
## Settings windows and pasted Markdown
Desktop Settings opens in a separate movable window for each workspace window.
Repeated requests focus the existing Settings window.
Closing the workspace window also closes its Settings window.
Settings opened before a workspace closes when that workspace opens, so plugin context cannot remain stale.
Saved preferences synchronize across windows. The browser preview keeps the Settings dialog.
The separate window has dedicated native permissions and loads only the browser settings contribution.
Plugin installation still lists all installed plugins.
Live Markdown formatting refreshes when background parsing finishes after a large paste.
Run `scripts/markdownPaste.smoke.mjs` against the development server to check pasted source and rendered formatting.
Run `scripts/settingsWindow.smoke.mjs` to check the Settings layout, save synchronization, and mocked native requests.
The browser checks do not test native title-bar movement or desktop clipboard behavior.
+55
View File
@@ -0,0 +1,55 @@
# Kanban changes for October 8 2026
This pass covers eight To Do cards across RuneStone, RuneStone Project Management, and RuneStone_Git.
The global project management helper read all three boards without data issues.
Selection used board placements and the separate priority field.
The App updating card received a [draft](app-updating-draft.md) and remains in Backlog.
## Changes
| Board | Card | Result |
| --- | --- | --- |
| RuneStone | Autocorrect only shows errors | Plain editable text permits the native spelling menu. Selection and table action menus remain available. |
| RuneStone | New file button | New file accepts the complete name without adding an extension. Rename includes the extension. |
| RuneStone | Monospace font is too big | Both code layouts use the shared 13px size and 21px line height. |
| RuneStone | Themes and theme switching | GPT, Claude, Sakura, and RuneStone support light and dark modes. Terminal uses green on black. |
| RuneStone | Users need the ability to clear specific cookies | Settings lists and filters cookies and history for each profile, with individual removal. |
| Project Management | Text box for adding new cards is somewhat broken | The composer uses the empty list space above the Add control. |
| Project Management | Add new card UI persists when not in use | Focus changes hide the composer and retain its draft. Cancel, view changes, board changes, and disposal discard drafts. |
| Git | Git interface missing functions | Visible push and pull controls accompany separate collapsible Changes and Graph sections. |
## Source checks
RuneStone passes its type checks with zero errors or warnings and all 195 unit tests.
The native suite passes 75 tests. Three existing tests remain ignored because they require external fixtures or services.
Git passes 11 native fixture tests, four plugin unit tests, source compilation, and sidebar browser checks.
The Git checks include upstream selection, divergence, dirty files, merge history, and errors.
Project Management passes type checks, 98 unit tests, and all 119 browser tests.
Its current source compiles, and both compiled-plugin browser tests pass.
The first compilation attempt stopped on Git ownership checks. A process-local safe-directory setting permits this known checkout.
No global Git trust setting changed.
Browser runtime checks pass all 35 unit tests, syntax checks, and the native Electron smoke test.
Individual removal preserves other cookie paths, other history entries, other profiles, bookmarks, and open tabs.
The host browser checks cover filters, busy controls, errors, profile changes, and delayed responses.
The cookie implementation uses the [Electron Cookies API](https://www.electronjs.org/docs/latest/api/cookies) to expire the selected cookie's exact domain and path.
Editor and menu checks cover exact filenames, extension changes, duplicate-name protection, fonts, spelling event dispatch, and shared menus.
Visual checks cover narrow settings and light and dark themes.
The appearance check covers all palettes, persistence, cross-window changes, and existing and newly opened code editors.
The initial Terminal check found gold brackets. The theme now sets all bracket colors to green. Separate editor theme IDs restore normal syntax colors after Terminal mode.
## Limits and review
Native spelling suggestions and actual correction still need desktop acceptance.
The Git graph uses text topology and shows at most 100 commits.
Push and pull require a configured upstream and existing Git authentication. Pull permits only fast-forward updates.
The updater remains a draft. This pass does not implement its proposed milestones.
Implementation-ready cards move to Review after their checks pass. Done remains reserved for user acceptance.
Build work must use GPT-6.1 Sol with medium reasoning, as requested.
It must produce the installer and changed Project Management and Git ZIPs.
The installer needs the rebuilt Browser runtime. A separate Browser plugin ZIP is unnecessary.
Source checks retain the existing versions until each distributable build starts.
@@ -0,0 +1,39 @@
# Menu, theme, and Git graph changes
These changes cover three To Do cards from the RuneStone and RuneStone_Git boards on October 8, 2026.
The [local test builds](../release-0.1.17.md) are RuneStone 0.1.17 and Git 0.1.4.
## Changes
| Card | Result |
| --- | --- |
| 591c856a-2dc8-40a8-b656-b1d709c59114 | WebView2 supplies spelling suggestions to the shared menu. Native commands apply corrections. |
| 8a2f3bef-dec0-4b8e-8cc8-923a204386ec | Claude follows Anthropic colors and font stacks. Sakura uses the card palette and light mode. GPT and Terminal themes are removed. |
| 7d194eeb-fd9c-4116-b716-f8b96a3b1de8 | Git history draws commit nodes and parent links, with branches, tags, messages, authors, and dates. |
Saved GPT and Terminal selections migrate to RuneStone with their previous light or dark mode.
Saved dark Sakura selections migrate to light Sakura.
Claude uses local Lora and Poppins fonts, with Georgia and Arial fallbacks. It does not download fonts.
Sakura syntax colors depend on the tokens that each language supplies.
The spelling bridge validates the window, request, and enabled command before it acts.
Dismissal completes the native request. Unsupported targets retain their native menu.
The graph shows at most 100 commits. Dashed links mark parents outside that history.
The Git ZIP requires the matching host build. Earlier hosts show an update message.
## Checks
- Host source check: no errors or warnings.
- Host unit tests: 198 passed.
- Native tests: 78 passed, three ignored.
- Frontend production compilation: passed.
- Git unit tests: five passed. Plugin compilation and sidebar, UI, and host browser checks passed.
- Appearance checks: migration, palette colors, font stacks, window sync, code editors, and 360px settings passed.
- Shared menu checks: both themes, keyboard navigation, native command mapping, and fallback passed.
Screenshots and check logs are in `.audit/`. Git screenshots are in `../RuneStone_Git/output/`.
The native Windows check confirmed real WebView2 commands in the shared menu. Native Undo restored Writer text in an isolated test profile.
That profile supplied no spelling suggestions. Correction and undo with a spelling suggestion still need desktop acceptance.
The reusable check is `scripts/spellingNative.smoke.mjs`. Set `REQUIRE_NATIVE_SUGGESTIONS=1` to require an actual suggestion.
Cards move to Review after their checks pass. Done remains reserved for user acceptance.
+110
View File
@@ -0,0 +1,110 @@
# Kanban work, October 8, 2026
## Scope and inspection
Workspace: `D:/Users/KnottyWyvern/Documents/RuneStone`.
The RuneStone board contains six selected To do cards. The Project Management board contains eight.
All 14 selected cards are unblocked.
Selection uses each board placement, not the shared card status.
Command from the RuneStone checkout: `node ../RuneStone_ProjectManagement/.agents/skills/runestone-project-management/scripts/inspect.mjs boards --workspace .`.
The first helper run failed because the renamed plugin checkout lacked usable dependencies (`ERR_MODULE_NOT_FOUND: yaml`).
The documented frozen-lockfile install restored dependencies.
The recent sandbox workspace contained no boards. The RuneStone workspace contained both requested boards.
The helper then retrieved both boards and all 14 cards with exit code 0 and no data issues.
Manual card retrieval was not necessary. The initial dependency failure remains part of this test record.
The shell sandbox also failed before command execution. Authorized commands ran outside that broken sandbox.
## Assignments
Related cards share an agent when their behavior or files overlap. These cards describe distinct outcomes, not confirmed duplicates.
Keep each card and its acceptance criteria. Do not delete or archive cards solely to group implementation.
The coordinator owns board updates, the skill, this record, and integration checks.
| Group | Card IDs | Model and effort | File ownership and sequence |
| --- | --- | --- | --- |
| Tabs and ribbon | bee9f324, c8321a48, d0850861 | Astra 6 high | Workbench, tab/pane layout, related smoke tests |
| Settings density | d8c20c7d, 2a509815 | Sol 6.1 medium | Settings windows, plugin list, dedicated tests |
| Repeated paste | 68136a13 | Sol 6.1 medium | LiveWriter, clipboard lifecycle, paste regression |
| Card details | 32f33744, 30a4c620, ed978e3d, 57074b19 | Astra 6 high | PM detail/editor UI and styles, before other PM groups |
| Card transfer | 7e41dc9e | Astra 6 high | PM board/store/UI, after card details |
| Board controls | 6369fc91, fe7e86e4 | Luna 6 max | PM board title/menu, after transfer releases UI ownership |
| Image viewer | 68fd3750 | Sol 6.1 medium | PM image viewer, description preview, styles, and image tests |
Only one agent edits each file at a time. Separate functions do not imply separate ownership.
Agents preserve all existing uncommitted changes. They do not reset files or commit unrelated work.
The coordinator moves cards to Review after their relevant checks pass. Done requires user acceptance.
The initial implementation scope did not include distributable builds or version changes.
## Skill checks
The six board-helper tests pass, including multiple workspaces, placements, migration conflicts, and read-only behavior.
The revised skill passes the prose lint at 0.97 issues per 100 words.
The Python format validator first failed because PyYAML was absent. It passed after a temporary dependency install.
## Host review results
All six RuneStone cards moved to Review.
The tab bar uses the available width and keeps its new-tab button beside the tabs.
Closing the last tab leaves one New tab. The two misleading ribbon launchers are removed.
Settings and the main window share their header height. Plugin rows use shared spacing tokens.
The paste fix accepts clipboard line endings and stops synchronous edits from returning to their source editor.
Checks pass: host type checks with zero errors or warnings, and all 191 unit tests.
Browser checks pass for tab order, plugin access, menu consistency, saved layout, settings density, settings titlebar, and settings windows.
Paste checks pass for 12 repeated clipboard cycles, saved source, editor reopen, line-ending variants, undo, and 5,000 formatted sections.
Visual checks cover light and dark themes, an 880-pixel tab bar, and settings widths down to 360 pixels.
Native desktop window calls used browser mocks. Native titlebar behavior still needs user acceptance.
## Project Management review results
The four card-detail cards moved to Review.
Description editing stays inside the card. Saved Markdown opens formatted.
Detail hints sit inside buttons. Priority choices use colored icons in a picker beside the trigger.
Type checks, unit tests, and 11 focused browser tests pass for these changes.
## Source review result, before packaging
All 14 selected cards are in Review. The helper confirmed their exact board placements after the updates.
No cards moved to Done. No cards were deleted or archived.
Seven subagents handled the seven groups with one writer for each file.
The small board-control group used Luna 6 max after source review confirmed its limited scope.
The other assignments used Astra 6 high or Sol 6.1 medium as shown above.
Card transfer now preserves the card identity, body, metadata, and unrelated board placements.
The image viewer opens from saved descriptions and supports outside-click dismissal, Escape, focus restoration, and image overlays.
Board menu actions now have icons. The smaller title pencil appears on hover or keyboard focus.
Final checks:
- RuneStone type checks: zero errors and warnings. All 191 unit tests pass.
- Host browser checks include installation, removal, menus, tabs, layout, settings, paste, and undo.
- Project Management type checks and compilation pass. All 101 unit tests and all 103 browser tests pass.
- The six skill-helper tests and the skill format validator pass.
- Both repository patches pass the whitespace check.
The first complete PM browser run exposed seven outdated or brittle test expectations.
Corrections scope deadline inputs to their field region, expect the saved description preview, and establish keyboard focus before checking its indicator.
The next complete run passed all 103 tests. The host install smoke also needed its removed ribbon selector replaced with the command API.
These test corrections retain the existing behavior checks.
Compiled PM output supports bundled-plugin tests. No installer or release ZIP was produced during source review.
Source review used RuneStone `0.1.12` and Project Management `0.2.17`.
The automated browser checks use mocked host calls. Native desktop behavior still needs user acceptance.
Test output is saved under the plugin repository's ignored `.audit/kanban-review-2026-10-08/` directory.
Original card backups are in `.runestone/agent-work-2026-10-08/backups/` in the RuneStone workspace.
Prose lint for this record: 1.45 issues per 100 words.
## Test builds requested after source review
The user requested distributable builds for desktop testing.
RuneStone 0.1.13 is available as `src-tauri/target/release/bundle/nsis/RuneStone_0.1.13_x64-setup.exe`.
Project Management 0.2.18 is available as `../RuneStone_ProjectManagement/plugin-packages/runestone.pm-0.2.18.zip`.
See the [installation notes](../release-0.1.13.md).
Both builds completed and passed artifact integrity checks. Previous release files remain intact.
The installer includes the existing browser runtime. Its application version is 0.1.13 and downgrades remain disabled.
The plugin ZIP has its manifest at the archive root. Its recorded file hashes match its contents.
Post-package checks passed the PM type check, 101 unit tests, and 103 browser tests.
Native host tests passed 63 tests, with three ignored.
The 14 cards remain in Review for user acceptance.
+94
View File
@@ -0,0 +1,94 @@
# Build and package RuneStone
[Development](development.md) · [Release history](releases.md) · [Installation](installation.md)
This guide is for maintainers. Users install a supplied package through the installation guide.
## Build the Windows installer
Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source).
The commands below use the checked-in dependency versions.
```sh
pnpm install --frozen-lockfile
pnpm check
pnpm test
pnpm build:installer
```
The last command builds the interface, compiles the release app, and creates an NSIS setup executable.
The first build needs internet access to download the packaging tools and the WebView2 bootstrapper.
Find the installer in:
```text
src-tauri/target/release/bundle/nsis/RuneStone_<version>_x64-setup.exe
```
Distribute this setup file. Users do not need the repository, a local server, or build tools.
Build output stays outside version control.
## Installer settings
Tauri automatically merges `src-tauri/tauri.windows.conf.json` into the base configuration on Windows.
This file selects NSIS for ordinary `pnpm tauri build` commands too.
It uses the existing RuneStone icon and installs the app for the current Windows account.
Tauri supplies the setup screens, Start menu shortcut, launch option, and uninstaller.
The installer includes the WebView2 bootstrapper.
If WebView2 is missing, setup downloads the runtime. An existing runtime needs no setup download.
The configuration blocks version downgrades.
It does not register document types or start RuneStone when Windows starts.
See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options.
## Prepare a release
Each project uses its own `zz.yy.xx` version. Routine source edits and checks retain the current version.
Increase `xx` once when producing a new completed installer or plugin ZIP. Failed attempts do not consume a version.
Keep version fields consistent, and restore them if no build completes.
Increase `yy` or `zz` only for a user-directed release, then reset the lower fields as defined in [the version policy](../AGENTS.md#versioning).
Publishing an existing artifact does not change its version.
1. Set the same version in `package.json`, `src-tauri/Cargo.toml`, and `src-tauri/tauri.conf.json`.
2. Update `src-tauri/Cargo.lock` with Cargo if the package version changed.
3. Run the checks and build command above.
4. Test the installer on a clean Windows account with the checks below.
5. Attach the setup file and release notes to the repository release or your chosen download page.
Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity.
No public download location or automatic release upload is configured yet.
After you publish an installer, add its download link to the README.
Local installers are unsigned until the maintainer configures Windows code signing.
Use [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) before public distribution.
## Installer checks
| Check | Expected result |
| --- | --- |
| Install on an account without Node.js or Rust | Setup completes and RuneStone opens |
| Install without WebView2, with internet access | Setup installs the runtime and RuneStone opens |
| Open RuneStone from the Start menu | The app opens without a terminal or development server |
| Create a workspace outside the installation folder | Notes save and reopen |
| Install a newer version | Setup updates the app and preserves workspace files |
| Reinstall the same version | Setup defaults to reinstall and preserves workspace files and settings |
| Try to install an older version | Setup blocks the downgrade |
| Remove RuneStone through Windows Settings | The app and shortcuts disappear, and the separate workspace remains |
These checks require a Windows test account or virtual machine. A successful build alone does not confirm them.
## Experimental platform 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.
On macOS, a local application bundle can use:
```sh
pnpm tauri build --bundles app -- --locked
```
Tauri places the bundle under `src-tauri/target/release/bundle/macos/`.
This command is a test route, not a validated RuneStone release workflow.
Check the [Tauri application bundle guide](https://v2.tauri.app/distribute/macos-application-bundle/) for platform packaging behavior.
Signing, notarization, architecture coverage, Browser packaging, and desktop acceptance remain unresolved for RuneStone on macOS.
+1 -1
View File
@@ -54,4 +54,4 @@ Surface and provider APIs are available. Automatic context-source registration,
External plugins retain RuneStone's existing full-application trust level. This API does not add a permission sandbox.
See [the implementation](../src/lib/completion/contracts.ts), [host tests](../scripts/completion.spec.ts), and the [plugin trial guide](../../RuneStone_LocalModel/docs/trial-guide.md).
See [the implementation](../src/lib/completion/contracts.ts), [host tests](../scripts/completion.spec.ts), and the [plugin trial guide](../../RuneStone_LocalAutocomplete/docs/trial-guide.md).
+13 -25
View File
@@ -1,6 +1,9 @@
# Developer README
# Development guide
[Back to RuneStone](../README.md)
[RuneStone](../README.md) · [Interface design](ui-design.md) · [Build and package](builds.md) · [Plugin development](plugins.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).
## Test changes without a full rebuild
@@ -44,13 +47,13 @@ The frontend uses port 1420, and Tauri loads `http://localhost:1420`.
| Change or task | Action |
| --- | --- |
| Svelte, TypeScript, or CSS under `src/` | Save the source file. Vite updates the interface without a Rust rebuild. |
| Feature source under `plugins/` | Run `pnpm build:plugins`, then uninstall and install the changed package through Settings. |
| Feature source under `plugins/` | Run `pnpm build:plugins`, then remove the old package and install the changed ZIP through Settings. |
| Table formulas source in `../RuneStone_TableFormulas/` | Install that checkout's dependencies, then run `pnpm build:plugins` in RuneStone. Reinstall the changed ZIP through Settings. |
| Rust code under `src-tauri/src/` | Save the source file. Tauri rebuilds the changed Rust code and restarts the app. |
| Rust dependencies or build settings | Allow Cargo to compile the affected dependencies. These changes can take longer. |
| JavaScript dependencies after a pull or branch change | Stop development, run `pnpm install --frozen-lockfile`, then start `pnpm tauri dev` again. |
| Tauri configuration, capabilities, or Vite configuration | Restart `pnpm tauri dev` to check the new settings. Native changes can require compilation. |
| Release or installer behavior | Use the [release guide](releases.md). Packaging requires a release build. |
| Release or installer behavior | Use the [build guide](builds.md). Packaging requires a release build. |
Keep `src-tauri/target/` between sessions so Cargo can reuse its build cache.
Do not run `cargo clean` as part of normal feature tests.
@@ -68,20 +71,21 @@ Use the [Linux readiness guide](linux.md) for Linux setup, native tests, and pac
See the setup steps below to install dependencies and run the desktop app.
See the [roadmap](roadmap.md) for goals and milestones. See the [product scope](product-scope.md) for capabilities and architecture constraints.
Agent instructions and UI design rules live in [AGENTS.md](../AGENTS.md).
See the [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.
## Run from source
These steps are for developers. App users can use the [Windows installer](installation.md).
These steps are for developers. App users can use a supplied [Windows installer](installation.md). Linux and macOS source setup remains experimental.
### Requirements
- Node.js 22.12 or later and pnpm
- Node.js 24 and pnpm 10
- A current stable Rust toolchain
- Microsoft C++ Build Tools and Microsoft Edge WebView2 on Windows
Use the [Tauri prerequisites guide](https://v2.tauri.app/start/prerequisites/) to install the Windows build tools and Rust toolchain.
Use the [Tauri prerequisites guide](https://v2.tauri.app/start/prerequisites/) for native build dependencies.
The [installation guide](installation.md) has separate Windows, Linux, and macOS routes.
1. Download or clone this repository.
2. Open a terminal in the repository folder.
@@ -89,7 +93,7 @@ Use the [Tauri prerequisites guide](https://v2.tauri.app/start/prerequisites/) t
4. Run `pnpm tauri dev`.
5. Use the folder button in the app to open a workspace or create one.
See the [release guide](releases.md) to build a Windows installer.
See the [build guide](builds.md) to build a Windows installer.
## Checks
@@ -182,19 +186,3 @@ Read Rust errors in the terminal that runs `pnpm tauri dev`.
In the Windows development window, press Ctrl+Shift+I to open the web inspector.
Use its console for frontend errors.
See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector).
## RuneStone 0.1.8: Settings windows and pasted Markdown
Desktop Settings opens in a separate movable window for each workspace window.
Repeated requests focus the existing Settings window.
Closing the workspace window also closes its Settings window.
Settings opened before a workspace closes when that workspace opens, so plugin context cannot remain stale.
Saved preferences synchronize across windows. The browser preview keeps the Settings dialog.
The separate window has dedicated native permissions and loads only the browser settings contribution.
Plugin installation still lists all installed plugins.
Live Markdown formatting refreshes when background parsing finishes after a large paste.
Run `scripts/markdownPaste.smoke.mjs` against the development server to check pasted source and rendered formatting.
Run `scripts/settingsWindow.smoke.mjs` to check the Settings layout, save synchronization, and mocked native requests.
The browser checks do not test native title-bar movement or desktop clipboard behavior.
+86
View File
@@ -0,0 +1,86 @@
# Images, diagrams, and tables
[User guide](../user-guide.md) · [Terminal guide](terminal.md)
## Insert and edit images
Drag a workspace image from the navigator into a Markdown editor to insert a
relative link to the existing file. An “Insert image” hint marks the editor.
Escape cancels the drag. Dropping files from the system file explorer or pasting
images copies them into `attachments/` with unique filenames. Undo removes the
inserted links while keeping the image files.
In Writer, image Markdown stays hidden until you choose **Edit image source**. The image remains visible while you edit. Hide it again with the same button,
Escape, or by moving the cursor away. Click an image to select it, then
right-click or press Shift+F10 for copy image, copy Markdown, swap image, remove
image, zoom, edit source, open in a new tab, copy path, and show in Explorer.
Remove image or Delete removes only that embed from the note and supports undo.
Zoom supports fit, magnification and Escape to close, including in Split and Read.
## Edit table contents
Tables keep readable column widths and render `<br>` as cell line breaks.
Hover beside a table's right edge to add a column, or below its bottom edge to
add a row. Clicking a cell edits its contents. Wide tables scroll within the document.
### Move rows or columns
Grips appear on hover or keyboard focus above columns and beside body rows.
Drag a grip to reorder: a preview follows the pointer, the source row/column
stays highlighted, and a line marks the drop position. Drag near an edge
to scroll, or press Escape to cancel. Focus a grip and use arrow keys to move it.
Row moves keep the Markdown header fixed. Columns carry their alignment with them.
### Select, copy, or format cells
Drag across cells or Shift+click to select a rectangle, then right-click for
cut/copy/paste, bold, italic, strikethrough, highlight, code, math, comment,
clear formatting, alignment, clear cells, and delete cells. Clipboard shortcuts,
Ctrl+B/I, Shift+arrow selection, and undo/redo work on the selected cells.
TSV or Markdown tables paste as a grid and expand the table when needed.
Alignment applies to selected columns, as required by Markdown. Clear empties
contents; Delete removes complete selected rows/columns, or shifts a partial
selection left. Math stores inline `$…$` syntax. Comments use `%%…%%` and are
hidden in Read mode. Each operation can be undone in one step.
### Work with text inside a cell
Right-clicking text within a cell preserves the selected words and offers note
links, external links, workspace search, extraction to a new note, formatting,
rich/plain-text paste, and Select all. Extraction saves the selected Markdown
in a new file and replaces the selection with a note link. Undo restores the
original text without deleting the new note. Row and Column submenus insert,
move, duplicate, and delete at the clicked cell. Column moves keep alignment. Sorting is stable and natural (2 before 10), leaves blanks last, and keeps the
header fixed. Context-menu actions and table edge buttons have matching icons.
## Calculate with Table formulas
Install and enable the optional Table formulas plugin before using these calculations.
Table formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`,
`=SUM(B2:B10)`, or `=ROUND(B2/3, 2)`. Columns use A, B, …, AA. Row 1 is
the header, so the first data row is 2. References stay inside the current table.
Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`.
Functions include SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND.
Separate function arguments with commas: `=AVERAGE(B2,C2)` averages two cells.
A colon selects a range: `=AVERAGE(B2:C2)`.
Aggregates ignore text and blank cells. Arithmetic treats blank cells as zero.
Results recalculate in Writer, Split, and Read. Click a result to edit its
formula; Enter commits it and Tab moves to the next cell. The Formulas control
below each table explains the syntax, and the active cell shows its address.
Invalid formulas, missing cells, and circular references display error labels.
Markdown stores the formula itself, so other apps display readable source.
Use code formatting or `\=` to keep formula-like text literal. References are
positional: copying, inserting, deleting, sorting, or moving cells does not
rewrite addresses. Cross-table references and automatic fill are not supported.
## Read diagrams and document properties
The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks,
code blocks and reference images. Frontmatter sits in a collapsed Properties
section. Wiki links, note callouts and locally rendered Mermaid diagrams are
supported in Writer, Split and Read. Diagram source remains available to copy. Invalid diagrams show a message and their source. Toolbar icons show tooltips
on hover or keyboard focus; Split view stacks vertically in narrow panes.
+54
View File
@@ -0,0 +1,54 @@
# Terminal guide
[User guide](../user-guide.md) · [Install a plugin](../plugins.md#install-a-plugin)
Install and enable the Terminal plugin to use these controls. The shell runtime must exist on your computer.
## Open and arrange terminals
Ctrl+` or Ctrl+J shows or hides the terminal, preserving sessions and scrollback.
New Terminal (Ctrl+Shift+`) creates an independent shell; Split (Ctrl+Shift+5)
adds a resizable pane in the active group and inherits its current directory/profile.
The terminal list appears only when multiple sessions exist. Kill terminates a
session; Delete does the same while a terminal-list entry has focus. Maximize
and Restore change the panel size without restarting shells.
## Choose a shell and its settings
The dropdown immediately beside New Terminal offers installed PowerShell,
PowerShell 7, Git Bash, Command Prompt, and Bash profiles, a default-profile
picker, terminal settings, tasks, and separate terminal windows
(Ctrl+Shift+Alt+`). Font size, scrollback, cursor blinking, and default profile
persist locally. New terminals inherit the app environment, including PATH.
## Run scripts and navigate commands
More terminal actions clears scrollback, runs selected editor text, or saves
and runs the active script. Supported runners include Python, JavaScript,
PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes
must be installed. Recent-command (Ctrl+Alt+R) and directory (Ctrl+G) pickers
work while the terminal is focused. Ctrl+Up/Down navigates prompt markers.
History is kept in memory for the current dock; PowerShell/Bash report commands
after completion, while Command Prompt captures submitted text at its prompt.
## Configure workspace tasks
Configure Tasks creates/opens `.runestone/tasks.json`. Its `tasks` array contains
objects with `label`, `command`, and an optional `profile` ID (`powershell`,
`pwsh`, `git-bash`, `cmd`, or `bash`). Run Task starts the chosen command in its
own terminal at the workspace root. Tasks run only when explicitly selected.
## Use debugging and dictation tools
JavaScript Debug Terminal starts a Node.js REPL with a local inspector on an
available port. Attach an external debugger using the printed address.
RuneStone does not provide VS Code's debugger or automatic debug attachment.
Start Dictation invokes Windows voice typing (Win+H) in the focused terminal;
Windows microphone/voice-typing configuration is required. Other platforms
use their operating system's dictation shortcut.
## Close detached terminals
Closing a detached terminal window terminates its sessions. Switching workspace
closes detached terminal windows and ends the old workspace's sessions.
+71
View File
@@ -0,0 +1,71 @@
# Appearance and custom themes
[User guide](../user-guide.md) · [Interface design](../ui-design.md)
Open Settings → Appearance to choose RuneStone, Claude, Sakura, or an installed custom theme.
RuneStone and Claude offer light and dark appearances. Sakura uses light only.
Claude uses local Lora and Poppins fonts, with Georgia and Arial fallbacks. It does not download fonts.
## Create a theme
1. Choose Export theme template.
2. Edit the saved JSON file in a text editor.
3. Choose Install theme and select the file.
The file must be smaller than 64 KiB. Both `light` and `dark` need `bg`, `text`, and `accent` colors.
Use hexadecimal colors with 3, 4, 6, or 8 digits. The example supplies complete surface and text colors for both modes.
```json
{
"schema": 1,
"id": "harbor",
"name": "Harbor",
"light": {
"bg": "#f3f6f8",
"bg-elevated": "#ffffff",
"bg-active": "#dfe9ef",
"border": "#bccdd8",
"text": "#223344",
"text-dim": "#526778",
"text-strong": "#102536",
"accent": "#14658f",
"selection": "#b5d9ef"
},
"dark": {
"bg": "#14232e",
"bg-elevated": "#1b2d3b",
"bg-active": "#294354",
"border": "#405b6d",
"text": "#e0eaf0",
"text-dim": "#a3bac8",
"text-strong": "#f5fafc",
"accent": "#81c8ed",
"selection": "#315d77"
}
}
```
The ID starts with a lowercase letter and permits lowercase letters, numbers, and hyphens, up to 64 characters.
The visible name permits up to 80 characters. Reinstalling the same ID replaces that theme's colors.
Unknown color keys or invalid values stop installation with an error.
## Available colors
| Keys | Use |
| --- | --- |
| `bg`, `bg-elevated`, `bg-active`, `border` | Surfaces, selected controls, and boundaries |
| `text`, `text-dim`, `text-strong` | Normal, secondary, and prominent text |
| `accent`, `accent-2`, `selection` | Links, accents, and editor selection |
| `error`, `warn`, `warn-hot`, `ok`, `special` | Messages and syntax colors |
Omitted optional colors use the RuneStone defaults for that appearance.
The theme file contains color values, without scripts, style rules, or plugin code.
## Share or remove a theme
With a custom theme selected, Export theme template saves its current definition.
Share that JSON file with another user, who can install it through Appearance.
Remove custom theme removes the selected definition and returns to RuneStone colors.
Themes stay in this device's application preferences and apply across workspaces.
Check normal text, secondary text, links, focus indicators, and selections in both appearances before sharing a theme.
+75 -30
View File
@@ -1,47 +1,92 @@
# Installation guide
# Installation and updates
[Back to RuneStone](../README.md)
[RuneStone](../README.md) · [User guide](user-guide.md) · [Release history](releases.md)
| Platform | Current route |
| --- | --- |
| Windows 10 or 11, Intel/AMD 64-bit | Supplied local test installer |
| Linux | Experimental source setup. Native build and installation checks remain unvalidated. |
| macOS | Experimental source setup. Native build and installation checks remain unvalidated. |
No public download location is configured. Get a Windows installer from the maintainer who supplied your test release.
Linux and macOS do not yet have a validated RuneStone download, supported version range, or architecture matrix.
## Install on Windows
RuneStone supports Windows 10 and 11 on 64-bit Intel and AMD computers.
The installer contains the app and its interface. You do not need developer tools or a terminal.
There is no public download yet. Get the setup file from the maintainer who supplied your release.
1. Save `RuneStone_<version>_x64-setup.exe` to Downloads.
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.
1. Save `RuneStone_<version>_x64-setup.exe` to your Downloads folder.
2. Double-click the file.
3. Follow the setup steps.
4. Open **RuneStone** from the Windows Start menu.
5. Use the folder button to open a workspace or create one.
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.
Keep the default installation folder unless you need a different location.
Setup installs the app for your Windows account and adds a Start menu shortcut.
If WebView2 is missing, setup downloads and installs it. Keep your internet connection active until setup finishes.
## Update or reinstall on Windows
## Update RuneStone
1. Save your open documents.
1. Save your documents.
2. Close all RuneStone windows.
3. Open the installer for the newer version.
4. Follow the setup steps.
3. Open the installer for the same or a newer version.
4. Complete setup.
The installer replaces the app. Your workspace files stay in their current folders.
Setup blocks older versions from replacing a newer version.
Run the installer directly. An existing installation defaults to reinstall, including the same version.
You do not need to uninstall first. Setup preserves workspace files and settings and blocks version downgrades.
The [release notes](releases.md) record which installer checks still need desktop acceptance.
## Try the source on Linux
This route is for developers who can diagnose an experimental build.
1. Install Node.js 24, pnpm 10, and stable Rust.
2. Install the [Tauri system packages for your distribution](https://v2.tauri.app/start/prerequisites/#linux).
3. Download or clone RuneStone into a Linux folder.
4. Open a terminal in that folder and run the commands below.
```sh
pnpm install --frozen-lockfile
pnpm tauri dev
```
Run the app inside your graphical desktop session. Do not copy Windows dependency or build folders into the Linux checkout.
The [Linux readiness guide](linux.md) contains the Debian/Ubuntu package example, desktop checks, and experimental Debian/AppImage packaging steps.
No native Linux test result is recorded yet.
## 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
pnpm tauri dev
```
Tauri permits Command Line Tools for desktop development. See its [macOS prerequisites](https://v2.tauri.app/start/prerequisites/#macos).
RuneStone does not yet have a tested macOS installer, signing setup, or notarization process.
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
1. Open **Settings > Apps > Installed apps** in Windows 11, or **Apps & features** in Windows 10.
2. Find **RuneStone**.
3. Select **Uninstall**.
On Windows, open Settings → Apps → Installed apps, select RuneStone, then select Uninstall.
Windows 10 calls this list Apps & features.
Your workspace folders contain your notes, scripts, images, and workspace settings.
Keep these folders outside the app installation folder. Removing the app leaves these separate folders in place.
Keep workspace folders outside the application folder. Removal leaves those separate folders in place.
An experimental source session stops with Ctrl+C in its terminal. It does not install a desktop package.
## Setup help
- **WebView2 download fails:** Restore your internet connection, then run the installer again.
- **Windows shows an unknown publisher:** Current local builds are unsigned. Check the file source with the maintainer before you proceed.
- **The app cannot open a workspace:** Use the folder button to choose a folder that your Windows account can access.
| 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. |
| A workspace will not open | Choose a folder that your account can access. |
| 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) explains the app controls.
The [release guide](releases.md) explains how maintainers build and distribute installers.
The [user guide](user-guide.md#resolve-file-conflicts) covers document errors after launch.
+39
View File
@@ -0,0 +1,39 @@
# Plugin names and source folders
Use these names in Settings, plugin manifests, help, and problem reports.
Use names without spaces for source folders and package metadata.
| Plugin name | Source folder after manual rename | Current source folder | npm package name | Stable plugin ID |
| --- | --- | --- | --- | --- |
| Browser | `RuneStone_Browser` | `RuneStone_WebViewer` | `runestone-browser` | `runestone.browser` |
| Local Autocomplete | `RuneStone_LocalAutocomplete` | `RuneStone_LocalModel` | `runestone-local-autocomplete` | `runestone.local-autocomplete` |
| Project Management | `RuneStone_ProjectManagement` | `RuneStone_PM` | `runestone-project-management` | `runestone.pm` |
## Manual source folder changes
The team must rename the three source folders because local tools and saved project paths can depend on them.
These changes remain pending. The current folders and repository URLs still use their earlier names.
1. Close development servers and tools that use the three source folders.
2. Rename each current source folder to its matching name in the table.
3. Update saved editor projects, shortcuts, task paths, and local scripts that contain the old absolute paths.
4. Update cross-project documentation links after the folders move.
5. Run the documented checks from each renamed checkout before the next build.
Keep each plugin beside the `RuneStone` host checkout, or set `RUNESTONE_ROOT` to the host path.
The plugin build and package scripts use their own checkout or working directory and the host path.
They support both the current and intended folder names.
A local folder rename does not rename a remote repository. Keep existing remote URLs until the team changes them.
## 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 keeps `runestone.pm-<version>.zip`.
Do not rename published ZIP files or change plugin IDs as part of a display-name change.
Project Management retains `.runestone/pm/`, `runestone_pm`, and its existing preview storage key.
Existing view IDs, setting keys, and document IDs also stay unchanged.
These technical names preserve access to existing data and are not alternate product names.
The [plugin package reference](plugins.md) explains packaging and installation.
+39 -12
View File
@@ -4,6 +4,7 @@
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 pending manual folder changes.
Terminal and Table formulas use the same installed package system as all other plugins.
## Build and install the feature packages
@@ -372,7 +373,7 @@ Settings loads enabled plugins so their configuration pages remain available in
The host calls `mount(container, context)` with `context.surface` set to `"settings"` or `"view"`.
Older hosts can omit the context argument.
Local Autocomplete keeps temporary reference text in its editor view because that text belongs to one window.
Open Commands → Configure local autocomplete in that window to use reference text.
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.
@@ -406,7 +407,8 @@ The native read command checks the active window's workspace boundary and reject
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 appear as icon buttons in the ribbon left of the navigation pane.
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.
@@ -448,15 +450,40 @@ Run `scripts/pluginInstall.smoke.mjs`, `scripts/plugins.smoke.mjs`, and `scripts
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.
## Browser development plugin
## Built-in browser
Browser development lives in `../RuneStone_WebViewer/`.
Build `releases/runestone.browser-0.1.0.zip` there with `npm run build:plugin`.
The plugin opens editor tabs, contributes to Settings and Bookmarks, and handles web links when selected by the user.
A fresh browser store contains one User profile. Users can create blank profiles or duplicate an existing profile.
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 browser requires the native browser service in this host revision.
Build and stage the runtime from its checkout, then include `src-tauri/tauri.browser.conf.json` when building RuneStone.
The runtime is an optional host resource, similar in purpose to the native service used by Terminal.
Plugin ZIP files still contain JavaScript and assets. They do not install arbitrary native executables.
See the browser checkout's README for build steps and current limits.
The interface source lives in `src/lib/browser/`. The runtime source remains in `../RuneStone_Browser/`.
Stage the runtime with that checkout's `npm run stage:host` 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.
+5 -4
View File
@@ -3,6 +3,7 @@
[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.
@@ -73,12 +74,12 @@ See the [installation and removal guide](plugins.md#uninstall-with-one-confirmat
- [ ] Move native terminal services into a separate in-house package.
- [x] Move formula evaluation, rendered results, and help controls into an external Table formulas package.
- [ ] Move the remaining spreadsheet operations into a separate in-house package.
- [ ] Add one Project management plugin with connected Kanban, Gantt, and Calendar views.
- [ ] 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 PM plugin has a separate development project. See its [design and scope](../../RuneStone_PM/project-management.md).
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_ProjectManagement/project-management.md).
### Planned plugin lineup
@@ -91,7 +92,7 @@ No plugin starts automatically in a fresh installation. The planned lineup inclu
Planned plugins disabled by default:
- Project management. Connected Kanban, Gantt, and Calendar views within one package.
- 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.
+32
View File
@@ -0,0 +1,32 @@
# Test build: RuneStone 0.1.13 and Project Management 0.2.18
These builds include the 14 Kanban cards prepared for user review on October 8, 2026.
See the [work record](archive/kanban-review-2026-10-08.md) for assignments and checks.
## Changes
- The tab bar uses available space and keeps one New tab after the last tab closes.
- Settings and plugin rows use shared dimensions and compact spacing.
- Repeated formatted paste no longer duplicates content or freezes the editor.
- Card descriptions edit inside the card and display saved Markdown formatting.
- Priorities use a nearby picker with colors and icons.
- Cards can move between boards while preserving their content and metadata.
- Image controls overlay the viewer. Outside clicks and Escape close it.
- Board menu actions have icons. The title edit indicator appears on hover or keyboard focus.
## Local installation
Run `RuneStone_0.1.13_x64-setup.exe` to reinstall or update RuneStone.
The installer includes the existing browser runtime and retains the downgrade restriction.
In Settings → Plug-ins, uninstall the previous Project Management package.
Restart RuneStone, then choose Install plugin ZIP and select `runestone.pm-0.2.18.zip`.
Workspace cards and retained plugin settings survive removal of the old package.
## Checks
Project Management passed its type check, 101 unit tests, and 103 browser tests after packaging.
Host native tests passed 63 tests, with three ignored. The source checks passed all 191 host unit tests and focused browser checks.
Native installer use and the changed desktop behavior remain for user acceptance.
All 14 cards remain in Review.
Both artifacts passed integrity checks. The plugin file hashes match its build record.
+35
View File
@@ -0,0 +1,35 @@
# Test build: RuneStone 0.1.14, Project Management 0.2.19, and Git 0.1.1
These builds cover 16 selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Browser tabs, profiles, and bookmarks now belong to RuneStone. The installer includes the existing Chromium runtime.
- The left ribbon, shared menus, and table cell spacing use compact dimensions and clear icons.
- Project Management improves card spacing, title focus, outside clicks, image dismissal, and detail icons.
- Large boards retain their view and scroll position. Board selection retains the current tab position.
- Label deletion clears saved references. Card archive actions retain workspace files.
- Git adds a sidebar for status, file diffs, staging, unstaging, commits, and line history.
## Local installation
Run `RuneStone_0.1.14_x64-setup.exe` to reinstall or update RuneStone. Setup retains the downgrade restriction and preserves workspace files and settings.
Install `runestone.pm-0.2.19.zip` and `runestone.git-0.1.1.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing Project Management installation, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace cards survive package removal.
Browser needs no separate ZIP. An old Browser package can be removed through Settings. Browser profiles and bookmarks retain their existing storage.
## Checks and limits
The host passed its source check, 193 unit tests, and 71 native tests. Three native tests remain ignored.
Focused browser checks passed for the built-in browser, plugin access, menus, layouts, and selections in both themes and narrow windows.
Project Management passed its type check, 98 unit tests, and 111 browser tests after packaging. Git passed its source check and four unit tests.
Git also passed seven native host tests and its standalone and real-host browser checks before packaging.
The ZIP manifests and all extracted files match the compiled files.
Browser tests use native mocks. Native browser use, installer behavior, and desktop acceptance still need user review.
Git requires installed Git and a workspace at the repository root. Linked worktrees, remote actions, branch changes, and repository creation remain unsupported.
Git retains commit hooks. Diff tabs refresh when the user selects the file again.
+37
View File
@@ -0,0 +1,37 @@
# Test build: RuneStone 0.1.15, Project Management 0.2.20, and Terminal 0.1.2
These builds cover eight selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Tables retain separate plain paragraphs without extra blank lines. Cell dimensions stay stable during edits and navigation.
- IDE and Terminal text use a lighter font weight.
- Shared menus use compact 14-pixel icons and 26-pixel rows.
- Git and other plugin sidebar views appear beside Files, Search, and Bookmarks in the top header.
- Project Management retains horizontal scroll when hidden tabs refresh or create a board. Each list has an inline Add a card control.
- The UI design reference records shared dimensions, icons, corners, selections, and menus.
## Local installation
Run `RuneStone_0.1.15_x64-setup.exe` to reinstall or update RuneStone. Setup preserves workspace files and settings, and blocks version downgrades.
Install `runestone.pm-0.2.20.zip` and `runestone.terminal-0.1.2.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
Git 0.1.1 remains the current package. The host supplies its new navigation position.
The installer includes the built-in browser and its Chromium runtime.
## Checks and limits
The host passed its source check, 195 unit tests, and 71 native tests. Three native tests remain ignored.
Browser checks passed for shared menus, table navigation, plugin tab order, workbench layout, and the actual Git navigation view.
Table checks cover both themes, two window widths, save, undo, and cell dimensions.
Project Management passed its type check, 98 unit tests, and all 116 browser tests after packaging.
Its final compiled module passed host checks for scroll retention in both legacy and managed board tabs.
Terminal passed its source check, six unit tests, and browser checks, including its rendered font weight in the light theme.
Both ZIPs contain a root manifest. Every archived file matches its compiled source hash.
Browser tests use native mocks. Native installer behavior and desktop acceptance still need user review.
The build creates local artifacts. It does not install, publish, or commit them.
+70
View File
@@ -0,0 +1,70 @@
# Test build: RuneStone 0.1.16, Project Management 0.2.21, and Git 0.1.2
These local builds cover eight selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Plain editable text permits the native spelling menu. Selected text and tables retain their action menus.
- New file accepts the complete filename. Rename includes the extension.
- Code editors share a 13px font size and 21px line height.
- GPT, Claude, Sakura, and RuneStone support light and dark modes. Terminal uses green text on black.
- Browser settings list and filter cookies and history for each profile. Users can remove individual entries.
- Project Management uses the empty list space for its card composer. Focus changes hide the composer and retain its draft.
- Git adds push, pull, and separate collapsible Changes and Graph sections.
See the [source changes and limits](archive/kanban-changes-2026-10-08.md) for more details.
## Local installation
Run `RuneStone_0.1.16_x64-setup.exe` to reinstall or update RuneStone.
Setup defaults to reinstall for an existing version and blocks downgrades. Workspace files and user settings remain outside the installation folder.
Install `runestone.pm-0.2.21.zip` and `runestone.git-0.1.2.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
The installer includes the rebuilt Browser runtime. Browser needs no separate plugin ZIP.
## Build files
| Build | Local path | Bytes |
| --- | --- | --- |
| RuneStone 0.1.16 | `src-tauri/target/release/bundle/nsis/RuneStone_0.1.16_x64-setup.exe` | 125007691 |
| Project Management 0.2.21 | `../RuneStone_ProjectManagement/plugin-packages/runestone.pm-0.2.21.zip` | 160626 |
| Git 0.1.2 | `../RuneStone_Git/releases/runestone.git-0.1.2.zip` | 6563 |
## SHA256 checksums
```text
a8b0b2532aec27d2862cf3d3924383c67c66b15493456f43158aace0fcf79c5f RuneStone_0.1.16_x64-setup.exe
0003494fc6c671121e11adb3334b2e973f755fd324abc0860c05af19caaa00e5 runestone.pm-0.2.21.zip
8748d264fe9daa563a7e426372d7c965ad27a019ce35842c343a9dfdc7e15b2c runestone.git-0.1.2.zip
```
The installer folder also contains `RuneStone_0.1.16_release-checksums.sha256` with these three checksums.
## Checks and limits
The host passed its source check, 195 unit tests, and 75 native tests. Three native tests remain ignored.
The installer build completed. Both the application and setup executable report version 0.1.16.
The generated installer includes all 73 Browser resources and retains the default reinstall choice and downgrade restriction.
Browser checks cover filenames, extension changes, shared menus, fonts, appearance, and cookie and history controls.
The final appearance check passed all palettes, both modes, three-window sync, reload, and narrow settings.
Terminal-to-Sakura changes restore the original syntax colors. Existing and new editors pass the same check.
Project Management passed its type check, 98 unit tests, and all 119 browser tests after packaging.
The browser suite includes both compiled-plugin checks.
Git passed source checks, four plugin unit tests, 11 native fixture tests, and sidebar browser checks.
Both ZIPs contain a root manifest. Every archived file matches its compiled source SHA256 hash.
The packaged Browser runtime passed native Electron checks, including individual cookie and history removal.
All 73 staged runtime files match the packaged source SHA256 hashes.
Runtime packaging is intermediate installer output and does not change the Browser version.
Native spelling suggestions and actual correction still need desktop acceptance.
Actual installation, reinstall, settings retention, and downgrade protection still need desktop acceptance.
The Git graph shows at most 100 commits. Push and pull require a configured upstream and existing Git authentication.
Pull permits only fast-forward updates.
These builds create local artifacts. They do not install, publish, or commit them.
+74
View File
@@ -0,0 +1,74 @@
# Test build: RuneStone 0.1.17 and Git 0.1.4
These local builds cover three selected cards on October 8, 2026.
The cards remain in Review for user acceptance.
## Changes
- WebView2 supplies spelling suggestions to the shared menu. Native commands apply corrections.
- Claude uses Anthropic colors and local Lora and Poppins font stacks, with Georgia and Arial fallbacks.
- Sakura uses the card palette and light mode. Saved dark Sakura selections migrate to light Sakura.
- GPT and Terminal themes are removed. Saved selections migrate to RuneStone with their previous light or dark mode.
- Git history draws commit nodes and parent links, with branches, tags, messages, authors, and dates.
See the [source changes and checks](archive/kanban-followup-2026-10-08.md) for more details.
## Local installation
Run `RuneStone_0.1.17_x64-setup.exe` to reinstall or update RuneStone.
Setup defaults to reinstall for an existing version and blocks downgrades.
Workspace files and user settings remain outside the installation folder.
Install `runestone.git-0.1.4.zip` through Settings → Plug-ins → Install plugin ZIP.
This Git package requires RuneStone 0.1.17 or later.
For an existing Git plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
Browser remains part of the installer. All 73 staged runtime files match the previous packaged source hashes.
The Browser runtime and other plugins need no new release build for these changes.
## Build files
| Build | Local path | Bytes |
| --- | --- | --- |
| RuneStone 0.1.17 | `src-tauri/target/release/bundle/nsis/RuneStone_0.1.17_x64-setup.exe` | 125009581 |
| Git 0.1.4 | `../RuneStone_Git/releases/runestone.git-0.1.4.zip` | 8004 |
## SHA256 checksums
```text
378b95b6d7f1d4f0413449e67264780d6d84e46e53b8304e6c63296917ec716c RuneStone_0.1.17_x64-setup.exe
eca6eeb9304f344f667c0d31666db54b207efb86c0b7a109c1ce6f563c61c859 runestone.git-0.1.4.zip
```
The installer folder also contains `RuneStone_0.1.17_release-checksums.sha256` with these checksums.
## Checks and limits
The host passed its source check with no errors or warnings and 198 unit tests.
Native tests passed 78 tests, with three ignored.
The frontend production build passed before packaging and during the installer build.
The locked NSIS build completed with the normal `com.runestone.app` identifier and window configuration.
The application and installer report version 0.1.17.
The generated installer includes all 73 Browser resources and retains the default reinstall choice and downgrade restriction.
Git passed its source check, five unit tests, compilation, and sidebar, UI, and host browser checks.
The final ZIP contains a root manifest, a readable entry module, styles, and installation guidance.
Every archived plugin file matches its compiled source SHA256 hash.
All 73 archived Browser resources match their staged source hashes.
The installer passes the 7-Zip archive integrity check.
The archived application differs from the release executable only in the three-byte Tauri NSIS bundle marker.
Git 0.1.3 remains a superseded local artifact. Version 0.1.4 adds the required host version and current feature guidance to its README.
Neither build replaces an earlier release file.
Appearance checks passed all five supported theme and mode combinations, migration, three-window sync, Monaco colors, and 360px settings.
The shared menu check passed after the final icon mapping changes.
Native Undo through the shared menu restored Writer text in an isolated WebView2 profile.
That profile supplied no spelling suggestions. Correction and undo with an actual spelling suggestion still need desktop acceptance.
Actual installation, reinstall, settings retention, and downgrade protection also need desktop acceptance.
The Git graph shows at most 100 commits. Dashed links mark parents outside that history.
Push and pull require a configured upstream and existing Git authentication.
Pull permits only fast-forward updates.
These builds create local artifacts. They do not install, publish, or commit them.
-11
View File
@@ -1,11 +0,0 @@
# RuneStone 0.1.7
This version is a local build. The installer is not published for public download.
- Install plugins from standard ZIP files or experimental Gitea release links.
- Open plugin documents in editor tabs, with navigation icons and rename support.
- Read binary workspace files through the plugin API, with a 64 MiB limit.
- Use consistent menus with icons, keyboard controls, rounded rows, and shared theme styles.
- Install Terminal and Table formulas from their separate plugin packages.
The Windows installer is unsigned. Clean-account installation and upgrade checks remain untested.
+16 -66
View File
@@ -1,71 +1,21 @@
# Release guide
# Release history
[Back to RuneStone](../README.md)
[RuneStone](../README.md) · [Installation](installation.md) · [Build and package](builds.md)
For experimental Linux builds, use the [Linux readiness guide](linux.md).
These entries record completed local test builds. They are not public download links.
Source changes after a build do not change its recorded contents.
Each entry includes artifact paths, checks, and any remaining desktop acceptance work.
## Build the Windows installer
| RuneStone | Related plugin builds | Notes |
| --- | --- | --- |
| 0.1.17 | Git 0.1.4 | [Menu, themes, and Git graph](release-0.1.17.md) |
| 0.1.16 | Project Management 0.2.21, Git 0.1.2 | [Follow-up test build](release-0.1.16.md) |
| 0.1.15 | Project Management 0.2.20, Terminal 0.1.2 | [Test build](release-0.1.15.md) |
| 0.1.14 | Project Management 0.2.19, Git 0.1.1 | [Test build](release-0.1.14.md) |
| 0.1.13 | Project Management 0.2.18 | [Kanban test build](release-0.1.13.md) |
Build on 64-bit Windows with the tools in the [development guide](development.md#run-from-source).
The commands below use the checked-in dependency versions.
Earlier local installers include Windows save hotfix 0.1.11a, with numeric installer version 0.1.12.
Their release notes are not complete in this checkout.
```sh
pnpm install --frozen-lockfile
pnpm check
pnpm test
pnpm build:installer
```
The last command builds the interface, compiles the release app, and creates an NSIS setup executable.
The first build needs internet access to download the packaging tools and the WebView2 bootstrapper.
Find the installer in:
```text
src-tauri/target/release/bundle/nsis/RuneStone_<version>_x64-setup.exe
```
Distribute this setup file. Users do not need the repository, a local server, or build tools.
Build output stays outside version control.
## Installer settings
Tauri automatically merges `src-tauri/tauri.windows.conf.json` into the base configuration on Windows.
This file selects NSIS for ordinary `pnpm tauri build` commands too.
It uses the existing RuneStone icon and installs the app for the current Windows account.
Tauri supplies the setup screens, Start menu shortcut, launch option, and uninstaller.
The installer includes the WebView2 bootstrapper.
If WebView2 is missing, setup downloads the runtime. An existing runtime needs no setup download.
The configuration blocks version downgrades.
It does not register document types or start RuneStone when Windows starts.
See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options.
## Prepare a release
1. Set the same version in `package.json`, `src-tauri/Cargo.toml`, and `src-tauri/tauri.conf.json`.
2. Update `src-tauri/Cargo.lock` with Cargo if the package version changed.
3. Run the checks and build command above.
4. Test the installer on a clean Windows account with the checks below.
5. Attach the setup file and release notes to the repository release or your chosen download page.
Keep `com.runestone.app` as the app identifier so upgrades retain the same app identity.
No public download location or automatic release upload is configured yet.
After you publish an installer, add its download link to the README.
Local installers are unsigned until the maintainer configures Windows code signing.
Use [Tauri's signing guide](https://v2.tauri.app/distribute/sign/windows/) before public distribution.
## Installer checks
| Check | Expected result |
| --- | --- |
| Install on an account without Node.js or Rust | Setup completes and RuneStone opens |
| Install without WebView2, with internet access | Setup installs the runtime and RuneStone opens |
| Open RuneStone from the Start menu | The app opens without a terminal or development server |
| Create a workspace outside the installation folder | Notes save and reopen |
| Install a newer version | Setup updates the app and preserves workspace files |
| Try to install an older version | Setup blocks the downgrade |
| Remove RuneStone through Windows Settings | The app and shortcuts disappear, and the separate workspace remains |
These checks require a Windows test account or virtual machine. A successful build alone does not confirm them.
See the [archive](archive/README.md) for dated implementation records and proposals.
Maintainers use the [build guide](builds.md) to package installers and run installation checks.
+1 -1
View File
@@ -52,7 +52,7 @@ 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 [RuneStone_PM roadmap](../../RuneStone_PM/roadmap.md).
Project Management plugin planning lives in the separate [Project Management roadmap](../../RuneStone_ProjectManagement/roadmap.md).
## Why this order?
+110
View File
@@ -0,0 +1,110 @@
# Interface design
[Back to development](development.md)
RuneStone uses compact controls, clear icons, and shared theme values.
This reference describes the interface and its shared dimensions. Agent instructions remain in [AGENTS.md](../AGENTS.md).
## Design principles
Keep attention on the user's work. Use quiet backgrounds for the active view and reserve strong accents for alerts or actions that need attention.
Tabs can join visually with their content area. A selected view does not need a bright border or a repeated heading.
Show each board name once in the main controls. Keep switching and renaming as separate actions with clear targets.
Avoid repeated view names, instructions, and descriptions when the visible content already explains the current view.
Use familiar icons and visual previews to explain choices. Keep visible labels when an icon alone has more than one likely meaning.
Every icon control needs an accessible name, a tooltip on hover and keyboard focus, and a comfortable target.
Use a preview for visual choices such as themes and table styles.
Treat these principles as the basis for shared components and plugin interfaces.
Check the user's work area first during reviews. Controls must support that work without competing for attention.
## Window and navigation
The main window and Settings use the same 36-pixel titlebar height: `--rs-titlebar-height`.
The main header holds navigation, document tabs, actions, and window controls.
Files, Search, Bookmarks, and installed sidebar views such as Git share the top navigation group.
Editor views from plugins can use the vertical plugin ribbon. The ribbon uses no width when it has no entries.
The active navigation button shows which view occupies the left pane.
Document and plugin tabs share the tab bar. The new-tab button follows the tabs.
Tabs retain their order and pin state when a plugin replaces its current view.
The last closed tab leaves an empty New tab. Sidebar widths and visibility persist across window sessions.
Opening a different editor does not restore a hidden outline.
## Icons and controls
Use a recognizable icon for a familiar action. Pair ambiguous icons with short labels.
Icon-only buttons have accessible names and tooltips on hover and keyboard focus.
Reuse the same icon for the same action. Shared icon buttons use 28-pixel targets.
Do not add icons to explanations or settings that have no clear visual equivalent.
Controls and navigation highlights use `--rs-control-radius`, currently 5 pixels.
Selection outlines use `--rs-item-selection-radius` and the shared `--rs-item-selection-*` color and width values.
Adjacent selected items share one continuous fill and an outline around the exposed perimeter.
Separate groups retain separate outlines. Nested rows retain exposed edges at indentation changes.
Document table cells and their selection outlines stay square. Table toolbar buttons and menus remain rounded.
## Menus and dropdown actions
Action menus use `src/lib/ui/actionMenu.ts`. Svelte callers can use `ContextMenu.svelte`.
`src/lib/ui/menu.css` supplies shared presentation. `src/lib/theme/tokens.css` supplies dimensions and colors.
Feature code does not override menu rows. Menu width can expand when content needs more space.
| Token | Default | Purpose |
| --- | --- | --- |
| `--rs-menu-width` | 248px | Standard menu width |
| `--rs-menu-padding` | 5px | Inset around rows |
| `--rs-menu-row-height` | 26px | Minimum row height |
| `--rs-menu-row-padding` | 3px 8px | Vertical and horizontal row padding |
| `--rs-menu-font-size` | 12px | Shared text size |
| `--rs-menu-icon-size` | 14px | Action icon size |
| `--rs-menu-icon-gap` | 8px | Space between icon and label |
All rows reserve an icon column. Shortcut text and submenu arrows occupy trailing columns.
Enabled rows share hover and keyboard focus colors. Disabled rows stay readable and cannot run.
Menus support arrow keys, Home, End, Enter, Space, and Escape.
Right opens a submenu. Left returns to its parent. Keyboard dismissal restores focus.
Menus stay inside the viewport and scroll when their contents exceed its height.
Searchable pickers and form dialogs can use richer layouts. Native select controls retain platform behavior.
## Settings
Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls.
Related plugin metadata and actions occupy compact rows. Controls wrap at narrow widths, and the content area scrolls.
Long navigation lists must leave room for the selected page.
| Shared token | Default |
| --- | --- |
| `--rs-settings-row-padding` | 10px |
| `--rs-settings-control-height` | 28px |
| `--rs-settings-heading-size` | 18px |
| `--rs-settings-description-size` | 12px |
| `--rs-settings-gap` | 8px |
| `--rs-settings-section-gap` | 16px |
## Typography and tables
The interface uses `--rs-font-ui`, and prose uses `--rs-font-prose`.
The IDE and Terminal share `--rs-font-mono` and `--rs-code-font-weight`.
The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas.
The default code weight is 300. Actual appearance depends on installed fonts and their available weights.
Terminal font-size preferences remain independent.
Tables use shared cell padding and line height. Entering a cell does not change its row height.
A plain paragraph after a table remains a paragraph when the separator line is removed.
Table rows need an unescaped pipe. Writer and Reading use the same row boundary rule.
## Checks for interface changes
Check light and dark themes, keyboard use, focus indicators, narrow windows, and viewport edges.
For selection changes, check single items, contiguous ranges, separate groups, and nested rows.
For Settings changes, include long plugin lists. For tab changes, include plugin views and pinned tabs.
Run `node scripts/menuConsistency.smoke.mjs` against the development server after shared menu changes.
The menu check covers file, folder, pane, tab, editor, table, and submenu examples.
Use `SMOKE_URL` to select the server URL. Use `PLAYWRIGHT_MODULE` and `CHROME_PATH` when the environment needs explicit paths.
Browser tests with desktop mocks do not replace native installer and window acceptance checks.
+147 -162
View File
@@ -1,173 +1,158 @@
# User guide
[Back to RuneStone](../README.md)
[RuneStone](../README.md) · [Installation](installation.md) · [Release history](releases.md)
Current features and limitations as of October 2026.
This guide describes current source behavior. A supplied installer can contain an earlier feature set.
Check its release notes if a control is missing.
## Settings and help
| Task | Go to |
| --- | --- |
| Open a workspace or create files | [Files and workspaces](#open-a-workspace) |
| Write, read, or follow a link | [Edit documents](#edit-documents) |
| 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) |
| Run commands or scripts | [Terminal guide](guides/terminal.md) |
| Resolve a changed or missing file | [File conflicts](#resolve-file-conflicts) |
Use the gear beside the workspace selector to open Settings, or press Ctrl+,.
Use the question mark beside it to open Help and about, or press F1.
Both shortcuts work when the sidebar is hidden.
## Open a workspace
General settings control auto-save. It starts enabled, with a five-second interval.
Choose a whole number from 1 to 300 seconds, or turn auto-save off.
Changes apply when you leave the interval field and persist across restarts.
These preferences apply to all workspaces on this device. Other open windows receive changes immediately.
Restore defaults enables auto-save and sets the interval to five seconds.
Use the folder button or Ctrl+O to open a folder or choose a recent workspace.
The menu shows full paths and remembers the 20 most recent folders.
New workspace creates a named folder without replacing an existing folder.
Opening another workspace creates a new window and keeps the current window's documents and terminals.
Search settings to find a category. Plug-ins lists installed packages, including Terminal and Table formulas after installation.
No plugin starts automatically in a fresh installation. Enable changes persist across restarts and open windows.
Disabling Terminal ends its sessions. Disabling Table formulas keeps the formula source and basic table editing.
Use Install plugin ZIP for local packages, or Install from Git link for an experimental Gitea release download.
The puzzle button opens installed plugin commands and views. See the [plugin guide](plugins.md#experimental-installation-from-a-gitea-link) for release and private-access requirements.
Uninstall requires one confirmation and preserves settings, source packages, and workspace documents.
See the [plugin guide](plugins.md) for package formats, removal, and current boundaries.
Help and about includes the app version, basic instructions, and keyboard shortcuts.
Press Escape or use the close button to return to your work.
RuneStone uses ordinary files. The navigator, Quick Open, and search do not apply Git ignore rules.
They hide `.git`, `.obsidian`, and temporary save files. The navigator hides `.runestone` by default.
Settings → General → Show .runestone folder reveals workspace configuration files in the navigator.
The navigator does not traverse directory symlinks.
## Workspace, editing, and terminals
## Create and find files
- The navigator, Quick Open, and search do not apply `.gitignore`, `.ignore`, or global Git exclusions.
Internal folders (`.git`, `.obsidian`, and `.runestone`) and temporary save files stay hidden.
- The folder button and Ctrl+O open recent workspaces, with the current workspace
marked and full paths shown. The list remembers the 20 most recently opened
folders across restarts. Open another folder from the bottom of the menu, or
choose New workspace to create and open a named folder in a chosen location.
Existing folders are never overwritten. Opening or creating a workspace opens
a new window, keeping the current window's documents and terminals in place.
- Markdown's writing layout is one continuous document with live formatting.
Type freely, press Enter to continue, and use arrow keys or select across lines.
The active line reveals its raw Markdown, including link destinations and task
markers. Other lines show formatting. Checkboxes stay beside their item text. Clicking one updates the Markdown and completed items are struck through.
Ctrl+click follows links. There is no formatting toolbar.
Ctrl+E switches to the IDE source editor; Split and Read remain available.
Writing edits update the shared source model without converting through HTML,
preserving Markdown syntax, frontmatter and Windows line endings. Mermaid code,
tables and images preview inline. Table cells can be edited directly.
- Click a note's title in Writing to rename its file. Enter or leaving the field
saves the name; Escape cancels. The folder and Markdown extension are preserved,
and renaming keeps the note's contents and editing history.
- Drag a workspace image from the navigator into a Markdown editor to insert a
relative link to the existing file. An “Insert image” hint marks the editor;
Escape cancels the drag. Dropping files from the system file explorer or pasting
images copies them into `attachments/` with unique filenames. Undo removes the
inserted links while keeping the image files.
In Writing, image Markdown stays hidden until **Edit image source** is pressed. The image remains visible while editing. Hide it again with the same button,
Escape, or by moving the cursor away. Click an image to select it, then
right-click or press Shift+F10 for copy image, copy Markdown, swap image, remove
image, zoom, edit source, open in a new tab, copy path, and show in Explorer.
Remove image or Delete removes only that embed from the note and supports undo.
Zoom supports fit, magnification and Escape to close, including in Split and Read.
- Right-click Markdown text in writing or source mode (or press Shift+F10) for
note/external links, selection search, extraction, formatting, and clipboard
actions. Format includes bold, italic, strike, highlight, code, math, comments,
and clear formatting. Paragraph applies lists, tasks, headings 1–6, body text,
or quotes to the selected lines. Insert adds footnotes, tables, callouts,
horizontal rules, code blocks, and math blocks as Markdown source. Use arrow
keys to navigate submenus and Escape to return to editing. Obsidian Bases are
not supported.
- Tables keep readable column widths and render `<br>` as cell line breaks.
Hover beside a table's right edge to add a column, or below its bottom edge to
add a row. Clicking a cell edits its contents. Wide tables scroll within the document.
Grips appear on hover or keyboard focus above columns and beside body rows.
Drag a grip to reorder: a preview follows the pointer, the source row/column
stays highlighted, and a line marks the drop position. Drag near an edge
to scroll, or press Escape to cancel. Focus a grip and use arrow keys to move it.
Row moves keep the Markdown header fixed. Columns carry their alignment with them.
Drag across cells or Shift+click to select a rectangle, then right-click for
cut/copy/paste, bold, italic, strikethrough, highlight, code, math, comment,
clear formatting, alignment, clear cells, and delete cells. Clipboard shortcuts,
Ctrl+B/I, Shift+arrow selection, and undo/redo work on the selected cells.
TSV or Markdown tables paste as a grid and expand the table when needed.
Alignment applies to selected columns, as required by Markdown. Clear empties
contents; Delete removes complete selected rows/columns, or shifts a partial
selection left. Math stores inline `$…$` syntax. Comments use `%%…%%` and are
hidden in Read mode. Each operation can be undone in one step.
Right-clicking text within a cell preserves the selected words and offers note
links, external links, workspace search, extraction to a new note, formatting,
rich/plain-text paste, and Select all. Extraction saves the selected Markdown
in a new file and replaces the selection with a note link. Undo restores the
original text without deleting the new note. Row and Column submenus insert,
move, duplicate, and delete at the clicked cell. Column moves keep alignment. Sorting is stable and natural (2 before 10), leaves blanks last, and keeps the
header fixed. Context-menu actions and table edge buttons have matching icons.
- Table formulas start with `=`: for example, `=B2+C2`, `=AVERAGE(B2:C2)`,
`=SUM(B2:B10)`, or `=ROUND(B2/3, 2)`. Columns use A, B, …, AA. Row 1 is
the header, so the first data row is 2. References stay inside the current table.
Arithmetic supports `+`, `-`, `*`, `/`, `^`, parentheses, and postfix `%`.
Functions include SUM, AVERAGE, MIN, MAX, COUNT, ABS, and ROUND.
Separate function arguments with commas: `=AVERAGE(B2,C2)` averages two cells.
A colon selects a range: `=AVERAGE(B2:C2)`.
Aggregates ignore text and blank cells. Arithmetic treats blank cells as zero.
Results recalculate in Writing, Split, and Read. Click a result to edit its
formula; Enter commits it and Tab moves to the next cell. The Formulas control
below each table explains the syntax, and the active cell shows its address.
Invalid formulas, missing cells, and circular references display error labels.
Markdown stores the formula itself, so other apps display readable source.
Use code formatting or `\=` to keep formula-like text literal. References are
positional: copying, inserting, deleting, sorting, or moving cells does not
rewrite addresses. Cross-table references and automatic fill are not supported.
- Tabs retain their editor models, undo history, cursor and scroll state while open.
- Drag a tab left or right to change its position. Hold it near either edge to scroll through other tabs.
- Right-click a tab for Move tab left and Move tab right. With a tab focused, use Alt+Shift+Left or Alt+Shift+Right.
Use the arrow keys, Home, or End to select tabs. Press Escape to cancel a drag.
- Click the + beside the tabs or press Ctrl T to open an empty tab. Open or create a file from there to use that tab. No file is created until you choose New file.
- Changed notes and scripts auto-save every five seconds by default, including background tabs.
Use Settings to change the interval or turn auto-save off.
Unchanged files are never rewritten. Ctrl+S saves immediately. Disk conflicts
and unavailable files preserve your edits for resolution instead of overwriting.
- The reader uses a Markdown parser for paragraphs, nested lists, tables, tasks,
code blocks and reference images. Frontmatter sits in a collapsed Properties
section. Wiki links, note callouts and locally rendered Mermaid diagrams are
supported in Writing, Split and Read. Diagram source remains available to copy. Invalid diagrams show a message and their source. Toolbar icons show tooltips
on hover or keyboard focus; Split view stacks vertically in narrow panes.
- Ctrl+P finds files by path. Ctrl+N creates a note or script at a workspace-relative
path. Ctrl+S saves. Ctrl+Shift+F opens workspace search; Ctrl+F searches the editor.
- Ctrl+` or Ctrl+J shows or hides the terminal, preserving sessions and scrollback.
New Terminal (Ctrl+Shift+`) creates an independent shell; Split (Ctrl+Shift+5)
adds a resizable pane in the active group and inherits its current directory/profile.
The terminal list appears only when multiple sessions exist. Kill terminates a
session; Delete does the same while a terminal-list entry has focus. Maximize
and Restore change the panel size without restarting shells.
- The dropdown immediately beside New Terminal offers installed PowerShell,
PowerShell 7, Git Bash, Command Prompt, and Bash profiles, a default-profile
picker, terminal settings, tasks, and separate terminal windows
(Ctrl+Shift+Alt+`). Font size, scrollback, cursor blinking, and default profile
persist locally. New terminals inherit the app environment, including PATH.
- More terminal actions clears scrollback, runs selected editor text, or saves
and runs the active script. Supported runners include Python, JavaScript,
PowerShell, Bash, Ruby, Windows batch files, and executables. Their runtimes
must be installed. Recent-command (Ctrl+Alt+R) and directory (Ctrl+G) pickers
work while the terminal is focused. Ctrl+Up/Down navigates prompt markers.
History is kept in memory for the current dock; PowerShell/Bash report commands
after completion, while Command Prompt captures submitted text at its prompt.
- Configure Tasks creates/opens `.runestone/tasks.json`. Its `tasks` array contains
objects with `label`, `command`, and an optional `profile` ID (`powershell`,
`pwsh`, `git-bash`, `cmd`, or `bash`). Run Task starts the chosen command in its
own terminal at the workspace root. Tasks run only when explicitly selected.
- JavaScript Debug Terminal starts a Node.js REPL with a local inspector on an
available port. Attach an external debugger using the printed address.
RuneStone does not provide VS Code's debugger or automatic debug attachment.
Start Dictation invokes Windows voice typing (Win+H) in the focused terminal;
Windows microphone/voice-typing configuration is required. Other platforms
use their operating system's dictation shortcut.
- Closing a detached terminal window terminates its sessions. Switching workspace
closes detached terminal windows and ends the old workspace's sessions.
- File watching reloads clean buffers after an agent or another application changes
them. Dirty buffers display a conflict with the disk version and explicit choices
to use it, keep local edits, or save a copy. Missing files retain their open buffer.
- Saves compare the current disk text with the saved baseline, prepare a complete
temporary file, then replace the destination. This prevents known stale saves and
truncation on failed writes. It does not lock out other processes. Concurrent tools
can still write between the last comparison and replacement.
- Closing a dirty tab, switching workspaces, and closing the desktop window prompt
before discarding edits or terminating terminal sessions.
- `.git`, `.obsidian`, `.runestone`, and temporary save files are hidden from the
navigator/search. Directory symlinks are not traversed by the navigator.
Press Ctrl+N for New file. Enter the complete filename, including its extension, such as `notes/meeting.md` or `scripts/check.py`.
RuneStone does not add an extension to New file.
New note creates a Markdown file. The note title can then rename it.
## Limitations
Use Ctrl+P to find files by path. Ctrl+Shift+F searches the workspace, and Ctrl+F searches the editor.
Right-click a file or folder for its available actions. Drag files between folders to reorganize them.
With the navigator focused, Ctrl+Z undoes a file move and Ctrl+Shift+Z repeats it.
Vault-wide wiki-link resolution, backlinks and math rendering still need work.
Git UI, language servers, restricted plugin permissions, persistent tab restoration and crash recovery
are not implemented. Unsaved buffers and terminals last for the current app
session only.
## Edit documents
Writer shows Markdown as a continuous document. The active line reveals its source, while other lines show formatting.
Use Enter, arrow keys, and ordinary text selection to edit across lines.
Checkboxes update their task markers, and completed tasks show a strike through their text.
Ctrl+E switches between Writer and the IDE source editor. The document controls select Edit, Read, or Split.
Hover a control or focus it with the keyboard to see its label. Split stacks vertically in narrow panes.
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.
Read mode follows links with an ordinary click. Wiki links, note callouts, and Mermaid diagrams work in document views.
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.
### Format text
Right-click Markdown text, or press Shift+F10, for formatting, links, search, extraction, and clipboard actions.
Use arrow keys for submenus and Escape to return to editing.
| Menu | Actions |
| --- | --- |
| Format | Bold, italic, strike, highlight, code, math, comments, and clear formatting |
| Paragraph | Lists, tasks, headings 1–6, body text, and quotes |
| Insert | Footnotes, tables, callouts, horizontal rules, code blocks, and math blocks |
There is no formatting toolbar. Obsidian Bases are not supported.
Right-click a misspelled word for the operating system's spelling suggestions when available.
Windows can retain its native spelling menu when WebView2 cannot expose suggestion labels to RuneStone.
## Use note templates
1. Right-click a Markdown file or its tab.
2. Choose Save as template and enter a name.
3. Choose the saved template from New note.
Templates belong to the current workspace and live in `.runestone/templates/` as Markdown files.
New note copies the template into a new file. Duplicate names receive a unique filename.
Editing the new note does not change the template. New file still accepts an exact filename and extension.
## Manage tabs
Tabs retain their editor models, undo history, cursor, and scroll position while open.
Click + or press Ctrl+T for an empty tab. Opening or creating a file uses that tab.
Ctrl+Tab selects the next tab, and Ctrl+Shift+Tab selects the previous tab.
Drag a tab to reorder it. Holding it near an edge scrolls the tab strip, and Escape cancels the drag.
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.
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.
## Save your work
Auto-save starts enabled with a five-second interval and includes background tabs.
Ctrl+S saves immediately. RuneStone does not rewrite unchanged files.
Settings → General accepts an interval from 1 to 300 seconds or turns auto-save off.
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.
## Resolve file conflicts
Clean buffers reload when another tool changes the file. A buffer with local edits shows a disk conflict instead.
Choose the disk version, keep local edits, or save a copy. Missing files keep their open buffer.
Saves compare disk text with the saved baseline, write a complete temporary file, then replace the destination.
Failed writes keep the edits available. This process does not lock other tools out of the file.
Another process can still write between the final comparison and replacement.
## Change settings or add plugins
The gear beside the workspace selector opens Settings. Ctrl+, works when the sidebar is hidden.
Settings searches by category. Preferences apply to all workspaces on this device and synchronize across open windows.
The desktop uses a separate Settings window. The browser preview uses a dialog.
Settings → Appearance selects built-in colors or installs a theme. See the [appearance guide](guides/themes.md).
Settings → Plug-ins installs local ZIPs or experimental Gitea release links.
Use the [plugin guide](plugins.md#install-a-plugin) for installation, access, and removal details.
No optional plugin starts automatically in a fresh installation. Enable choices persist across restarts and windows.
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.
## Keyboard reference
These are the Windows/Linux shortcuts. macOS desktop behavior still needs native tests.
| Action | Shortcut |
| --- | --- |
| Open workspace / Find file / New file | Ctrl+O / Ctrl+P / Ctrl+N |
| New tab / Close tab | Ctrl+T / Ctrl+W |
| Next tab / Previous tab | Ctrl+Tab / Ctrl+Shift+Tab |
| Save / Find in document / Search workspace | Ctrl+S / Ctrl+F / Ctrl+Shift+F |
| Switch Writer and IDE | Ctrl+E |
| Context actions | Shift+F10 |
| Settings / Help and about | Ctrl+, / F1 |
The [Terminal guide](guides/terminal.md) lists plugin shortcuts.
## Get help and check limits
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.
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 a reproducible problem, record the app version, operating system, steps, expected result, and error text.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.6 KiB

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.7 KiB

After

Width:  |  Height:  |  Size: 5.0 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "runestone",
"version": "0.1.10",
"version": "0.1.18",
"description": "Desktop editor for a local workspace",
"type": "module",
"scripts": {
+199
View File
@@ -0,0 +1,199 @@
// Run against the development server with an isolated browser storage context.
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
const findings = [];
const output = ".audit";
await mkdir(output, { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
const secondSettings = await context.newPage();
for (const page of [main, settings, secondSettings]) {
page.setDefaultTimeout(10000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await main.getByText("appearance-smoke", { exact: true }).waitFor();
async function openCode(index) {
await main.keyboard.press("Control+p");
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
await main.locator(".monaco-editor textarea").waitFor();
await main.waitForFunction(async file => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
}, `theme-${index}.py`);
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
}
async function editorIds() {
return main.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
});
}
async function syntaxColors() {
return main.locator(".view-line span").evaluateAll(spans => Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
})));
}
async function waitForSyntax(expected = null) {
await main.waitForFunction(expected => {
const spans = [...document.querySelectorAll(".view-line span")];
const colors = Object.fromEntries(["RuneStone", "print", "42"].map(text => {
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
return [text, span ? getComputedStyle(span).color : null];
}));
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected);
}
async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click();
await page.getByRole("combobox", { name: "Color theme", exact: true }).waitFor();
}
await openCode(0);
await openAppearance(settings);
await openAppearance(secondSettings);
async function expectAppearance(theme, mode) {
for (const page of [settings, secondSettings, main]) {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
}
assert.equal(await secondSettings.getByRole("combobox", { name: "Color theme", exact: true }).inputValue(), theme);
assert.equal(await secondSettings.getByRole("combobox", { name: "Appearance", exact: true }).inputValue(), mode);
await main.waitForFunction(() => {
const root = document.documentElement;
const probe = document.createElement("i");
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-bg");
document.body.append(probe);
const expected = getComputedStyle(probe).backgroundColor;
probe.remove();
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === expected);
});
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
}
let nextCode = 1;
const backgrounds = new Set();
for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds();
await settings.getByRole("combobox", { name: "Color theme", exact: true }).selectOption(theme);
if (theme !== "sakura") await settings.getByRole("combobox", { name: "Appearance", exact: true }).selectOption(mode);
backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++);
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
await expectAppearance(theme, mode);
await waitForSyntax();
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}.png` });
await main.screenshot({ path: `${output}/appearance-editor-${theme}-${mode}.png` });
if (theme === 'sakura') {
const keywordColor = await main.locator('.view-line span').evaluateAll(spans => {
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === 'def');
return keyword ? getComputedStyle(keyword).color : null;
});
assert.equal(keywordColor, 'rgb(152, 85, 108)', 'Sakura keywords use Plum Wine');
}
const typography = await settings.evaluate(() => ({
body: getComputedStyle(document.body).fontFamily,
heading: getComputedStyle(document.querySelector('h2')).fontFamily,
prose: getComputedStyle(document.documentElement).getPropertyValue('--rs-font-prose').trim(),
}));
if (theme === 'claude') {
assert.match(typography.body, /Lora.*Georgia/);
assert.match(typography.prose, /Lora.*Georgia/);
assert.match(typography.heading, /Poppins.*Arial/);
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-accent').trim()), '#d97757');
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
}
}
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
assert.deepEqual(await settings.getByRole('combobox', { name: 'Color theme', exact: true }).locator('option').evaluateAll(options => options.map(option => option.value)), ['default', 'claude', 'sakura']);
assert.equal(await settings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
assert.equal(await secondSettings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
});
assert.deepEqual(sakura, { bg: '#fefcfc', border: '#f8dbe6', selection: '#ffc9dc', 'bg-active': '#dbeacb', 'syntax-parameter': '#cb6b91', 'syntax-keyword': '#98556c', 'syntax-local': '#618c71', 'syntax-static': '#69a2bd', 'syntax-instance': '#607fa9', 'syntax-global': '#687788' });
for (const [theme, savedMode, expectedTheme, mode] of [
['gpt', 'light', 'default', 'light'],
['terminal', 'dark', 'default', 'dark'],
['sakura', 'dark', 'sakura', 'light'],
]) {
await settings.evaluate(value => localStorage.setItem('runestone.appearance', JSON.stringify(value)), { theme, mode: savedMode });
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await expectAppearance(expectedTheme, mode);
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance'))), { theme: expectedTheme, mode });
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
}
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 });
await settings.getByRole('combobox', { name: 'Color theme', exact: true }).selectOption(theme);
if (theme !== 'sakura') await settings.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption(mode);
await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme', 'Appearance']) {
const control = settings.getByRole('combobox', { name, exact: true });
await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
}
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}-360.png` });
}
assert.deepEqual(errors, []);
assert.deepEqual(findings, [], 'Appearance findings');
await context.close();
console.log('Appearance smoke passed: supported palettes, modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.');
} catch (error) {
console.error('Browser errors:', errors);
for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) {
await page.screenshot({ path: `${output}/appearance-failure-${index}.png` }).catch(() => {});
}
throw error;
} finally { await browser.close(); }
+21
View File
@@ -0,0 +1,21 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { parseAppearance, normalizeAppearance, THEMES } from '../src/lib/theme/appearance.ts';
test('Removed palettes preserve the saved mode with the default palette', () => {
for (const theme of ['gpt', 'terminal', 'unknown']) {
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
}
}
assert.deepEqual(THEMES, ['default', 'claude', 'sakura']);
});
test('Sakura cannot restore or save a dark appearance', () => {
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
assert.deepEqual(normalizeAppearance({ theme: 'sakura', mode: 'dark' }), { theme: 'sakura', mode: 'light' });
});
test('Malformed storage returns a valid default appearance', () => {
for (const raw of [null, '', '{', 'null', '42', '[]']) {
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
}
});
+139
View File
@@ -0,0 +1,139 @@
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
const runtime = path.resolve('../RuneStone_Browser');
const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright');
const electron = require('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
let sequence = 0, page, pendingFrame, painting = false;
const pending = new Map();
const commands = [];
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
const ready = new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
});
});
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const errors = [];
try {
await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(), listeners = new Map(); let next = 0;
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
throw Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
});
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(150);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
await page.waitForTimeout(100);
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
await mkdir('output', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(errors, []);
await writeFile('output/browser-interaction.json', JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, passed: ['Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer bursts coalesce', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron pages, autoscroll cleanup, pointer coalescing and center new-tab action');
} finally {
await browser.close();
await rpc('shutdown').catch(() => {}); child.kill();
}
+213
View File
@@ -0,0 +1,213 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from 'node:module';
import { mkdir } 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: 1100, height: 850 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
const check = window.webDataTest = { data, snapshot, calls: [], hold: [], pending: [], failNext: {} };
let sequence = 0;
const callbacks = new Map();
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-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') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'web-data-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
if (args.session !== 'web-data-session') throw Error('Missing browser session');
const operation = args.command, details = args.args || {}, key = `${operation}:${details.profileId}`;
check.calls.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('combobox', { name: 'Profile', exact: true });
const kind = section.getByRole('combobox', { name: 'Web data type', exact: true });
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.webDataTest.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.webDataTest.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.webDataTest;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
try {
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await kind.selectOption('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.webDataTest.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await profile.selectOption('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await kind.selectOption('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await profile.selectOption('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await profile.selectOption('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await profile.selectOption('user');
await settle();
const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.inputValue(), 'user');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
await page.evaluate(() => { window.webDataTest.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.webDataTest.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.webDataTest.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.webDataTest.calls.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
for (const dataType of ['cookies', 'history']) {
await kind.selectOption(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
}
}
assert.deepEqual(errors, []);
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
} catch (error) {
console.error(await page.locator('body').innerText());
console.error('Page errors:', errors);
throw error;
} finally { await browser.close(); }
+106
View File
@@ -0,0 +1,106 @@
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: 1280, height: 800 } });
const page = await context.newPage();
page.setDefaultTimeout(10000);
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map(); let next = 0;
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
window.builtinCheck = { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'window-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'workspace_last_path') return null;
if (command === 'workspace_recent') return [];
if (command === 'plugins_snapshot') return { root: 'test', plugins: [
{ manifest: { schemaVersion: 1, id: 'org.test.boards', name: 'Boards', author: 'Test', description: '', version: '0.1.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'fixture', enabled: true, installedAt: 1, path: '', error: null, removal: false },
...(window.builtinCheck.legacy && !window.builtinCheck.removed ? [{ manifest: { schemaVersion: 1, id: 'runestone.browser', name: 'Browser', author: 'Test', description: '', version: '0.1.6', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'old', enabled: true, installedAt: 1, path: '', error: null, removal: false }] : [])
] };
if (command === 'plugins_load') {
window.builtinCheck.loads.push(args.id);
if (args.id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.builtinCheck.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.builtinCheck.cleanups.push(id); };
}});
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
}`;
}
if (command === 'browser_request') {
if (args.session !== 'window-session') throw Error('Missing browser session');
window.builtinCheck.commands.push(args.command);
if (args.command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (args.command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.args.tabId);
if (args.command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.args.tabId); tab.url = args.args.input; tab.title = 'Example'; }
if (args.command === 'settings') Object.assign(snapshot.settings, args.args);
return structuredClone(snapshot);
}
if (command.startsWith('plugin:window|')) return false;
throw Error('Unhandled IPC: ' + command);
}
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5174');
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
assert.equal(await page.getByRole('combobox', { name: 'Browser profile' }).inputValue(), 'user');
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async () => { const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); openPluginView('org.test.boards', 'board-a'); });
const before = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.builtinCheck.mounts.includes('board-b') && window.builtinCheck.cleanups.includes('board-a'));
const after = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
assert.deepEqual(after, before);
await page.getByRole('button', { name: 'Source control', exact: true }).click();
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/builtin-browser-${theme}.png` });
}
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
assert.equal(await page.getByRole('combobox', { name: 'Profile', exact: true }).inputValue(), 'user');
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-settings-${theme}.png` });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
assert.deepEqual(errors, []);
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
} catch (error) {
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}), errors);
throw error;
} finally { await browser.close(); }
+15
View File
@@ -0,0 +1,15 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseCustomTheme } from "../src/lib/theme/customThemes.ts";
const palette = { bg: "#123", text: "#abcdef", accent: "#AABBCC" };
const theme = { schema: 1, id: "my-theme", name: "My theme", light: palette, dark: palette };
test("theme files accept explicit color tokens in both appearances", () => {
assert.deepEqual(parseCustomTheme(theme), theme);
});
test("theme files reject CSS injection, unknown tokens, and incomplete palettes", () => {
for (const dark of [{ ...palette, bg: "url(https://invalid.test)" }, { ...palette, position: "fixed" }, { bg: "#000" }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, dark }));
}
assert.throws(() => parseCustomTheme({ ...theme, id: "../unsafe" }));
});
+142
View File
@@ -0,0 +1,142 @@
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: 1280, height: 900 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-files-smoke";
const files = new Map([
["note.md", "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n"],
["hello.txt", "print('hello')\n"],
["notes/existing.md", "Existing note"],
]);
window.editorFilesTest = { files, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
window.editorFilesTest.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: "editor-files-smoke", 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 + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), 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("path already exists");
files.set(args.rel, ""); return;
}
if (command === "workspace_rename") {
if (files.has(args.to)) throw new Error("destination already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === "workspace_search") return [];
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const row = name => page.locator(`[data-tree-rel="${name}"]`);
async function enterName(name) {
await page.locator("#text-request").fill(name);
await page.getByRole("button", { name: "Continue", exact: true }).click();
}
async function modelDetails() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await row("note.md").waitFor();
await page.getByRole("button", { name: "New file", exact: true }).click();
await enterName("LICENSE");
await row("LICENSE").waitFor();
await page.evaluate(() => window.editorFilesTest.files.set("LICENSE", "Keep this content"));
await page.getByRole("button", { name: "New file", exact: true }).click();
await enterName("LICENSE");
await page.getByText("path already exists", { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.get("LICENSE")), "Keep this content");
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("LICENSE 2")), false);
await row("notes").click({ button: "right" });
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
await enterName("hello_world.py");
await row("notes/hello_world.py").waitFor();
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("notes/hello_world.py.md")), false);
await row("hello.txt").dblclick();
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
await row("hello.txt").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
assert.equal(await row("hello.txt").locator("input.rename").inputValue(), "hello.txt");
await row("hello.txt").locator("input.rename").fill("hello.py");
await page.keyboard.press("Enter");
await row("hello.py").waitFor();
await page.waitForFunction(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.getLanguageId() === "python");
});
const code = await modelDetails();
assert.equal(code.value, "print('hello')\n");
assert.equal(code.fontSize, 13);
await page.keyboard.press("Control+e");
assert.equal((await modelDetails()).fontSize, code.fontSize, "Code size stays the same in both layouts");
await row("note.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerTest = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
const nativeAllowed = await page.evaluate(() => {
window.writerTest.dispatch({ selection: { anchor: 3 } });
const line = document.querySelector(".cm-line"), rect = line.getBoundingClientRect();
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: rect.left + 15, clientY: rect.top + 5 });
line.dispatchEvent(event);
return !event.defaultPrevented;
});
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
assert.equal(await page.getByRole("menu").count(), 0);
await page.evaluate(() => { window.writerTest.focus(); });
await page.keyboard.press("Shift+F10");
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.evaluate(() => window.writerTest.dispatch({ selection: { anchor: 0, head: 9 } }));
await page.getByText("Mispelled text.", { exact: true }).click({ button: "right" });
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".live-writer td").first().click({ button: "right" });
await page.getByRole("menu", { name: "Table actions", exact: true }).waitFor();
await page.keyboard.press("Escape");
await page.locator(".writer-cell-editor").click();
await page.keyboard.press("ArrowRight");
assert.equal(await page.locator(".writer-cell-editor p").evaluate(node => {
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
node.dispatchEvent(event);
return !event.defaultPrevented;
}), true, "Active table text permits the native spelling menu");
await page.locator(".cm-line").first().click();
}
assert.deepEqual(errors, []);
console.log("PASS: exact filenames, extensionless creation, extension rename and language, equal code font sizes, native spelling event, shared selection and table menus in both themes");
} finally { await browser.close(); }
+152
View File
@@ -0,0 +1,152 @@
import { createRequire } from "node:module";
import { mkdir } 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: 1280, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\editor-interactions-smoke";
const files = new Map([
["note.md", "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n"],
["other.md", "# Other document\n\nKeep the original tab.\n"],
]);
const callbacks = new Map(), listeners = new Map();
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
window.editorTest = { files, calls: [], emit };
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.editorTest.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") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "editor-interactions-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".runestone/")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:opener|open_url" || command.startsWith("spelling_menu_")) return;
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
async function writer() {
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
async function top() {
await writer();
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
await page.locator('[data-tree-rel="note.md"]').dblclick();
await writer();
const code = page.locator(".writer-code-line").filter({ hasText: "pnpm install" });
await code.scrollIntoViewIfNeeded();
const points = await page.evaluate(() => {
const view = window.writerView, from = view.state.doc.toString().indexOf("pnpm install");
return { from: view.coordsAtPos(from), to: view.coordsAtPos(from + 12) };
});
await page.mouse.move(points.from.left + 1, (points.from.top + points.from.bottom) / 2);
await page.mouse.down();
await page.mouse.move(points.to.left, (points.to.top + points.to.bottom) / 2, { steps: 8 });
await page.mouse.up();
assert.match(await page.evaluate(() => { const view = window.writerView; return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); }), /pnpm install/);
await page.getByRole("button", { name: "Copy code", exact: true }).first().click();
assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, "\n"), "pnpm install --frozen-lockfile\npnpm check\npnpm test\n");
console.log("PASS: first drag selects code and the copy button copies only the code body");
await page.evaluate(() => { const view = window.writerView; view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("preserve =") + 5 }, scrollIntoView: true }); view.focus(); });
await page.keyboard.type("X");
await page.waitForTimeout(250);
const saved = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.ok(saved.scroll > 1000);
await page.locator('[data-tree-rel="other.md"]').dblclick();
await writer();
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await writer();
await page.waitForTimeout(250);
const restored = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
assert.equal(restored.head, saved.head);
assert.equal(restored.doc, saved.doc);
assert.ok(Math.abs(restored.caret.top - saved.caret.top) < 3, JSON.stringify({ saved, restored }));
await page.evaluate(() => { window.dispatchEvent(new Event("blur")); window.dispatchEvent(new Event("focus")); });
await page.waitForTimeout(150);
assert.equal(await page.evaluate(() => window.writerView.state.selection.main.head), saved.head);
console.log("PASS: code edit, caret, and scroll survive tab and window focus changes");
await top();
await page.locator('.writer-link[data-href="other.md"]').click({ modifiers: ["Control"] });
await page.getByRole("tab", { name: "other.md", exact: true }).waitFor();
assert.equal(await page.getByRole("tab", { name: "note.md", exact: true }).count(), 1);
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await top();
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
await page.waitForFunction(() => window.editorTest.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
const linkPoint = await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
const position = view.getModel().getPositionAt(view.getValue().indexOf("[Local]") + 3);
view.revealPositionInCenter(position);
view.setPosition(position); view.focus();
return position;
});
await page.waitForTimeout(300);
const point = await page.evaluate(async position => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected), rect = view.getDomNode().getBoundingClientRect(), coords = view.getScrolledVisiblePosition(position);
return { x: rect.left + coords.left + 2, y: rect.top + coords.top + coords.height / 2 };
}, linkPoint);
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
console.log("PASS: Writer and IDE Ctrl+click open workspace links while retaining the source tab");
await page.getByRole("tab", { name: "note.md", exact: true }).click();
await page.keyboard.press("Control+e");
await top();
await mkdir(".audit", { recursive: true });
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => {
const { applyAppearance, parseAppearance } = await import("/src/lib/theme/appearance.ts");
applyAppearance({ ...parseAppearance(null), mode });
}, theme);
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
await page.screenshot({ path: `.audit/editor-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
assert.deepEqual(writing, reading);
await page.screenshot({ path: `.audit/reader-typography-${theme}.png` });
await page.getByRole("group", { name: "Document view", exact: true }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await top();
}
await page.setViewportSize({ width: 640, height: 750 });
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.screenshot({ path: ".audit/editor-typography-narrow.png" });
assert.ok(await page.locator(".cm-content").evaluate(node => node.getBoundingClientRect().width <= node.closest(".cm-scroller").getBoundingClientRect().width + 1));
const spelling = await page.evaluate(async () => {
const { isSpellingTarget } = await import("/src/lib/editor/spellingMenu.ts");
const area = document.createElement("textarea"); area.spellcheck = true; document.body.append(area);
const active = isSpellingTarget(area); area.readOnly = true; const readOnly = isSpellingTarget(area); area.remove();
return { active, readOnly };
});
assert.deepEqual(spelling, { active: true, readOnly: false });
assert.deepEqual(errors, []);
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
} finally { await browser.close(); }
+23
View File
@@ -0,0 +1,23 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { documentLinks, documentLinkAt } from "../src/lib/editor/documentLinks.ts";
test("document links keep complete source ranges and decode Markdown destinations", () => {
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_(b)) and [[Another note|Alias]]';
const links = documentLinks(source);
assert.deepEqual(links.map(link => [link.kind, link.target]), [["md", "notes/two words.md"], ["md", "https://example.com/a_(b)"], ["wiki", "Another note"]]);
for (const link of links) {
assert.equal(documentLinkAt(source, link.from + 2)?.target, link.target);
assert.equal(documentLinkAt(source, link.to - 1)?.target, link.target);
}
});
test("literal code and images cannot become document links", () => {
const source = '![Image](image.png) `https://example.com`\n\n```md\n[Hidden](hidden.md)\n[[Hidden]]\n```\n\n[Open](open.md)';
assert.deepEqual(documentLinks(source).map(link => link.target), ["open.md"]);
});
test("bare and angle links omit prose punctuation and preserve balanced parentheses", () => {
const source = 'Go to https://example.com/a_(b). Next (<https://example.org>). Mail <mailto:[email protected]>.';
assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:[email protected]"]);
});
+6 -4
View File
@@ -183,15 +183,17 @@ try {
}, "../attachments/typed.svg");
await page.locator('img[alt="Wiki image"]').waitFor();
await save();
await page.getByRole("button", { name: "Read", exact: true }).click();
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Edit", exact: true }).focus();
await page.keyboard.press("ArrowRight");
await page.locator(".md-page .md-image-frame").first().hover();
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
await page.keyboard.press("Escape");
// Source mode uses the same drop flow; the batch is one undo step.
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Read", exact: true }).focus();
await page.keyboard.press("Home");
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
@@ -213,7 +215,7 @@ try {
await page.evaluate(() => { window.__TEST__.failWrite = false; });
// File drops over a rendered widget are handled by the editor's capture listener.
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
+152
View File
@@ -0,0 +1,152 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../node_modules/playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\kanban-smoke';
const files = new Map([['a.md', '# Alpha\n\nTemplate body.\n'], ['b.md', '# Beta\n'], ['folder/keep.md', '# Keep\n'], ['.runestone/config.json', '{}']]);
const calls = [], callbacks = new Map(); let id = 0;
window.workspaceSmoke = { files, calls, transfer: null };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: callback => { callbacks.set(++id, callback); return id; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === 'plugin:event|listen') return ++id;
if (command === 'plugin:event|unlisten' || command === 'spelling_menu_install' || command === 'spelling_menu_uninstall') return;
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'kanban-smoke', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw Error('File missing'); return files.get(args.rel); }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error('Save conflict');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('Exists'); files.set(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) || (!args.rel && path.startsWith('.runestone/') && !args.showInternal)) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw Error('Destination exists');
const matches = [...files].filter(([path]) => path === args.from || path.startsWith(args.from + '/'));
if (!matches.length) throw Error('Source missing');
for (const [path, contents] of matches) { files.delete(path); files.set(args.to + path.slice(args.from.length), contents); }
return;
}
if (command === 'workspace_copy') {
const path = (args.parent ? args.parent + '/' : '') + args.rel.split('/').pop();
if (files.has(path)) throw Error('Destination exists');
files.set(path, files.get(args.rel)); return { rel_path: path, name: path.split('/').pop(), kind: 'file' };
}
if (command === 'workspace_open_window') { window.workspaceSmoke.transfer = args.transfer; return; }
if (command === 'workspace_abs_path') return root + '\\' + args.rel;
if (command === 'workspace_recent') return [root];
if (command === 'workspace_search') return [];
if (command === 'plugin:dialog|message') return 'Cancel';
if (command === 'plugins_snapshot') return { plugins: [], issues: [] };
if (command.startsWith('plugin:window|') || command === 'workspace_open_terminal' || command === 'workspace_open_default') return;
if (command === 'browser_stop') return;
throw Error('Unhandled IPC: ' + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
page.setDefaultTimeout(15000);
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const menu = label => page.getByRole('menuitem', { name: label, exact: true });
try {
await page.goto(url);
await row('a.md').click();
await page.locator('.cm-content').waitFor();
await page.locator('.mode-switcher').first().hover();
await page.waitForFunction(() => document.querySelector('.mode-switcher')?.classList.contains('expanded'), null, { timeout: 500 });
await page.mouse.move(500, 400);
await row('a.md').click({ button: 'right' });
await menu('Save as template').click();
await page.getByRole('textbox', { name: 'Template name' }).fill('Meeting');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('.runestone/templates/Meeting.md'));
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.getByRole('button', { name: 'New note', exact: true }).click();
await menu('Meeting').click();
await page.getByRole('tab', { name: /Meeting/ }).waitFor();
assert.equal(await page.evaluate(() => window.workspaceSmoke.files.get('Meeting.md')), '# Alpha\n\nTemplate body.\n');
const before = await page.getByRole('tab', { selected: true }).getAttribute('data-path');
await page.keyboard.press('Control+Tab');
assert.notEqual(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await page.keyboard.press('Control+Shift+Tab');
assert.equal(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
await row('b.md').click({ button: 'right' }); await menu('Cut').click();
await row('folder').click({ button: 'right' }); await menu('Paste').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').click({ button: 'right' }); await menu('Undo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Redo file move').click();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await row('folder').focus();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
const sourceBox = await row('b.md').boundingBox(), folderBox = await row('folder').boundingBox();
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
await page.mouse.down();
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
await page.keyboard.press('Control+z');
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
await row('folder').click({ button: 'right' }); await menu('Open in terminal').click();
assert.ok(await page.evaluate(() => window.workspaceSmoke.calls.some(call => call.command === 'workspace_open_terminal' && call.args.rel === 'folder')));
await page.keyboard.press('Control+,');
const settingsPage = await context.newPage();
await settingsPage.goto(url + '/?settingsWindow=true');
await settingsPage.getByRole('switch', { name: 'Show .runestone folder' }).check();
await settingsPage.getByRole('button', { name: 'Appearance', exact: true }).click();
const theme = { schema: 1, id: 'smoke', name: 'Smoke theme', light: { bg: '#fefefe', text: '#222222', accent: '#334499' }, dark: { bg: '#181820', text: '#eeeeee', accent: '#aabbff' } };
await settingsPage.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: 'smoke.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(theme)) });
await settingsPage.waitForFunction(() => document.documentElement.dataset.palette === 'custom:smoke');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#181820');
await settingsPage.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption('light');
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#fefefe');
await mkdir('.audit', { recursive: true });
await settingsPage.screenshot({ path: '.audit/kanban-custom-theme-light.png' });
await settingsPage.close();
await row('.runestone').waitFor();
await page.getByRole('tab', { name: /Meeting/ }).click();
const editor = page.locator('.cm-content'); await editor.click(); await page.keyboard.press('Control+End'); await page.keyboard.type('Unsaved transfer');
await page.getByRole('tab', { name: /Meeting/ }).click({ button: 'right' });
await menu('Open in new window').click();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
const token = await page.evaluate(() => window.workspaceSmoke.transfer);
const target = await context.newPage();
target.on('pageerror', error => errors.push(error.message));
await target.goto(url + '/?tabTransfer=' + token);
await target.getByRole('tab', { name: /Meeting/ }).waitFor();
await target.waitForFunction(() => document.querySelector('.cm-content')?.textContent.includes('Unsaved transfer'));
await page.getByRole('tab', { name: /Meeting/ }).waitFor({ state: 'detached' });
await page.evaluate(() => { window.workspaceSmoke.transfer = null; });
const draggedTab = page.getByRole('tab').first();
const draggedPath = await draggedTab.getAttribute('data-path');
const tabBox = await draggedTab.boundingBox();
await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
await page.mouse.down();
await page.mouse.move(1480, 180, { steps: 12 });
await page.mouse.up();
await page.waitForFunction(() => window.workspaceSmoke.transfer);
assert.notEqual(await page.evaluate(() => window.workspaceSmoke.transfer), token);
assert.equal(await page.locator(`[role="tab"][data-path="${draggedPath}"]`).count(), 1, 'Keep the source tab until the new window accepts it');
assert.equal(errors.length, 0, errors.join('\n'));
console.log('PASS: templates, tab shortcuts, move undo/redo, terminal action, internal folder, theme import, and acknowledged unsaved tab transfer');
} finally { await browser.close(); }
+28 -1
View File
@@ -2,10 +2,37 @@ import assert from "node:assert/strict";
import test from "node:test";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts";
import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
test("prose directly after a table stays outside the table and its edit range", () => {
for (const eol of ["\n", "\r\n"]) {
const body = table.replaceAll("\n", eol);
const tail = `${eol}Plain text${eol}More text with an escaped \\| pipe${eol}# Heading`;
const source = body + tail;
assert.equal(parseMarkdownTable(source)?.end, body.length);
assert.equal(parseMarkdownTable(source)?.rows.length, 3);
assert.equal(appendTableRow(source), body + `${eol}| | |` + tail);
assert.equal(appendTableColumn(source), appendTableColumn(body) + tail);
assert.equal(replaceTableCell(source, 3, 0, "changed"), source);
const html = renderMarkdownHtml(source, new Map());
assert.equal((html.match(/<tr>/g) || []).length, 2);
assert.match(html, /<\/table>[\s\S]*<p>Plain text/);
const sections = renderMarkdownSections(source, new Map());
assert.equal(sections[0].end, body.length + eol.length);
assert.equal(source.slice(sections[1].start).startsWith("Plain text"), true);
}
});
test("table boundaries distinguish escaped pipes from delimiters and work in nested blocks", () => {
const body = "| A | B |\n| --- | --- |\nOne | Two\n| short |\n| escaped \\| pipe | value |\n| even \\\\| delimiter |";
assert.equal(parseMarkdownTable(body + "\nProse \\| literal")?.rows.length, 6);
assert.equal((renderMarkdownHtml(body + "\nProse \\| literal", new Map()).match(/<tr>/g) || []).length, 5);
assert.match(renderMarkdownHtml("> | A |\n> | --- |\n> | B |\n> Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
assert.match(renderMarkdownHtml("- Item\n\n | A |\n | --- |\n | B |\n Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
});
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
assert.equal(extractedCellMarkdown([
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
+71 -5
View File
@@ -16,12 +16,15 @@ await page.addInitScript(() => {
window.tabMenuTest = { 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: () => ++sequence, unregisterCallback: () => {},
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") return ++sequence;
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
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); }
@@ -65,7 +68,10 @@ try {
await tab.waitFor();
await page.locator(".cm-content").waitFor();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
@@ -105,7 +111,8 @@ try {
await page.keyboard.press("ArrowLeft");
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
await page.getByText("Original text.", { exact: true }).click();
await page.keyboard.press("Shift+F10");
const editor = menu("Markdown text actions");
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
await item("Paragraph").focus();
@@ -116,6 +123,55 @@ try {
await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 0, name: "", label: "", shortcut: "", kind: 3, enabled: false, checked: false, children: [] },
{ id: 73, name: "cut", label: "Cu&t", shortcut: "Ctrl+X", kind: 0, enabled: false, checked: false, children: [] },
{ id: 74, name: "copy", label: "&Copy", shortcut: "Ctrl+C", kind: 0, enabled: true, checked: false, children: [] },
{ id: 75, name: "spellCheck", label: "Spell check", shortcut: "", kind: 1, enabled: true, checked: true, children: [] },
] }));
const spelling = menu("Spelling actions");
await spelling.waitFor();
assert.deepEqual(await metrics(spelling), reference, "Spelling and file menus share styles");
assert.equal(await item("Add to dictionary").locator("svg.action-icon").count(), 1);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "Spell check" }).getAttribute("aria-checked"), "true");
await page.keyboard.press("ArrowDown");
await page.keyboard.press("ArrowDown");
assert.equal(await item("Copy Ctrl+C").evaluate(node => node === document.activeElement), true, "Spelling keyboard navigation skips disabled commands");
await page.screenshot({ path: ".audit/menu-spelling-" + theme + ".png" });
await page.keyboard.press("Home");
await page.keyboard.press("Enter");
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "spelling-1", command: 71 });
assert.equal(await page.locator(".cm-content").evaluate(node => node === document.activeElement), true);
async function emitSpelling(request) {
await page.evaluate(request => window.spellingTest.emit({ request, items: [
{ id: 81, name: "suggestion", label: "Replacement", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
] }), request);
await spelling.waitFor();
}
await emitSpelling("cancel");
await dismiss();
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "cancel", command: null });
await emitSpelling("outside");
await row.click();
await spelling.waitFor({ state: "detached" });
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "outside", command: null });
await emitSpelling("old");
await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss();
await page.evaluate(() => {
const input = document.createElement("input");
input.spellcheck = false;
document.body.append(input);
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
window.spellingTest.emit({ request: "ordinary-input", items: [] });
input.remove();
});
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true });
}
await page.setViewportSize({ width: 420, height: 320 });
await page.evaluate(async () => {
@@ -124,7 +180,10 @@ try {
{ label: "Without icon", run: () => {} },
{ label: "With icon", icon: "copy", run: () => {} },
{ label: "Unavailable", icon: "trash", disabled: true },
{ label: "More", icon: "plus", children: Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })) },
{ label: "More", icon: "plus", children: [
{ label: "Languages", children: [{ label: "English", checked: true, run: () => {} }] },
...Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })),
] },
], () => root.remove(), "Edge test");
});
const edge = menu("Edge test");
@@ -135,6 +194,13 @@ try {
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
await page.keyboard.press("ArrowRight");
const sub = menu("More");
await page.keyboard.press("ArrowRight");
assert.equal(await sub.isVisible(), true, "Nested submenus keep the parent visible");
assert.equal(await menu("Languages").isVisible(), true);
assert.equal(await page.getByRole("menuitemcheckbox", { name: "English" }).evaluate(node => node === document.activeElement), true);
await page.keyboard.press("ArrowLeft");
assert.equal(await menu("Languages").isVisible(), false);
assert.equal(await item("Languages").evaluate(node => node === document.activeElement), true);
for (const panel of [edge, sub]) {
const bounds = await panel.boundingBox();
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
+145
View File
@@ -0,0 +1,145 @@
// 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_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function open(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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5173');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
const formatted = '# Copied heading\n\n## Links\n\n[Reference](https://example.com) and [[second|Another note]]\n\n**Bold**, *italic*, and `code`.\n\n- A list item\n';
await page.evaluate(text => { window.__TEST__.files.set('notes/source.md', text); window.__TEST__.files.set('notes/pasted.md', ''); }, formatted);
await open('source.md');
await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Control+c');
await open('pasted.md');
await writer();
for (let iteration = 0; iteration < 12; iteration++) {
await page.locator('.cm-content').click();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await expectWriter('');
await page.keyboard.press('Control+v');
await expectWriter(formatted);
assert.equal(await page.locator('.live-writer .cm-editor').count(), 1, 'One mounted editor');
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('notes/pasted.md').replace(/\r\n?/g, '\n')), formatted);
if (iteration === 5) {
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.keyboard.press('Control+e');
await expectWriter(formatted);
}
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'pasted.md', exact: true }).click();
await expectWriter(formatted);
}
// Clipboard formats can use different line endings than the destination.
for (const lineBreak of ['\n', '\r\n', '\r']) {
await page.evaluate(({ text, lineBreak }) => {
const view = window.__WRITER__;
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
const clipboardData = new DataTransfer();
clipboardData.setData('text/plain', text.replace(/\n/g, lineBreak));
view.contentDOM.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }));
}, { text: formatted, lineBreak });
await expectWriter(formatted);
assert.equal(await page.evaluate(() => window.__WRITER__.state.doc.lines), formatted.split('\n').length);
await page.keyboard.press('Control+s');
const synchronized = await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const model = monaco.editor.getModels().find(model => model.uri.path.endsWith('/pasted.md'));
const source = window.__WRITER__.state.doc.sliceString(0, undefined, model.getEOL());
return source === model.getValue() && source === window.__TEST__.files.get('notes/pasted.md');
});
assert.equal(synchronized, true, 'Writer, model, and saved source agree');
}
assert.deepEqual(errors, []);
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
} finally { await browser.close(); }
+24 -25
View File
@@ -14,7 +14,7 @@ await context.addInitScript(() => {
let sequence = 0;
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("runestone.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
const modules = {
"runestone.local-autocomplete": `export function activate(api) {
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
@@ -26,11 +26,11 @@ await context.addInitScript(() => {
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
return () => { window.accessTest.disposed++; };
}});
api.registerCommand({ id: 'configure', title: 'Configure local autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
}`,
"runestone.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', run() {
"org.example.browser": `export function activate(api) {
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
}});
}`,
@@ -46,6 +46,8 @@ await context.addInitScript(() => {
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; }
if (command === 'browser_connect') return 'test-session';
if (command === 'browser_stop') return;
if (command === 'workspace_last_path') return null;
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) };
if (command === 'plugins_load') return modules[args.id];
@@ -66,29 +68,26 @@ const main = await context.newPage(), settings = await context.newPage();
for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); }
try {
await main.goto(origin);
const open = main.getByRole('button', { name: 'Open tab or view', exact: true });
await open.click();
const menu = main.getByRole('menu', { name: 'Open tab or view', exact: true });
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem').count(), 3);
assert.equal(await menu.getByText('Local Autocomplete').count(), 0);
await open.click(); await menu.waitFor({ state: 'detached' });
await open.focus(); await main.keyboard.press('Enter'); await main.keyboard.press('End'); await main.keyboard.press('Escape');
assert(await open.evaluate(element => element === document.activeElement));
await open.click(); await menu.getByRole('menuitem', { name: /New browser tab/ }).click();
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor();
assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0);
assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 0);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click();
await main.getByText('Task content', { exact: true }).waitFor();
await main.evaluate(async () => {
const { runPluginCommand } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
await runPluginCommand('org.example.browser', 'new-tab');
});
await main.getByText('Browser content', { exact: true }).waitFor();
await open.click(); assert.equal(await menu.getByRole('menuitem').count(), 3);
await menu.getByRole('menuitem', { name: /Task summary/ }).click();
await main.evaluate(async () => {
const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
openPluginView('org.example.tasks', 'dialog');
});
await main.getByRole('dialog', { name: 'Task summary' }).waitFor();
await main.keyboard.press('Escape');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'light');
await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu-light.png' }); await main.keyboard.press('Escape');
await main.evaluate(() => document.documentElement.dataset.theme = 'dark');
await main.getByRole('button', { name: 'Commands', exact: true }).click();
await main.getByRole('menuitem', { name: /Failed command/ }).click();
await main.getByRole('alert').filter({ hasText: 'Command failed for test' }).waitFor();
await main.getByRole('button', { name: 'Dismiss', exact: true }).click();
for (const theme of ['dark', 'light']) {
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await main.screenshot({ path: `.audit/plugin-access-${theme}.png` });
}
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click();
await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model');
@@ -109,7 +108,7 @@ try {
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' });
await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' });
assert.deepEqual(errors, []);
console.log('Plugin access smoke passed: launchers, dynamic tabs, keyboard focus, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
console.log('Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
} catch (error) {
await settings.screenshot({ path: '.audit/plugin-access-failure.png' });
console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors);
+59
View File
@@ -0,0 +1,59 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import { ContributionRegistry } from "../src/lib/plugins/registry.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
test("Git and file access stop before plugin cleanup", async () => {
const calls: unknown[] = [];
let api!: PluginApi;
const registry = new ContributionRegistry();
const session = new ExternalSession("test.git", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
openFile: async path => { calls.push(path); },
git: {
status: async () => ({ available: true, repository: true, branch: "main", changes: [] }),
diff: async (path, staged) => { calls.push([path, staged]); return "diff"; },
stage: async paths => { calls.push(paths); }, unstage: async paths => { calls.push(paths); },
commit: async message => { calls.push(message); }, blame: async () => null,
push: async () => { calls.push('push'); }, pull: async () => { calls.push('pull'); }, graph: async () => ({ commits: [] }),
},
}, () => {}, () => {}, registry);
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
await api.openFile!("notes.md");
assert.equal(await api.git!.diff("notes.md", true), "diff");
await api.git!.stage(["notes.md"]);
assert.deepEqual(calls, ["notes.md", ["notes.md", true], ["notes.md"]]);
await api.git!.push();
await api.git!.pull();
assert.deepEqual(await api.git!.graph(), { commits: [] });
assert.deepEqual(calls.slice(-2), ['push', 'pull']);
await session.stop();
assert.equal(registry.get("git"), undefined);
assert.throws(() => api.openFile!("notes.md"), /disabled/);
for (const action of [() => api.git!.push(), () => api.git!.pull(), () => api.git!.graph()]) assert.throws(action, /disabled/);
for (const action of [() => api.git!.status(), () => api.git!.diff("a", false), () => api.git!.stage(["a"]), () => api.git!.unstage(["a"]), () => api.git!.commit("a"), () => api.git!.blame("a", 1)]) assert.throws(action, /disabled/);
});
test("view replacement rejects unknown destinations and stops after disposal", async () => {
let api!: PluginApi;
const calls: unknown[] = [];
const session = new ExternalSession("test.boards", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
await session.start({ activate(value) {
api = value;
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
} });
api.replaceView!("a", "b");
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
await session.stop();
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
});
+4 -2
View File
@@ -167,8 +167,10 @@ try {
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' });
await settingsPage.keyboard.press('Escape');
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
await page.getByRole('button', { name: /Show workspace overview/ }).click();
await page.evaluate(async pluginId => {
const { runPluginCommand } = await import('/src/lib/plugins/external.ts');
await runPluginCommand(pluginId, 'show-overview');
}, manifest.id);
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
await view.getByText(/files and folders in this workspace/).waitFor();
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
+60 -1
View File
@@ -111,6 +111,62 @@ try {
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
await page.goto(url);
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
await tab("New tab").waitFor();
for (const close of ["button", "middle", "shortcut", "all"]) {
const before = await tab("New tab").getAttribute("data-path");
if (close === "button") await page.getByRole("button", { name: "Close New tab", exact: true }).click();
if (close === "middle") await tab("New tab").click({ button: "middle" });
if (close === "shortcut") await page.keyboard.press("Control+w");
if (close === "all") {
await menu("New tab");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
}
await page.waitForFunction(before => {
const tabs = document.querySelectorAll('.header [role="tab"]');
return tabs.length === 1 && tabs[0].getAttribute("data-path") !== before;
}, before);
assert.equal(await tab("New tab").getAttribute("aria-selected"), "true");
}
for (const name of ["a.md", "b.md", "c.md", "note-0.md"]) await openFile(name);
await page.getByRole("textbox", { name: "Writing editor", exact: true }).filter({ hasText: "# note-0.md" }).waitFor();
for (const width of [880, 1280, 1440]) {
await page.setViewportSize({ width, height: 1000 });
await settle();
for (const theme of ["dark", "light"]) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
const dimensions = await page.locator(".header").evaluate(header => {
const bar = header.querySelector('[role="tablist"]');
const rows = [...bar.querySelectorAll(".tab")];
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]');
const bounds = bar.getBoundingClientRect();
return {
overflow: bar.scrollWidth - bar.clientWidth,
left: bounds.left,
navigationRight: header.querySelector(".header-left").getBoundingClientRect().right,
tabWidth: Math.min(...rows.map(row => row.getBoundingClientRect().width)),
gap: plus.getBoundingClientRect().left - Math.min(bounds.right, rows.at(-1).getBoundingClientRect().right),
fits: header.scrollWidth <= header.clientWidth,
};
});
if (width >= 1280) assert.ok(dimensions.overflow <= 1, JSON.stringify(dimensions));
assert.ok(Math.abs(dimensions.left - dimensions.navigationRight) <= 2, JSON.stringify(dimensions));
assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions));
assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions));
assert.ok(dimensions.fits);
const plus = page.getByRole("button", { name: "New tab (Ctrl T)", exact: true });
await plus.evaluate(button => button.blur());
await plus.focus();
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl T)" }).waitFor();
await page.keyboard.press("Escape");
await mkdir(".audit", { recursive: true });
await page.locator(".header").screenshot({ path: `.audit/compact-tabs-${width}-${theme}.png` });
}
}
await menu("note-0.md");
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
console.log("PASS: the last tab becomes a new tab, tabs retain usable widths, and the adjacent plus button has a focus tooltip");
await openFile("a.md");
await openFile("b.md");
await openView("Overview");
@@ -232,7 +288,9 @@ try {
await settingsPage.close();
await page.goto(`${url}?no-workspace`);
await tab("New tab").waitFor();
await openView("Overview");
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
await openView("Browser");
await drag("Browser", "Overview");
assert.deepEqual(await order(), ["Browser", "Overview"]);
@@ -242,7 +300,8 @@ try {
await tab("Browser").click({ button: "middle" });
assert.deepEqual(await order(), ["Overview"]);
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
assert.equal(await page.getByRole("tab").count(), 0);
await tab("New tab").waitFor();
assert.deepEqual(await order(), ["New tab"]);
assert.deepEqual(errors, []);
console.log("PASS: plugin tabs reorder and close without an open workspace");
} catch (error) {
+4 -4
View File
@@ -7,15 +7,15 @@ test("missing or damaged preferences keep safe defaults", () => {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds })), { autosaveEnabled: false, autosaveSeconds: 5 });
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10 });
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
});
test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds };
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
}
@@ -25,7 +25,7 @@ test("invalid changes never reach storage and storage failures reach the caller"
let writes = 0;
const storage = { setItem: () => { writes++; } };
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds }));
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
}
assert.equal(writes, 0);
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
+109
View File
@@ -0,0 +1,109 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
const errors = [];
await mkdir(".audit", { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
const callbacks = new Map();
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
})) };
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage();
const settings = await context.newPage();
for (const page of [main, settings]) {
page.setDefaultTimeout(7000);
page.on("pageerror", error => errors.push(error.message));
}
await main.goto(origin);
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
const header = settings.locator("dialog > header");
const mainHeader = main.locator(".header");
assert.equal((await header.boundingBox()).height, (await mainHeader.boundingBox()).height, "Settings and main title bars share their height");
for (const name of ["Minimize window", "Maximize window", "Close window"]) {
const a = await main.getByRole("button", { name, exact: true }).boundingBox();
const b = await settings.getByRole("button", { name, exact: true }).boundingBox();
assert.equal(a.width, b.width);
assert.equal(a.height, b.height, `${name} has the same dimensions in both windows`);
}
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
await settings.getByRole("switch", { name: "Example plugin 1", exact: true }).waitFor();
const content = settings.locator(".content");
const pluginRows = content.locator(".row");
assert.equal(await pluginRows.count(), 7);
for (const theme of ["dark", "light"]) {
await settings.evaluate(value => document.documentElement.dataset.theme = value, theme);
for (const width of [1152, 540, 360]) {
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 420 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
assert(await content.evaluate(element => element.scrollWidth <= element.clientWidth), "The plugin content does not scroll horizontally");
const rows = await pluginRows.evaluateAll(elements => elements.map(element => element.getBoundingClientRect().height));
if (width === 1152) {
assert(rows.every(height => height <= 100), `Desktop plugin rows stay compact: ${rows}`);
const count = await pluginRows.evaluateAll(elements => {
const container = elements[0].closest(".content").getBoundingClientRect();
return elements.filter(element => element.getBoundingClientRect().bottom <= container.bottom).length;
});
assert(count >= 5, `At least five complete plugin rows fit at the screenshot size, got ${count}`);
}
const copy = pluginRows.first().locator(".plugin-copy");
const controls = pluginRows.first().locator(".controls");
const a = await copy.boundingBox(), b = await controls.boundingBox();
assert(a.x + a.width <= b.x + 1 || a.y + a.height <= b.y + 1, "Plugin text does not overlap its actions");
for (const button of await controls.getByRole("button").all()) {
const bounds = await button.boundingBox();
assert(bounds.width >= 28 && bounds.height >= 28);
assert(await button.getAttribute("aria-label"));
}
await settings.screenshot({ path: `.audit/settings-density-${theme}-${width}.png` });
}
}
await settings.setViewportSize({ width: 540, height: 420 });
await settings.getByRole("button", { name: "Install from Git link", exact: true }).click();
const install = settings.getByRole("dialog", { name: "Install from Git link", exact: true });
await install.waitFor();
assert(await install.getByRole("textbox", { name: "Repository link", exact: true }).isVisible());
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Cancel");
await settings.keyboard.press("Escape");
await install.waitFor({ state: "detached" });
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Install from Git link");
await settings.getByRole("button", { name: "General", exact: true }).click();
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
await settings.evaluate(async () => {
const { pluginTools } = await import("/src/lib/plugins/external.ts");
pluginTools.set(Array.from({ length: 12 }, (_, index) => ({ owner: "org.example.plugin-0", id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: "settings" })));
});
await settings.setViewportSize({ width: 360, height: 420 });
const sidebar = settings.locator("dialog aside");
assert((await sidebar.boundingBox()).height <= 154, "Many plugin categories leave space for setting controls");
assert(await sidebar.evaluate(element => element.scrollWidth <= element.clientWidth));
await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).scrollIntoViewIfNeeded();
const category = await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).boundingBox();
const navigation = await sidebar.boundingBox();
assert(category.y >= navigation.y && category.y + category.height <= navigation.y + navigation.height, "Every plugin category remains reachable");
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
assert.deepEqual(errors, []);
console.log("Settings density smoke passed: matching title bars and window controls, seven plugin rows, compact layout, readable text, accessible actions, both themes, narrow layouts, Git dialog focus, and many plugin categories.");
} finally { await browser.close(); }
+96
View File
@@ -0,0 +1,96 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import { mkdirSync, readFileSync } from "node:fs";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
mkdirSync(".audit", { recursive: true });
const settingsCapability = JSON.parse(readFileSync(new URL("../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
}
const errors = [];
try {
const context = await browser.newContext({ viewport: { width: 920, height: 650 } });
await context.addInitScript(() => {
window.isTauri = true;
const callbacks = new Map();
const listeners = new Map();
window.__TEST__ = { calls: [], maximized: false, fail: "", resize: () => callbacks.get(listeners.get("tauri://resize"))?.({ payload: {} }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "settings-main" }, currentWebview: { label: "settings-main" } },
transformCallback: callback => { const id = callbacks.size + 1; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.__TEST__.calls.push(command);
if (window.__TEST__.fail === command) throw new Error("Window action failed");
if (command === "plugins_snapshot") return { root: "D:\\SettingsTest\\plugins", plugins: [] };
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return args.handler; }
if (command === "plugin:window|is_maximized") return window.__TEST__.maximized;
if (command === "plugin:window|toggle_maximize") window.__TEST__.maximized = !window.__TEST__.maximized;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.on("pageerror", error => errors.push(error.message));
page.setDefaultTimeout(5000);
await page.goto(`${url}/?settingsWindow=true`);
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
await dialog.waitFor();
assert.equal(await dialog.getByRole("button", { name: /^Close/ }).count(), 1);
assert(await dialog.locator("header[data-tauri-drag-region] h1[data-tauri-drag-region]").isVisible());
assert.equal(await dialog.locator(".window-controls [data-tauri-drag-region]").count(), 0);
const calls = () => page.evaluate(() => window.__TEST__.calls);
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
assert((await calls()).includes("plugin:window|minimize"));
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Restore window", exact: true }).focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
await page.evaluate(() => { window.__TEST__.maximized = true; window.__TEST__.resize(); });
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
await page.getByRole("button", { name: "Close window", exact: true }).focus();
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
await page.keyboard.press("Space");
const beforeEscape = (await calls()).filter(command => command === "plugin:window|close").length;
assert.equal(beforeEscape, 1);
await page.getByRole("textbox", { name: "Search settings" }).focus();
await page.keyboard.press("Escape");
assert.equal((await calls()).filter(command => command === "plugin:window|close").length, beforeEscape + 1);
await page.mouse.move(400, 180);
for (const theme of ["dark", "light"]) {
await page.evaluate(value => document.documentElement.setAttribute("data-theme", value), theme);
for (const size of [{ width: 920, height: 650 }, { width: 540, height: 420 }]) {
await page.setViewportSize(size);
assert(await dialog.evaluate(element => element.scrollWidth === element.clientWidth));
for (const label of ["Minimize window", "Restore window", "Close window"]) {
const button = dialog.getByRole("button", { name: label, exact: true });
const bounds = await button.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= size.width && bounds.height >= 28);
assert.notEqual(await button.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
}
await page.screenshot({ path: `.audit/settings-window-${theme}-${size.width}.png` });
}
}
await page.evaluate(() => { window.__TEST__.fail = "plugin:window|minimize"; });
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
await dialog.getByRole("alert").filter({ hasText: "Window action failed" }).waitFor();
await page.evaluate(() => { window.__TEST__.fail = ""; });
await page.getByRole("button", { name: "Minimize window", exact: true }).focus();
await page.keyboard.press("Shift+Tab");
assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Restore defaults");
await page.keyboard.press("Tab");
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Minimize window");
const web = await browser.newPage();
await web.goto(`${url}/?settingsWindow=true`);
await web.getByRole("button", { name: "Close settings", exact: true }).waitFor();
assert.equal(await web.getByRole("group", { name: "Window controls" }).count(), 0);
assert.deepEqual(errors, []);
console.log("Settings window smoke passed: scoped permissions, drag regions, minimize, maximize, restore, resize, close, Escape, keyboard focus, tooltips, errors, both themes, narrow layout, and browser fallback.");
} finally { await browser.close(); }
+2 -1
View File
@@ -65,6 +65,7 @@ try {
if (command === "workspace_last_path") return null;
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugin:window|close") { window.settingsTest.closes++; return; }
throw new Error(`Unexpected IPC: ${command}`);
},
@@ -84,7 +85,7 @@ try {
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
await desktop.goto(`${origin}/?settingsWindow=true`);
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
await desktop.getByRole("button", { name: "Close settings", exact: true }).click();
await desktop.getByRole("button", { name: "Close window", exact: true }).click();
assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1);
assert.deepEqual(errors, []);
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
+66
View File
@@ -0,0 +1,66 @@
// Use a debug app with TAURI_CONFIG identifier com.runestone.spelling-test,
// a hidden window, and a separate WEBVIEW2_USER_DATA_FOLDER outside Vite's watch paths.
// Set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224 before launch.
// The normal app identifier is rejected before this test writes any workspace files.
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || "http://127.0.0.1:9224");
const page = browser.contexts()[0].pages()[0];
page.setDefaultTimeout(15000);
try {
await page.goto(process.env.SPELLING_APP_URL || "http://localhost:1420");
const data = await page.evaluate(async () => {
const { appDataDir } = await import("/node_modules/@tauri-apps/api/path.js");
return appDataDir();
});
assert.match(data, /[\\/]com\.runestone\.spelling-test[\\/]?$/, "Use the isolated spelling-test app identifier");
const workspace = resolve(process.env.SPELLING_WORKSPACE || ".audit/spelling-workspace");
await mkdir(workspace, { recursive: true });
await writeFile(resolve(workspace, "Spelling.md"), "# Spelling\n\nI recieved a letter.\n");
await page.evaluate(async path => {
const { invoke } = await import("/node_modules/@tauri-apps/api/core.js");
await invoke("workspace_open", { path });
}, workspace);
await page.reload();
await page.locator('[data-tree-rel="Spelling.md"]').click();
const editor = page.locator(".cm-content");
await editor.waitFor();
const line = page.getByText("I recieved a letter.", { exact: true });
const rect = await line.boundingBox();
await line.click();
const before = await editor.innerText();
await page.keyboard.press("End");
await page.keyboard.type(" TEST");
assert.notEqual(await editor.innerText(), before);
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
const menu = page.getByRole("menu", { name: "Spelling actions", exact: true });
await menu.waitFor();
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/spelling-native.png" });
await menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true }).click();
await page.waitForFunction(expected => document.querySelector(".cm-content")?.innerText === expected, before);
console.log("PASS: real WebView2 command dispatch through the shared menu restores the editor text.");
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
await menu.waitFor();
const suggestion = menu.getByRole("menuitem", { name: "received", exact: true });
if (await suggestion.count()) {
await suggestion.click();
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I received a letter."));
await page.keyboard.press("Control+z");
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I recieved a letter."));
console.log("PASS: native spelling correction and editor undo.");
} else {
await page.keyboard.press("Escape");
assert.notEqual(process.env.REQUIRE_NATIVE_SUGGESTIONS, "1", "The test WebView2 profile supplied no spelling suggestions");
console.log("SKIP: native spelling correction. This WebView2 profile supplied no suggestions. Desktop acceptance is still required.");
}
} finally {
await page.keyboard.press("Escape").catch(() => {});
await browser.close();
}
+3 -5
View File
@@ -74,9 +74,7 @@ async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
}
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
}
@@ -108,7 +106,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
}, source);
await quickOpen('drag.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
@@ -202,7 +200,7 @@ try {
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
});
await quickOpen('long.md');
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
+63 -1
View File
@@ -1,3 +1,4 @@
import { mockFeaturePlugins } from "./pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
@@ -70,6 +71,8 @@ await page.addInitScript(() => {
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
@@ -286,6 +289,65 @@ try {
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// Focusing empty and filled cells must not resize rows or columns.
const stableSource = '# Stable table\n\n| Column 2 | Column 1 | | |\n| --- | --- | --- | --- |\n| 2cm | Value | | |\n| text | 123 | | |\n| | | | |\n| LongUnbrokenCellValue | **Bold**<br>Two lines | A longer sentence wraps in a narrow table. | `code` |\n\nParagraph one.\nParagraph two.\n';
const dimensions = () => table.evaluate(el => [...el.rows].map(row => [...row.cells].map(cell => {
const rect = cell.getBoundingClientRect();
return { width: rect.width, height: rect.height };
})));
async function stableDimensions(expected, label) {
const actual = await dimensions();
for (let r = 0; r < expected.length; r++) for (let c = 0; c < expected[r].length; c++) {
for (const axis of ['width', 'height']) assert.ok(Math.abs(expected[r][c][axis] - actual[r][c][axis]) < 1,
`${label}: row ${r}, column ${c} ${axis} changed from ${expected[r][c][axis]} to ${actual[r][c][axis]}`);
}
}
for (const theme of ['dark', 'light']) for (const width of [1440, 800]) {
await page.setViewportSize({ width, height: 1000 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
const name = `stable-${theme}-${width}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: stableSource });
await quickOpen(name);
await table.waitFor();
const initial = await dimensions();
for (const [r, c] of [[1, 3], [2, 3], [3, 3], [0, 0], [1, 0], [1, 1], [4, 0], [4, 1], [4, 2], [4, 3], [2, 1]]) {
await at(r, c);
await stableDimensions(initial, `${theme} ${width} focus ${r},${c}`);
}
await arrow('Tab', 2, 2);
await stableDimensions(initial, `${theme} ${width} Tab`);
await arrow('ArrowDown', 3, 2);
await stableDimensions(initial, `${theme} ${width} ArrowDown`);
await page.keyboard.press('Escape');
await stableDimensions(initial, `${theme} ${width} blur`);
// Delete the blank line through the prose editor, then save and undo/redo.
await page.locator('.cm-line').filter({ hasText: 'Paragraph one.' }).click();
await page.keyboard.press('Home');
await page.keyboard.press('Backspace');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table tr').length === 5 &&
[...document.querySelectorAll('.cm-line')].some(line => line.textContent === 'Paragraph one.'));
await page.keyboard.press('Control+s');
const joined = stableSource.replace('\n\nParagraph one.', '\nParagraph one.');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, source }) => window.__TEST__.files.get(name) === source, { name, source: stableSource });
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
assert.equal(await table.locator('tr').count(), 5);
await at(1, 0);
await edit.fill('updated');
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined.replace('| 2cm |', '| updated |'), { name, joined });
}
await page.setViewportSize({ width: 1440, height: 1000 });
// A line break in a tall table keeps the caret and viewport in the active cell.
const tallSource = '# Tall table\n\nBefore.\n\n| Name | Value |\n| --- | --- |\n' +
Array.from({ length: 45 }, (_, i) => `| Row ${i + 1} | |`).join('\n') + '\n\nAfter.\n';
@@ -342,7 +404,7 @@ try {
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
}
assert.deepEqual(errors, []);
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape');
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape, stable cell dimensions and table/prose boundaries in both themes at wide/narrow widths');
} catch (error) {
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
throw error;
+20
View File
@@ -0,0 +1,20 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { moveMarks, replayMoveMarks } from "../src/lib/workspace/treeMoveHistory.ts";
test("move undo preserves later bookmarks, pins, and new files", () => {
const before = { pins: ["notes/a.md"], bookmarks: [], order: { notes: ["a.md", "b.md"], archive: [] as string[] } };
const after = moveMarks(before, "notes/a.md", "archive/a.md");
const current = { ...after, bookmarks: ["other.md"], pins: [...after.pins, "b.md"], order: { ...after.order, notes: [...after.order.notes, "new.md"] } };
const undo = replayMoveMarks(current, before, after, [{ from: "notes/a.md", to: "archive/a.md" }], false);
assert.deepEqual(undo.pins, ["notes/a.md", "b.md"]);
assert.deepEqual(undo.bookmarks, ["other.md"]);
assert.deepEqual(undo.order.notes, ["a.md", "b.md", "new.md"]);
assert.deepEqual(undo.order.archive, []);
});
test("folder moves retain nested marks and custom order", () => {
const marks = { pins: ["old/child.md"], bookmarks: ["old/deep/file.md"], order: { old: ["child.md"], "old/deep": ["file.md"] } };
const next = moveMarks(marks, "old", "new/old");
assert.deepEqual(next.pins, ["new/old/child.md"]);
assert.deepEqual(next.bookmarks, ["new/old/deep/file.md"]);
assert.deepEqual(next.order["new/old/deep"], ["file.md"]);
});
+2 -1
View File
@@ -82,7 +82,8 @@ try {
await row('src').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
assert.equal(await page.getByRole('tab').count(), 0);
assert.equal(await page.getByRole('tab').count(), 1);
assert.equal(await page.getByRole('tab', { name: 'New tab', exact: true }).count(), 1);
await row('notes').click({ modifiers: ['Control'] });
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
+104
View File
@@ -0,0 +1,104 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.setDefaultTimeout(30000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const url = process.env.SMOKE_URL || "http://127.0.0.1:5174";
const row = page.locator('[data-tree-rel="note.md"]');
try {
await page.goto(url);
await row.waitFor();
await row.click();
await page.locator('.writer-table table').waitFor();
const alignment = await page.evaluate(() => ({header:document.querySelector('.header-left').getBoundingClientRect().right, content:document.querySelector('.center').getBoundingClientRect().left}));
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
const table = await page.locator('.writer-table table').evaluate(el => ({width:el.getBoundingClientRect().width, heights:[...el.rows].map(row=>row.getBoundingClientRect().height), radius:getComputedStyle(el.parentElement).borderRadius}));
assert.ok(table.width < 400, JSON.stringify(table));
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
assert.equal(table.radius, '0px');
await row.focus();
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'visible');
await page.locator('.cm-content').click({position:{x:80,y:100}});
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'hidden');
assert.equal(await row.getAttribute('aria-selected'), 'true');
const line = page.locator('.cm-line').filter({hasText:'A second paragraph.'});
await line.hover();
assert.equal(await line.evaluate(el=>getComputedStyle(el,'::before').width), '3px');
assert.equal(await page.locator('.line-history').count(),0);
await page.evaluate(async()=>{
const {pluginHost}=await import('/src/lib/plugins/registry.ts');
window.blameCalls=[];
window.removeGit=pluginHost.register('ui-test','git',{blame:async(path,line)=>{
window.blameCalls.push({path,line});
return {commit:'123456789abcdef',author:'UI test',date:'2026-10-07T12:34:00Z',summary:`Changed line ${line}`};
}});
});
await line.click();
await page.locator('.line-history').waitFor();
assert.match(await page.locator('.line-history').getAttribute('title'), /Line 5 · UI test/);
await page.keyboard.type('x');
await page.locator('.line-history').waitFor({state:'hidden'});
await page.keyboard.press('Control+z');
await page.locator('.line-history').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const tab = await page.locator('.tab.active').evaluate(el=>({background:getComputedStyle(el).backgroundColor,border:getComputedStyle(el).borderBottomColor,shadow:getComputedStyle(el).boxShadow}));
const pane = await page.locator('.chrome-bar').evaluate(el=>getComputedStyle(el).backgroundColor);
assert.equal(tab.background,pane);
assert.equal(tab.border,'rgba(0, 0, 0, 0)');
assert.equal(tab.shadow,'none');
await line.hover();
await page.screenshot({path:`.audit/ui-cards/writer-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('ArrowRight');
await page.locator('.md-page .reading').waitFor();
const paragraph=page.locator('.md-page p').filter({hasText:'A second paragraph.'});
await paragraph.hover();
assert.equal(await paragraph.evaluate(el=>getComputedStyle(el,'::before').width),'3px');
assert.ok((await page.locator('.md-page table').boundingBox()).width<400);
await page.screenshot({path:`.audit/ui-cards/read-${theme}.png`});
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('Home');
}
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('Home');
await page.locator('.monaco-editor').waitFor();
await page.locator('.line-history').waitFor();
await page.evaluate(()=>window.removeGit());
await page.locator('.line-history').waitFor({state:'hidden'});
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('End');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:760,height:640});
for(const theme of ['dark','light']) {
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
const dimensions=await page.locator('.header-left .icon-btn').evaluateAll(els=>els.map(el=>({width:el.getBoundingClientRect().width,svg:el.querySelector('svg').getBoundingClientRect().width})));
assert.ok(dimensions.every(size=>size.width>=28 && size.svg>=16),JSON.stringify(dimensions));
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
await page.screenshot({path:`.audit/ui-cards/narrow-${theme}.png`});
}
assert.deepEqual(errors,[]);
console.log('PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width');
} finally {await browser.close();}
+175
View File
@@ -0,0 +1,175 @@
// 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_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function open(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();
}
async function writer() {
await page.locator('.cm-content').waitFor();
return page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
return window.__WRITER__.state.sliceDoc();
});
}
async function expectWriter(expected) {
await writer();
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors }); throw error; }
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await open('welcome.md');
const original = await writer();
await page.locator('.cm-content').click();
await page.keyboard.press('Control+End');
await page.keyboard.type(' first edit');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+s');
await open('second.md');
await writer();
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
console.log('PASS: saved Writer edit survives tab switch with undo and redo');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
assert.equal(await page.evaluate(() => window.__WRITER__.state.selection.main.head), (original + ' first edit').length);
console.log('PASS: Writer undo and redo survive window focus refresh and restore the caret');
await page.keyboard.press('Control+e');
await page.locator('.monaco-editor textarea').waitFor();
await page.evaluate(async () => {
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
editor.setPosition({ lineNumber: editor.getModel().getLineCount(), column: editor.getModel().getLineMaxColumn(editor.getModel().getLineCount()) });
editor.focus();
window.__IDE__ = editor;
});
await page.keyboard.type(' second edit');
assert.equal(await page.evaluate(() => window.__IDE__.getDomNode()?.isConnected), true, 'Typing keeps the same IDE editor mounted');
assert.equal(await page.evaluate(() => window.__IDE__.getValue()), original + ' first edit second edit');
await page.keyboard.press('Control+e');
await expectWriter(original + ' first edit second edit');
await page.locator('.cm-content').click();
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit second');
await page.keyboard.press('Control+z');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+z');
await expectWriter(original);
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second');
await page.keyboard.press('Control+y');
await expectWriter(original + ' first edit second edit');
console.log('PASS: Writer undo includes edits from IDE mode');
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
await page.evaluate(source => {
window.__TEST__.files.set('table.md', source);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table.md'] });
}, tableSource);
await open('table.md');
await writer();
const cells = page.locator('.writer-table tbody td');
await cells.nth(0).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Alpha');
await cells.nth(1).click();
await page.keyboard.press('Control+a');
await page.keyboard.type('Beta');
await page.keyboard.press('Escape');
const editedTable = await writer();
assert.ok(editedTable.includes('Alpha') && editedTable.includes('Beta'));
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
await writer();
await page.getByRole('tab', { name: 'table.md', exact: true }).click();
await writer();
await page.keyboard.press('Control+z');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+z');
await expectWriter(tableSource);
await page.keyboard.press('Control+y');
await expectWriter(editedTable.replace('Beta', 'Two'));
await page.keyboard.press('Control+y');
await expectWriter(editedTable);
console.log('PASS: table cell typing stays grouped per cell across tab switches');
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+95
View File
@@ -0,0 +1,95 @@
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: () => 1, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
if (command === "workspace_last_path") return "D:\\LayoutTest";
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
if (command === "workspace_read") {
if (args.rel === "note.md") return "# Layout test\n\nA note.\n";
throw new Error("Missing file");
}
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const errors = [];
context.on("page", page => page.on("pageerror", error => errors.push(error.message)));
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
let page = await context.newPage();
page.setDefaultTimeout(5000);
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
async function reopen() {
await page.close();
page = await context.newPage();
page.setDefaultTimeout(5000);
await page.goto(url);
await ready();
}
async function resize(index, x) {
const box = await page.locator(".gutter-v").nth(index).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + 60);
await page.mouse.down();
await page.mouse.move(x, box.y + 60);
await page.mouse.up();
}
async function widths() {
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
}
try {
await page.goto(url);
await ready();
await page.getByText("LayoutTest", { exact: true }).waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
await page.locator(".cm-content").waitFor();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor").waitFor();
assert.equal(await page.locator(".right").count(), 0);
await page.keyboard.press("Control+e");
await page.locator(".cm-content").waitFor();
assert.equal(await page.locator(".right").count(), 0);
console.log("PASS: hidden outline stays hidden across Writer and IDE changes");
await page.reload();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
assert.equal(await page.locator(".right").count(), 0);
await reopen();
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
console.log("PASS: hidden outline survives reload and window reopen");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
await resize(0, 330);
await resize(1, 970);
const resized = await widths();
assert.deepEqual(resized, ["330px", "310px"]);
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await reopen();
assert.deepEqual(await widths(), resized);
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Hide outline", exact: true }).waitFor();
console.log("PASS: resized sidebars and chosen navigation view survive reopen");
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
await reopen();
assert.equal(await page.locator(".left, .right").count(), 0);
await page.keyboard.press("Control+b");
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
await page.getByRole("button", { name: "Show outline", exact: true }).click();
assert.deepEqual(await widths(), resized);
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
assert.deepEqual(errors, []);
} finally { await browser.close(); }
+30
View File
@@ -0,0 +1,30 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout } from "../src/lib/workspace/workbenchLayout.ts";
test("missing and damaged layouts use defaults", () => {
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
assert.deepEqual(parseWorkbenchLayout(raw), DEFAULT_WORKBENCH_LAYOUT);
}
});
test("invalid layout fields do not discard valid collapsed states", () => {
for (const leftWidth of [0, -1, 159, 481, "260", null]) {
assert.deepEqual(parseWorkbenchLayout(JSON.stringify({ leftOpen: false, rightOpen: false, leftWidth, rightWidth: 320, leftView: "unknown" })), {
...DEFAULT_WORKBENCH_LAYOUT, leftOpen: false, rightOpen: false, rightWidth: 320,
});
}
assert.deepEqual(parseWorkbenchLayout('{"leftOpen":"false","rightOpen":0}'), DEFAULT_WORKBENCH_LAYOUT);
});
test("layout survives storage round trips with hidden panels and all navigation views", () => {
const store = new Map<string, string>();
for (const leftView of ["files", "search", "bookmarks"] as const) {
for (const leftWidth of [160, 321.5, 480]) {
const layout = { leftOpen: false, rightOpen: false, leftWidth, rightWidth: 400, leftView };
saveWorkbenchLayout({ setItem: (key, value) => { store.set(key, value); } }, layout);
assert.deepEqual(parseWorkbenchLayout(store.get(WORKBENCH_LAYOUT_KEY)!), layout);
}
}
assert.throws(() => saveWorkbenchLayout({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_WORKBENCH_LAYOUT }), /Storage unavailable/);
});
+3 -1
View File
@@ -3130,7 +3130,7 @@ dependencies = [
[[package]]
name = "runestone"
version = "0.1.10"
version = "0.1.18"
dependencies = [
"base64 0.23.1",
"dunce",
@@ -3147,6 +3147,8 @@ dependencies = [
"tauri-plugin-opener",
"thiserror 2.0.20",
"uuid",
"webview2-com",
"windows",
"windows-sys 0.61.2",
"zip",
]
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "runestone"
version = "0.1.10"
version = "0.1.18"
description = "Writing workspace plus script editor"
authors = ["you"]
edition = "2021"
@@ -31,6 +31,8 @@ reqwest = { version = "0.13.5", default-features = false, features = ["blocking"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] }
webview2-com = "0.38.2"
windows = { version = "0.61.3", features = ["Win32_Foundation", "Win32_System_Com"] }
# Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration
+17
View File
@@ -2,11 +2,26 @@ fn main() {
tauri_build::try_build(
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"spelling_menu_install",
"spelling_menu_select",
"spelling_menu_uninstall",
"settings_open_window",
"completion_request",
"completion_cancel",
"browser_request",
"browser_connect",
"browser_stop",
"git_status",
"git_diff",
"git_stage",
"git_unstage",
"git_commit",
"git_blame",
"git_push",
"git_pull",
"git_graph",
"git_commit_diff",
"git_commit_details",
"workspace_open",
"workspace_open_window",
"workspace_last_path",
@@ -25,6 +40,8 @@ fn main() {
"workspace_copy",
"workspace_abs_path",
"workspace_reveal",
"workspace_open_terminal",
"workspace_open_default",
"workspace_search",
"plugins_snapshot",
"plugins_choose",
+17
View File
@@ -4,11 +4,26 @@
"description": "Capability for the main window",
"windows": ["main", "workspace-*", "terminal-*", "browser-*"],
"permissions": [
"allow-spelling-menu-install",
"allow-spelling-menu-select",
"allow-spelling-menu-uninstall",
"allow-settings-open-window",
"allow-completion-request",
"allow-completion-cancel",
"allow-browser-request",
"allow-browser-connect",
"allow-browser-stop",
"allow-git-status",
"allow-git-diff",
"allow-git-stage",
"allow-git-unstage",
"allow-git-commit",
"allow-git-blame",
"allow-git-push",
"allow-git-pull",
"allow-git-graph",
"allow-git-commit-diff",
"allow-git-commit-details",
"core:default",
"core:window:allow-destroy",
"core:window:allow-close",
@@ -35,6 +50,8 @@
"allow-workspace-copy",
"allow-workspace-abs-path",
"allow-workspace-reveal",
"allow-workspace-open-terminal",
"allow-workspace-open-default",
"allow-workspace-search",
"allow-plugins-snapshot",
"allow-plugins-choose",
+4
View File
@@ -6,6 +6,9 @@
"permissions": [
"core:default",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-toggle-maximize",
"core:window:allow-start-dragging",
"dialog:default",
"allow-plugins-snapshot",
"allow-plugins-choose",
@@ -22,6 +25,7 @@
"allow-plugins-data",
"allow-plugins-asset",
"allow-browser-request",
"allow-browser-connect",
"allow-browser-stop",
"allow-completion-request",
"allow-completion-cancel"
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-browser-connect"
description = "Enables the browser_connect command without any pre-configured scope."
commands.allow = ["browser_connect"]
[[permission]]
identifier = "deny-browser-connect"
description = "Denies the browser_connect command without any pre-configured scope."
commands.deny = ["browser_connect"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-blame"
description = "Enables the git_blame command without any pre-configured scope."
commands.allow = ["git_blame"]
[[permission]]
identifier = "deny-git-blame"
description = "Denies the git_blame command without any pre-configured scope."
commands.deny = ["git_blame"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-commit"
description = "Enables the git_commit command without any pre-configured scope."
commands.allow = ["git_commit"]
[[permission]]
identifier = "deny-git-commit"
description = "Denies the git_commit command without any pre-configured scope."
commands.deny = ["git_commit"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-commit-details"
description = "Enables the git_commit_details command without any pre-configured scope."
commands.allow = ["git_commit_details"]
[[permission]]
identifier = "deny-git-commit-details"
description = "Denies the git_commit_details command without any pre-configured scope."
commands.deny = ["git_commit_details"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-commit-diff"
description = "Enables the git_commit_diff command without any pre-configured scope."
commands.allow = ["git_commit_diff"]
[[permission]]
identifier = "deny-git-commit-diff"
description = "Denies the git_commit_diff command without any pre-configured scope."
commands.deny = ["git_commit_diff"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-diff"
description = "Enables the git_diff command without any pre-configured scope."
commands.allow = ["git_diff"]
[[permission]]
identifier = "deny-git-diff"
description = "Denies the git_diff command without any pre-configured scope."
commands.deny = ["git_diff"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-graph"
description = "Enables the git_graph command without any pre-configured scope."
commands.allow = ["git_graph"]
[[permission]]
identifier = "deny-git-graph"
description = "Denies the git_graph command without any pre-configured scope."
commands.deny = ["git_graph"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-pull"
description = "Enables the git_pull command without any pre-configured scope."
commands.allow = ["git_pull"]
[[permission]]
identifier = "deny-git-pull"
description = "Denies the git_pull command without any pre-configured scope."
commands.deny = ["git_pull"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-push"
description = "Enables the git_push command without any pre-configured scope."
commands.allow = ["git_push"]
[[permission]]
identifier = "deny-git-push"
description = "Denies the git_push command without any pre-configured scope."
commands.deny = ["git_push"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-stage"
description = "Enables the git_stage command without any pre-configured scope."
commands.allow = ["git_stage"]
[[permission]]
identifier = "deny-git-stage"
description = "Denies the git_stage command without any pre-configured scope."
commands.deny = ["git_stage"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-status"
description = "Enables the git_status command without any pre-configured scope."
commands.allow = ["git_status"]
[[permission]]
identifier = "deny-git-status"
description = "Denies the git_status command without any pre-configured scope."
commands.deny = ["git_status"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-git-unstage"
description = "Enables the git_unstage command without any pre-configured scope."
commands.allow = ["git_unstage"]
[[permission]]
identifier = "deny-git-unstage"
description = "Denies the git_unstage command without any pre-configured scope."
commands.deny = ["git_unstage"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-spelling-menu-install"
description = "Enables the spelling_menu_install command without any pre-configured scope."
commands.allow = ["spelling_menu_install"]
[[permission]]
identifier = "deny-spelling-menu-install"
description = "Denies the spelling_menu_install command without any pre-configured scope."
commands.deny = ["spelling_menu_install"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-spelling-menu-select"
description = "Enables the spelling_menu_select command without any pre-configured scope."
commands.allow = ["spelling_menu_select"]
[[permission]]
identifier = "deny-spelling-menu-select"
description = "Denies the spelling_menu_select command without any pre-configured scope."
commands.deny = ["spelling_menu_select"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-spelling-menu-uninstall"
description = "Enables the spelling_menu_uninstall command without any pre-configured scope."
commands.allow = ["spelling_menu_uninstall"]
[[permission]]
identifier = "deny-spelling-menu-uninstall"
description = "Denies the spelling_menu_uninstall command without any pre-configured scope."
commands.deny = ["spelling_menu_uninstall"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-open-default"
description = "Enables the workspace_open_default command without any pre-configured scope."
commands.allow = ["workspace_open_default"]
[[permission]]
identifier = "deny-workspace-open-default"
description = "Denies the workspace_open_default command without any pre-configured scope."
commands.deny = ["workspace_open_default"]
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-workspace-open-terminal"
description = "Enables the workspace_open_terminal command without any pre-configured scope."
commands.allow = ["workspace_open_terminal"]
[[permission]]
identifier = "deny-workspace-open-terminal"
description = "Denies the workspace_open_terminal command without any pre-configured scope."
commands.deny = ["workspace_open_terminal"]
+42 -2
View File
@@ -37,11 +37,15 @@ const COMMANDS: &[&str] = &[
"removeBookmark",
"settings",
"clearData",
"webData",
"removeCookie",
"removeHistory",
"agentSnapshot",
];
#[derive(Default)]
pub struct BrowserState {
inner: Mutex<Option<Worker>>,
sessions: Mutex<HashMap<String, String>>,
}
#[derive(Default)]
struct WindowTabs {
@@ -347,7 +351,19 @@ fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64
Ok(())
}
impl BrowserState {
fn connect(&self, owner: &str) -> Result<String> {
let mut sessions = self.sessions.lock().map_err(fail)?;
Ok(sessions.entry(owner.to_string()).or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone())
}
fn require_session(&self, owner: &str, token: &str) -> Result<()> {
if self.sessions.lock().map_err(fail)?.get(owner).is_some_and(|saved| saved == token) {
Ok(())
} else {
Err("The browser session is unavailable in this window.".into())
}
}
pub fn close_window(&self, owner: &str) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.remove(owner); }
if let Ok(mut guard) = self.inner.lock() {
let Some(worker) = guard.as_mut() else { return; };
let (closed, empty) = match worker.routing.lock() {
@@ -361,6 +377,7 @@ impl BrowserState {
}
}
pub fn close_all(&self) {
if let Ok(mut sessions) = self.sessions.lock() { sessions.clear(); }
if let Ok(mut guard) = self.inner.lock() {
if let Some(mut worker) = guard.take() {
let _ = worker.stop();
@@ -460,16 +477,25 @@ impl BrowserState {
}
}
#[tauri::command]
pub async fn browser_connect(state: State<'_, BrowserState>, window: tauri::Window) -> Result<String> {
state.connect(window.label())
}
#[tauri::command]
pub async fn browser_request(
app: AppHandle,
window: tauri::Window,
command: String,
args: Value,
session: Option<String>,
) -> Result<Value> {
let owner = window.label().to_string();
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
if let Some(token) = session {
app.state::<BrowserState>().require_session(&owner, &token)?;
} else {
app.state::<crate::plugins::PluginState>()
.require_lease(&app, &owner, PLUGIN)?;
}
tauri::async_runtime::spawn_blocking(move || {
app.state::<BrowserState>()
.request(&app, &owner, &command, args)
@@ -487,6 +513,20 @@ pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window)
mod tests {
use super::*;
#[test]
fn builtin_sessions_are_scoped_to_a_window_and_revoked_on_close() {
let state = BrowserState::default();
assert!(state.require_session("main", "missing").is_err());
let token = state.connect("main").unwrap();
assert!(state.require_session("main", &token).is_ok());
assert!(state.require_session("other", &token).is_err());
state.close_window("main");
assert!(state.require_session("main", &token).is_err());
let next = state.connect("main").unwrap();
assert_ne!(next, token);
state.close_all();
assert!(state.require_session("main", &next).is_err());
}
#[test]
fn drag_transfer_requires_the_owner_token_and_rejects_replays() {
let mut routes = WindowTabs::default();
routes.windows.extend(["main".into(), "browser-other".into()]);
+840
View File
@@ -0,0 +1,840 @@
use crate::workspace::{current_root_path, WorkspaceState};
use serde::Serialize;
use std::io::Read;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use tauri::{State, Window};
const OUTPUT_LIMIT: usize = 2 * 1024 * 1024;
static GIT_LOCK: Mutex<()> = Mutex::new(());
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitChange {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
original_path: Option<String>,
index: String,
worktree: String,
}
#[derive(Debug, Serialize)]
pub struct GitStatus {
available: bool,
repository: bool,
branch: Option<String>,
changes: Vec<GitChange>,
}
#[derive(Debug, Serialize)]
pub struct GitLineInfo {
commit: String,
author: String,
date: String,
summary: String,
}
fn read_output(mut stream: impl Read) -> Result<Vec<u8>, String> {
let mut result = Vec::new();
let mut buffer = [0; 8192];
let mut overflow = false;
loop {
let count = stream.read(&mut buffer).map_err(|e| e.to_string())?;
if count == 0 {
break;
}
if result.len() + count <= OUTPUT_LIMIT {
result.extend_from_slice(&buffer[..count]);
} else {
overflow = true;
}
}
if overflow {
Err(
"Git output exceeds the 2 MiB limit. Use Git outside RuneStone for this operation."
.into(),
)
} else {
Ok(result)
}
}
fn run(root: &Path, args: &[&str]) -> Result<Output, String> {
let mut command = Command::new("git");
command
.current_dir(root)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, _) in std::env::vars_os() {
if key
.to_string_lossy()
.to_ascii_uppercase()
.starts_with("GIT_")
{
command.env_remove(key);
}
}
command
.env("GIT_TERMINAL_PROMPT", "0")
.env("GIT_OPTIONAL_LOCKS", "0")
.args([
"--no-pager",
"--literal-pathspecs",
"-c",
"core.fsmonitor=false",
])
.args(args);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x08000000);
}
let mut child = command
.spawn()
.map_err(|e| format!("Could not start Git. Install Git and restart RuneStone. {e}"))?;
let stdout = child.stdout.take().ok_or("Git output is unavailable.")?;
let stderr = child.stderr.take().ok_or("Git errors are unavailable.")?;
let out = std::thread::spawn(move || read_output(stdout));
let err = std::thread::spawn(move || read_output(stderr));
let start = Instant::now();
let mut completed = None;
let status = loop {
if completed.is_none() {
completed = child.try_wait().map_err(|e| e.to_string())?;
}
if let Some(status) = completed {
if out.is_finished() && err.is_finished() {
break status;
}
}
if start.elapsed() > Duration::from_secs(30) {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Git can start SSH and credential helpers that also hold its output pipes.
let _ = Command::new("taskkill")
.args(["/PID", &child.id().to_string(), "/T", "/F"])
.creation_flags(0x08000000)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
let _ = child.kill();
let _ = child.wait();
return Err(
"Git did not finish within 30 seconds. Refresh to check the repository state."
.into(),
);
}
std::thread::sleep(Duration::from_millis(15));
};
Ok(Output {
status,
stdout: out.join().map_err(|_| "Could not read Git output.")??,
stderr: err.join().map_err(|_| "Could not read Git errors.")??,
})
}
fn checked(root: &Path, args: &[&str]) -> Result<String, String> {
let output = run(root, args)?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
}
String::from_utf8(output.stdout)
.map_err(|_| "Git returned a filename that is not UTF-8.".into())
}
fn repository(root: &Path) -> Result<(), String> {
let top = checked(root, &["rev-parse", "--show-toplevel"])?;
let top = dunce::canonicalize(top.trim()).map_err(|e| e.to_string())?;
if top != root {
return Err("Open the repository root as your workspace to use Git.".into());
}
for argument in ["--absolute-git-dir", "--git-common-dir"] {
let git_dir = checked(root, &["rev-parse", argument])?;
let git_dir = dunce::canonicalize(root.join(git_dir.trim())).map_err(|e| e.to_string())?;
if !git_dir.starts_with(root) {
return Err(
"Git metadata must be inside the workspace. Linked worktrees are not supported."
.into(),
);
}
}
Ok(())
}
fn safe_path(root: &Path, value: &str) -> Result<(), String> {
if value.is_empty() || value.contains('\0') || value.contains('\\') || value.contains(':') {
return Err("Choose a relative Git file path inside the workspace.".into());
}
let path = Path::new(value);
if path
.components()
.any(|c| !matches!(c, Component::Normal(_)))
|| path
.components()
.any(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(".git"))
{
return Err("The Git path is outside the workspace or names Git metadata.".into());
}
let mut cursor = root.to_owned();
for part in path.components() {
cursor.push(part);
match std::fs::symlink_metadata(&cursor) {
Ok(_) => {
let real = dunce::canonicalize(&cursor).map_err(|e| e.to_string())?;
if !real.starts_with(root) {
return Err("The Git path points outside the workspace.".into());
}
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => break,
Err(e) => return Err(e.to_string()),
}
}
Ok(())
}
fn parse_status(value: &str) -> Result<Vec<GitChange>, String> {
let mut records = value.split('\0').filter(|s| !s.is_empty());
let mut changes = Vec::new();
while let Some(record) = records.next() {
if record.len() < 4 || record.as_bytes()[2] != b' ' {
return Err("Git returned an invalid status record.".into());
}
let index = record.as_bytes()[0] as char;
let worktree = record.as_bytes()[1] as char;
let original_path = if matches!(index, 'R' | 'C') || matches!(worktree, 'R' | 'C') {
Some(
records
.next()
.ok_or("Git returned an incomplete rename.")?
.to_owned(),
)
} else {
None
};
changes.push(GitChange {
path: record[3..].to_owned(),
original_path,
index: index.to_string(),
worktree: worktree.to_string(),
});
}
Ok(changes)
}
fn status(root: &Path) -> Result<GitStatus, String> {
let empty = |available| GitStatus {
available,
repository: false,
branch: None,
changes: vec![],
};
if run(root, &["--version"]).is_err() {
return Ok(empty(false));
}
if !root.join(".git").exists() {
return Ok(empty(true));
}
repository(root)?;
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).or_else(|_| {
checked(root, &["rev-parse", "--short", "HEAD"]).map(|id| format!("Detached {}", id.trim()))
})?;
let changes = parse_status(&checked(
root,
&["status", "--porcelain=v1", "-z", "--untracked-files=all"],
)?)?;
Ok(GitStatus {
available: true,
repository: true,
branch: Some(branch.trim().to_owned()),
changes,
})
}
fn diff(root: &Path, path: &str, staged: bool) -> Result<String, String> {
repository(root)?;
safe_path(root, path)?;
let untracked = !staged && checked(root, &["ls-files", "--error-unmatch", "--", path]).is_err();
if untracked {
let file = std::fs::File::open(root.join(path)).map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
file.take(512 * 1024 + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 512 * 1024 {
return Ok("This new file is too large to preview (512 KiB limit).".into());
}
if bytes.contains(&0) {
return Ok("Binary file. No text preview is available.".into());
}
let source = String::from_utf8(bytes).map_err(|_| "This file is not UTF-8 text.")?;
return Ok(format!(
"New file: {path}\n{}",
source
.lines()
.map(|line| format!("+{line}\n"))
.collect::<String>()
));
}
let change = status(root)?
.changes
.into_iter()
.find(|change| change.path == path);
let original = change.and_then(|change| change.original_path);
if let Some(original) = original.as_ref() {
safe_path(root, original)?;
}
let mut args = vec!["diff", "--no-ext-diff", "--no-textconv", "--no-color"];
if staged {
args.push("--cached");
}
args.extend(["--", path]);
if let Some(original) = original.as_deref() {
args.push(original);
}
checked(root, &args)
}
fn change_index(root: &Path, paths: &[String], stage: bool) -> Result<(), String> {
repository(root)?;
if paths.is_empty() || paths.len() > 10000 {
return Err("Choose between 1 and 10,000 files.".into());
}
for path in paths {
safe_path(root, path)?;
}
let has_head = !stage && run(root, &["rev-parse", "--verify", "HEAD"])?
.status
.success();
let mut args = if stage {
vec!["add", "--"]
} else if has_head {
vec!["restore", "--staged", "--"]
} else {
vec!["rm", "--cached", "--ignore-unmatch", "--"]
};
args.extend(paths.iter().map(String::as_str));
checked(root, &args)?;
Ok(())
}
fn commit(root: &Path, message: &str) -> Result<(), String> {
repository(root)?;
if message.trim().is_empty() || message.len() > 65536 || message.contains('\0') {
return Err("Enter a commit message between 1 and 65,536 bytes.".into());
}
checked(root, &["commit", "-m", message])?;
Ok(())
}
fn upstream(root: &Path) -> Result<(String, String), String> {
let branch = checked(root, &["symbolic-ref", "--quiet", "--short", "HEAD"])
.map_err(|_| "Select a branch outside RuneStone before you push or pull.")?;
let branch = branch.trim();
let missing = "This branch has no remote upstream. Set its upstream with Git outside RuneStone, then refresh.";
let remote = checked(
root,
&["config", "--get", &format!("branch.{branch}.remote")],
)
.map_err(|_| missing)?;
let merge = checked(
root,
&["config", "--get-all", &format!("branch.{branch}.merge")],
)
.map_err(|_| missing)?;
let remote = remote.trim();
let merge = merge.trim();
if remote.is_empty()
|| remote.starts_with('-')
|| remote == "."
|| remote.contains('\n')
|| !merge.starts_with("refs/heads/")
|| merge.contains('\n')
{
return Err("Set one remote branch as the upstream with Git outside RuneStone.".into());
}
checked(root, &["check-ref-format", merge])?;
checked(root, &["remote", "get-url", "--", remote])?;
Ok((remote.into(), merge.into()))
}
fn synchronize(root: &Path, push: bool) -> Result<(), String> {
repository(root)?;
let (remote, reference) = upstream(root)?;
if !push && !status(root)?.changes.is_empty() {
return Err("Commit your changes or stash them with Git before you pull. Pull requires a clean working tree.".into());
}
// Explicit arguments prevent repository defaults from forcing a push or rebasing a pull.
let mirror = format!("remote.{remote}.mirror=false");
let target = format!("HEAD:{reference}");
let mut args = vec![
"-c",
"credential.interactive=false",
"-c",
"core.sshCommand=ssh -oBatchMode=yes -oConnectTimeout=15",
];
if push {
args.extend([
"-c",
&mirror,
"push",
"--porcelain",
"--no-follow-tags",
"--recurse-submodules=no",
"--",
&remote,
&target,
]);
} else {
args.extend([
"pull",
"--ff-only",
"--no-rebase",
"--no-autostash",
"--no-recurse-submodules",
"--",
&remote,
&reference,
]);
}
checked(root, &args).map_err(|error| format!("{} failed. {error}\nIf Git needs credentials, sign in with Git outside RuneStone, then retry.", if push { "Push" } else { "Pull" }))?;
Ok(())
}
#[derive(Debug, Serialize)]
pub struct GitGraphCommit {
id: String,
parents: Vec<String>,
refs: Vec<String>,
summary: String,
author: String,
date: String,
}
#[derive(Debug, Serialize)]
pub struct GitGraph {
commits: Vec<GitGraphCommit>,
}
fn graph(root: &Path) -> Result<GitGraph, String> {
repository(root)?;
let has_head = run(root, &["rev-parse", "--verify", "HEAD"])?
.status
.success();
if !has_head
&& checked(root, &["rev-list", "--all", "--max-count=1"])?
.trim()
.is_empty()
{
return Ok(GitGraph { commits: Vec::new() });
}
let mut args = vec![
"log",
"--all",
"--max-count=100",
"--topo-order",
"--no-color",
"--decorate=short",
"--date=short",
"-z",
"--format=%H%x00%P%x00%D%x00%s%x00%an%x00%ad",
];
if has_head {
args.push("HEAD");
}
args.push("--");
let output = checked(root, &args)?;
let fields: Vec<&str> = output.split('\0').collect();
let mut commits = Vec::new();
for record in fields.chunks(6) {
if record.len() == 1 && record[0].trim().is_empty() { continue; }
if record.len() != 6 { return Err("Git returned incomplete commit history.".into()); }
commits.push(GitGraphCommit {
id: record[0].trim().to_owned(),
parents: record[1].split_whitespace().map(str::to_owned).collect(),
refs: record[2].split(", ").filter(|value| !value.is_empty()).map(str::to_owned).collect(),
summary: record[3].to_owned(),
author: record[4].to_owned(),
date: record[5].to_owned(),
});
}
Ok(GitGraph { commits })
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitCommitFile {
path: String,
#[serde(skip_serializing_if = "Option::is_none")]
original_path: Option<String>,
status: String,
}
#[derive(Debug, Serialize)]
pub struct GitCommitDetails {
id: String,
parents: Vec<String>,
author: String,
date: String,
message: String,
files: Vec<GitCommitFile>,
}
fn commit_id(value: &str) -> Result<(), String> {
if ![40, 64].contains(&value.len()) || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err("Select a commit from the Git graph.".into());
}
Ok(())
}
fn parse_commit_files(value: &str) -> Result<Vec<GitCommitFile>, String> {
let mut records = value.split('\0').filter(|field| !field.is_empty());
let mut files = Vec::new();
while let Some(status) = records.next() {
let first = records.next().ok_or("Git returned an incomplete file change.")?;
let renamed = status.starts_with('R') || status.starts_with('C');
let path = if renamed { records.next().ok_or("Git returned an incomplete rename.")? } else { first };
files.push(GitCommitFile { path: path.into(), original_path: renamed.then(|| first.into()), status: status.into() });
}
Ok(files)
}
fn commit_details(root: &Path, id: &str) -> Result<GitCommitDetails, String> {
commit_id(id)?;
repository(root)?;
let metadata = checked(root, &["show", "--no-patch", "--no-show-signature", "--format=%H%x00%P%x00%an%x00%aI%x00%B", id, "--"])?;
let fields: Vec<_> = metadata.splitn(5, '\0').collect();
if fields.len() != 5 { return Err("Git returned incomplete commit details.".into()); }
let parents: Vec<String> = fields[1].split_whitespace().map(str::to_owned).collect();
let mut args = vec!["diff-tree", "--root", "--no-commit-id", "--name-status", "-r", "-z", "-M"];
// Merge details use the first parent, as the graph's main line does.
if let Some(parent) = parents.first() { args.push(parent); }
args.extend([id, "--"]);
let files = parse_commit_files(&checked(root, &args)?)?;
Ok(GitCommitDetails { id: fields[0].into(), parents, author: fields[2].into(), date: fields[3].into(), message: fields[4].trim_end().into(), files })
}
fn commit_diff(root: &Path, id: &str, path: &str) -> Result<String, String> {
let details = commit_details(root, id)?;
safe_path(root, path)?;
let file = details.files.iter().find(|file| file.path == path).ok_or("This file is not part of the selected commit.")?;
let mut args = if let Some(parent) = details.parents.first() {
vec!["diff", "--no-ext-diff", "--no-textconv", "--no-color", "-M", parent, id]
} else {
vec!["show", "--format=", "--root", "--no-ext-diff", "--no-textconv", "--no-color", "-M", id]
};
args.extend(["--", path]);
if let Some(original) = &file.original_path { safe_path(root, original)?; args.push(original); }
checked(root, &args)
}
fn blame(root: &Path, path: &str, line: u32) -> Result<Option<GitLineInfo>, String> {
repository(root)?;
safe_path(root, path)?;
if line == 0 {
return Err("The Git line number must be at least 1.".into());
}
let range = format!("{line},{line}");
let output = run(
root,
&["blame", "--line-porcelain", "-L", &range, "--", path],
)?;
if !output.status.success() {
return Ok(None);
}
let text = String::from_utf8_lossy(&output.stdout);
let commit = text.split_whitespace().next().unwrap_or("");
if commit.is_empty() || commit.chars().all(|c| c == '0') {
return Ok(None);
}
let field = |key: &str| {
text.lines()
.find_map(|line| line.strip_prefix(key))
.unwrap_or("")
.to_owned()
};
Ok(Some(GitLineInfo {
commit: commit.into(),
author: field("author "),
date: field("author-time "),
summary: field("summary "),
}))
}
fn root(state: &WorkspaceState, window: &Window) -> Result<PathBuf, String> {
dunce::canonicalize(current_root_path(state, window.label()).map_err(|e| e.to_string())?)
.map_err(|e| e.to_string())
}
async fn task<T: Send + 'static>(
action: impl FnOnce() -> Result<T, String> + Send + 'static,
) -> Result<T, String> {
tauri::async_runtime::spawn_blocking(move || {
let _guard = GIT_LOCK
.lock()
.map_err(|_| "The Git service lock is unavailable.")?;
action()
})
.await
.map_err(|e| e.to_string())?
}
#[tauri::command]
pub async fn git_status(
window: Window,
state: State<'_, WorkspaceState>,
) -> Result<GitStatus, String> {
let root = root(&state, &window)?;
task(move || status(&root)).await
}
#[tauri::command]
pub async fn git_diff(
window: Window,
state: State<'_, WorkspaceState>,
path: String,
staged: bool,
) -> Result<String, String> {
let root = root(&state, &window)?;
task(move || diff(&root, &path, staged)).await
}
#[tauri::command]
pub async fn git_stage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, true)).await
}
#[tauri::command]
pub async fn git_unstage(
window: Window,
state: State<'_, WorkspaceState>,
paths: Vec<String>,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || change_index(&root, &paths, false)).await
}
#[tauri::command]
pub async fn git_commit(
window: Window,
state: State<'_, WorkspaceState>,
message: String,
) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || commit(&root, &message)).await
}
#[tauri::command]
pub async fn git_blame(
window: Window,
state: State<'_, WorkspaceState>,
path: String,
line: u32,
) -> Result<Option<GitLineInfo>, String> {
let root = root(&state, &window)?;
task(move || blame(&root, &path, line)).await
}
#[tauri::command]
pub async fn git_push(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || synchronize(&root, true)).await
}
#[tauri::command]
pub async fn git_pull(window: Window, state: State<'_, WorkspaceState>) -> Result<(), String> {
let root = root(&state, &window)?;
task(move || synchronize(&root, false)).await
}
#[tauri::command]
pub async fn git_graph(window: Window, state: State<'_, WorkspaceState>) -> Result<GitGraph, String> {
let root = root(&state, &window)?;
task(move || graph(&root)).await
}
#[tauri::command]
pub async fn git_commit_details(window: Window, state: State<'_, WorkspaceState>, commit: String) -> Result<GitCommitDetails, String> {
let root = root(&state, &window)?;
task(move || commit_details(&root, &commit)).await
}
#[tauri::command]
pub async fn git_commit_diff(window: Window, state: State<'_, WorkspaceState>, commit: String, path: String) -> Result<String, String> {
let root = root(&state, &window)?;
task(move || commit_diff(&root, &commit, &path)).await
}
#[cfg(test)]
#[path = "git_sync_tests.rs"]
mod sync_tests;
#[cfg(test)]
mod tests {
use super::*;
struct Repo(PathBuf);
impl Repo {
fn new() -> Self {
let path =
std::env::temp_dir().join(format!("runestone-git-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&path).unwrap();
let root = dunce::canonicalize(path).unwrap();
checked(&root, &["init", "--initial-branch=main"]).unwrap();
checked(&root, &["config", "user.name", "RuneStone Test"]).unwrap();
checked(&root, &["config", "user.email", "[email protected]"]).unwrap();
Self(root)
}
fn write(&self, path: &str, text: &str) {
std::fs::write(self.0.join(path), text).unwrap();
}
}
impl Drop for Repo {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn commit_details_cover_root_rename_deletion_and_full_messages() {
let repo = Repo::new();
repo.write("before 名.txt", "retained content\n");
change_index(&repo.0, &["before 名.txt".into()], true).unwrap();
commit(&repo.0, "Initial title\n\nFull commit description.").unwrap();
let first = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
let details = commit_details(&repo.0, &first).unwrap();
assert!(details.parents.is_empty());
assert_eq!(details.files[0].status, "A");
assert_eq!(details.files[0].path, "before 名.txt");
assert!(details.message.contains("Full commit description."));
assert!(commit_diff(&repo.0, &first, "before 名.txt").unwrap().contains("+retained content"));
checked(&repo.0, &["mv", "before 名.txt", "after 名.txt"]).unwrap();
commit(&repo.0, "Rename file").unwrap();
let renamed = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
let details = commit_details(&repo.0, &renamed).unwrap();
assert_eq!(details.files[0].original_path.as_deref(), Some("before 名.txt"));
assert!(commit_diff(&repo.0, &renamed, "after 名.txt").unwrap().contains("similarity index 100%"));
checked(&repo.0, &["rm", "after 名.txt"]).unwrap();
commit(&repo.0, "Delete file").unwrap();
let deleted = checked(&repo.0, &["rev-parse", "HEAD"]).unwrap().trim().to_owned();
assert_eq!(commit_details(&repo.0, &deleted).unwrap().files[0].status, "D");
assert!(commit_diff(&repo.0, &deleted, "after 名.txt").unwrap().contains("-retained content"));
for id in ["HEAD", "--all", "../outside", "abc123", "g123456789012345678901234567890123456789"] { assert!(commit_details(&repo.0, id).is_err()); }
assert!(commit_diff(&repo.0, &first, "missing.txt").is_err());
assert!(commit_diff(&repo.0, &first, "../escape").is_err());
}
#[test]
fn unborn_stage_unstage_commit_diff_and_blame() {
let repo = Repo::new();
repo.write("notes with spaces.md", "first\n");
let initial = status(&repo.0).unwrap();
assert_eq!(initial.branch.as_deref(), Some("main"));
assert_eq!(initial.changes[0].index, "?");
assert!(diff(&repo.0, "notes with spaces.md", false)
.unwrap()
.contains("+first"));
let paths = vec!["notes with spaces.md".to_owned()];
change_index(&repo.0, &paths, true).unwrap();
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
change_index(&repo.0, &paths, false).unwrap();
assert!(repo.0.join(&paths[0]).exists());
change_index(&repo.0, &paths, true).unwrap();
commit(&repo.0, "First notes").unwrap();
assert!(status(&repo.0).unwrap().changes.is_empty());
assert_eq!(
blame(&repo.0, &paths[0], 1).unwrap().unwrap().author,
"RuneStone Test"
);
repo.write(&paths[0], "second\n");
assert!(diff(&repo.0, &paths[0], false).unwrap().contains("+second"));
change_index(&repo.0, &paths, true).unwrap();
assert!(diff(&repo.0, &paths[0], true).unwrap().contains("+second"));
change_index(&repo.0, &paths, false).unwrap();
assert_eq!(
std::fs::read_to_string(repo.0.join(&paths[0])).unwrap(),
"second\n"
);
}
#[test]
fn rename_and_deleted_files_keep_correct_index_paths() {
let repo = Repo::new();
repo.write("before.txt", "retained content\n");
change_index(&repo.0, &["before.txt".into()], true).unwrap();
commit(&repo.0, "Initial").unwrap();
std::fs::rename(repo.0.join("before.txt"), repo.0.join("after.txt")).unwrap();
change_index(&repo.0, &["before.txt".into(), "after.txt".into()], true).unwrap();
let changes = status(&repo.0).unwrap().changes;
assert_eq!(changes[0].path, "after.txt");
assert_eq!(changes[0].original_path.as_deref(), Some("before.txt"));
assert!(diff(&repo.0, "after.txt", true)
.unwrap()
.contains("rename from before.txt"));
change_index(&repo.0, &["before.txt".into(), "after.txt".into()], false).unwrap();
assert!(repo.0.join("after.txt").exists());
assert!(!repo.0.join("before.txt").exists());
}
#[test]
fn rejects_unsafe_paths_and_parent_repository() {
let repo = Repo::new();
for path in [
"../escape",
"/escape",
"C:/escape",
".git/config",
"nested/../../escape",
"nested\\escape",
":(glob)*",
] {
assert!(safe_path(&repo.0, path).is_err(), "accepted {path}");
}
std::fs::create_dir(repo.0.join("child")).unwrap();
assert!(repository(&repo.0.join("child")).is_err());
assert!(!status(&repo.0.join("child")).unwrap().repository);
repo.write("--all", "literal\n");
change_index(&repo.0, &["--all".into()], true).unwrap();
assert_eq!(status(&repo.0).unwrap().changes[0].path, "--all");
assert!(commit(&repo.0, " ").is_err());
}
#[test]
fn parser_handles_unicode_and_newline_names() {
let changes = parse_status("R new\n名.txt\0old name.txt\0?? new file.txt\0").unwrap();
assert_eq!(changes[0].path, "new\n名.txt");
assert_eq!(changes[0].original_path.as_deref(), Some("old name.txt"));
assert_eq!(changes.len(), 2);
}
#[test]
fn configured_external_worktree_is_rejected() {
let repo = Repo::new();
let outside = Repo::new();
checked(
&repo.0,
&["config", "core.worktree", outside.0.to_str().unwrap()],
)
.unwrap();
assert!(repository(&repo.0).is_err());
assert!(change_index(&repo.0, &["outside.txt".into()], true).is_err());
}
#[test]
fn binary_untracked_preview_does_not_decode_bytes() {
let repo = Repo::new();
std::fs::write(repo.0.join("image.bin"), [0, 255, 1]).unwrap();
assert_eq!(
diff(&repo.0, "image.bin", false).unwrap(),
"Binary file. No text preview is available."
);
}
#[test]
fn commit_keeps_repository_hook_checks() {
let repo = Repo::new();
repo.write("notes.txt", "notes\n");
change_index(&repo.0, &["notes.txt".into()], true).unwrap();
let hook = repo.0.join(".git/hooks/pre-commit");
std::fs::write(
&hook,
"#!/bin/sh\necho 'Test hook rejected the commit' >&2\nexit 1\n",
)
.unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
assert!(commit(&repo.0, "Must fail")
.unwrap_err()
.contains("Test hook rejected"));
assert_eq!(status(&repo.0).unwrap().changes[0].index, "A");
}
}
+179
View File
@@ -0,0 +1,179 @@
use super::*;
struct Fixture(PathBuf);
impl Fixture {
fn new() -> Self {
let root =
std::env::temp_dir().join(format!("runestone-git-sync-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&root).unwrap();
let fixture = Self(dunce::canonicalize(root).unwrap());
fixture.git(
".",
&["init", "--bare", "--initial-branch=main", "remote.git"],
);
fixture.git(".", &["clone", "remote.git", "local"]);
for directory in ["local"] {
fixture.git(directory, &["config", "user.name", "RuneStone Test"]);
fixture.git(directory, &["config", "user.email", "[email protected]"]);
}
fixture
}
fn path(&self, directory: &str) -> PathBuf {
self.0.join(directory)
}
fn git(&self, directory: &str, args: &[&str]) -> String {
checked(&self.path(directory), args).unwrap()
}
fn commit(&self, directory: &str, name: &str, contents: &str) {
std::fs::write(self.path(directory).join(name), contents).unwrap();
self.git(directory, &["add", "--", name]);
self.git(
directory,
&[
"-c",
"user.name=RuneStone Test",
"-c",
"[email protected]",
"commit",
"-m",
contents,
],
);
}
fn seed(&self) {
self.commit("local", "first.txt", "Initial commit");
synchronize(&self.path("local"), true).unwrap();
self.git(".", &["clone", "remote.git", "peer"]);
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[test]
fn push_and_fast_forward_pull_use_only_the_upstream_branch() {
let fixture = Fixture::new();
fixture.seed();
fixture.git("local", &["branch", "unpublished"]);
fixture.git("local", &["tag", "unpublished-tag"]);
fixture.git("local", &["config", "push.default", "matching"]);
fixture.git("local", &["config", "remote.origin.mirror", "true"]);
fixture.commit("local", "second.txt", "Local change");
synchronize(&fixture.path("local"), true).unwrap();
let refs = fixture.git("remote.git", &["for-each-ref", "--format=%(refname)"]);
assert_eq!(refs.trim(), "refs/heads/main");
fixture.git("peer", &["pull", "--ff-only"]);
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.git("local", &["config", "pull.rebase", "true"]);
synchronize(&fixture.path("local"), false).unwrap();
assert_eq!(
fixture.git("local", &["rev-parse", "HEAD"]),
fixture.git("peer", &["rev-parse", "HEAD"])
);
assert_eq!(
std::fs::read_to_string(fixture.path("local").join("peer.txt")).unwrap(),
"Peer change"
);
}
#[test]
fn divergent_push_and_pull_preserve_local_and_remote_commits() {
let fixture = Fixture::new();
fixture.seed();
fixture.commit("peer", "peer.txt", "Peer change");
fixture.git("peer", &["push"]);
fixture.commit("local", "local.txt", "Local change");
fixture.git(
"local",
&[
"config",
"remote.origin.push",
"+refs/heads/main:refs/heads/main",
],
);
fixture.git("local", &["config", "pull.rebase", "true"]);
fixture.git("local", &["config", "pull.ff", "false"]);
let local = fixture.git("local", &["rev-parse", "HEAD"]);
let remote = fixture.git("remote.git", &["rev-parse", "HEAD"]);
assert!(synchronize(&fixture.path("local"), true).is_err());
assert!(synchronize(&fixture.path("local"), false).is_err());
assert_eq!(fixture.git("local", &["rev-parse", "HEAD"]), local);
assert_eq!(fixture.git("remote.git", &["rev-parse", "HEAD"]), remote);
assert!(!fixture.path("local/.git/MERGE_HEAD").exists());
assert!(!fixture.path("local/.git/rebase-merge").exists());
}
#[test]
fn dirty_missing_upstream_detached_and_remote_errors_are_clear() {
let fixture = Fixture::new();
fixture.seed();
std::fs::write(fixture.path("local/first.txt"), "Unsaved change").unwrap();
fixture.git("local", &["config", "merge.autoStash", "true"]);
assert!(synchronize(&fixture.path("local"), false)
.unwrap_err()
.contains("clean working tree"));
assert_eq!(
std::fs::read_to_string(fixture.path("local/first.txt")).unwrap(),
"Unsaved change"
);
fixture.git("local", &["branch", "--unset-upstream"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("no remote upstream"));
fixture.git("local", &["checkout", "--detach"]);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("Select a branch"));
fixture.git("local", &["checkout", "main"]);
fixture.git("local", &["branch", "--set-upstream-to=origin/main"]);
fixture.git(
"local",
&["remote", "set-url", "origin", "../missing-remote.git"],
);
assert!(synchronize(&fixture.path("local"), true)
.unwrap_err()
.contains("Push failed"));
}
#[test]
fn graph_shows_branch_forks_merges_tags_and_detached_history() {
let fixture = Fixture::new();
assert!(graph(&fixture.path("local")).unwrap().commits.is_empty());
fixture.seed();
fixture.git("local", &["checkout", "-b", "feature"]);
fixture.commit("local", "feature.txt", "Feature commit");
fixture.git("local", &["checkout", "main"]);
fixture.commit("local", "main.txt", "Main commit");
fixture.git(
"local",
&["merge", "--no-ff", "feature", "-m", "Merge feature"],
);
fixture.git("local", &["tag", "test-tag"]);
let history = graph(&fixture.path("local")).unwrap();
for expected in [
"HEAD -> main",
"feature",
"test-tag",
"Merge feature",
"RuneStone Test",
] {
assert!(format!("{history:?}").contains(expected), "Missing {expected}: {history:?}");
}
let merge = history.commits.iter().find(|commit| commit.summary == "Merge feature").unwrap();
assert_eq!(merge.parents.len(), 2);
let details = commit_details(&fixture.path("local"), &merge.id).unwrap();
assert_eq!(details.files.len(), 1);
assert_eq!(details.files[0].path, "feature.txt");
assert!(commit_diff(&fixture.path("local"), &merge.id, "feature.txt").unwrap().contains("+Feature commit"));
for parent in &merge.parents {
assert!(history.commits.iter().any(|commit| &commit.id == parent));
}
fixture.git("local", &["checkout", "--detach"]);
fixture.commit("local", "detached.txt", "Detached commit");
assert!(graph(&fixture.path("local"))
.unwrap()
.commits.iter().any(|commit| commit.summary == "Detached commit"));
}
+20
View File
@@ -3,8 +3,10 @@ mod plugins;
mod plugin_sources;
mod workspace;
mod browser;
mod git;
mod completion;
mod settings;
mod spelling;
use pty::PtyState;
use tauri::Manager;
@@ -22,11 +24,26 @@ pub fn run() {
.manage(completion::CompletionState::default())
.manage(settings::SettingsState::default())
.invoke_handler(tauri::generate_handler![
spelling::spelling_menu_install,
spelling::spelling_menu_select,
spelling::spelling_menu_uninstall,
settings::settings_open_window,
completion::completion_request,
completion::completion_cancel,
browser::browser_request,
browser::browser_connect,
browser::browser_stop,
git::git_status,
git::git_diff,
git::git_stage,
git::git_unstage,
git::git_commit,
git::git_blame,
git::git_push,
git::git_pull,
git::git_graph,
git::git_commit_diff,
git::git_commit_details,
workspace::workspace_open,
workspace::workspace_open_window,
workspace::workspace_last_path,
@@ -45,6 +62,8 @@ pub fn run() {
workspace::workspace_copy,
workspace::workspace_abs_path,
workspace::workspace_reveal,
workspace::workspace_open_terminal,
workspace::workspace_open_default,
workspace::workspace_search,
plugins::plugins_snapshot,
plugins::plugins_choose,
@@ -73,6 +92,7 @@ pub fn run() {
.run(|app, event| {
if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event {
settings::close_owned_window(app, label);
spelling::close_window(app, label);
app.state::<PtyState>().close_window(label);
app.state::<completion::CompletionState>().close_window(label);
app.state::<browser::BrowserState>().close_window(label);
+1 -1
View File
@@ -91,7 +91,7 @@ pub async fn settings_open_window(
.title(title)
.inner_size(920.0, 650.0)
.min_inner_size(540.0, 420.0)
.decorations(true)
.decorations(false)
.resizable(true)
.visible(false)
.disable_drag_drop_handler()
+216
View File
@@ -0,0 +1,216 @@
//! Display WebView2 spelling commands through the shared frontend menu.
//! Keep COM event arguments on the WebView thread until selection or cancellation.
#[cfg(any(windows, test))]
#[derive(Debug, PartialEq)]
enum Selection { Stale, Cancel, Native, Command(i32) }
#[cfg(any(windows, test))]
fn requires_native_label(kind: i32, label: &str) -> bool {
kind != 3 && label.trim().is_empty()
}
#[cfg(any(windows, test))]
fn selection(current: &str, request: &str, command: Option<i32>, fallback: bool, enabled: &std::collections::HashSet<i32>) -> Selection {
if current != request { return Selection::Stale; }
if fallback { return Selection::Native; }
command.filter(|id| enabled.contains(id)).map(Selection::Command).unwrap_or(Selection::Cancel)
}
#[cfg(windows)]
mod native {
use std::{cell::RefCell, collections::{HashMap, HashSet}};
use serde::Serialize;
use tauri::{Emitter, Manager};
use webview2_com::{take_pwstr, ContextMenuRequestedEventHandler, Microsoft::Web::WebView2::Win32::*};
use windows::core::{Interface, PWSTR, BOOL};
#[derive(Clone, Serialize)]
pub struct Item {
id: i32, name: String, label: String, shortcut: String, kind: i32,
enabled: bool, checked: bool, children: Vec<Item>,
}
#[derive(Clone, Serialize)]
struct Menu { request: String, items: Vec<Item> }
fn requires_native(items: &[Item]) -> bool {
items.iter().any(|item| super::requires_native_label(item.kind, &item.label) || requires_native(&item.children))
}
struct Pending {
request: String, args: ICoreWebView2ContextMenuRequestedEventArgs,
deferral: ICoreWebView2Deferral, commands: HashSet<i32>,
}
impl Drop for Pending {
fn drop(&mut self) { unsafe { let _ = self.deferral.Complete(); } }
}
thread_local! {
static PENDING: RefCell<HashMap<String, Pending>> = RefCell::new(HashMap::new());
static INSTALLED: RefCell<HashMap<String, (ICoreWebView2_11, i64)>> = RefCell::new(HashMap::new());
}
unsafe fn text(read: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result<String> {
let mut value = PWSTR::null();
let result = read(&mut value);
let text = take_pwstr(value);
result.map(|_| text)
}
unsafe fn items(collection: ICoreWebView2ContextMenuItemCollection, commands: &mut HashSet<i32>, parent_enabled: bool) -> windows::core::Result<Vec<Item>> {
let mut count = 0;
collection.Count(&mut count)?;
let mut result = Vec::new();
for index in 0..count {
let item = collection.GetValueAtIndex(index)?;
let (mut id, mut kind, mut enabled, mut checked) = (0, COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND, BOOL(0), BOOL(0));
item.CommandId(&mut id)?;
item.Kind(&mut kind)?;
item.IsEnabled(&mut enabled)?;
item.IsChecked(&mut checked)?;
let enabled = parent_enabled && enabled.as_bool();
let children = if kind == COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { items(item.Children()?, commands, enabled)? } else { Vec::new() };
if enabled && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SEPARATOR && kind != COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_SUBMENU { commands.insert(id); }
result.push(Item {
id, name: text(|value| item.Name(value))?, label: text(|value| item.Label(value))?,
shortcut: text(|value| item.ShortcutKeyDescription(value))?, kind: kind.0,
enabled, checked: checked.as_bool(), children,
});
}
Ok(result)
}
pub fn install(window: &tauri::WebviewWindow, controller: ICoreWebView2Controller) -> Result<(), String> {
let label = window.label().to_owned();
if INSTALLED.with(|installed| installed.borrow().contains_key(&label)) { return Ok(()); }
let app = window.app_handle().clone();
let owner = label.clone();
unsafe {
let core: ICoreWebView2_11 = controller.CoreWebView2().map_err(|e| e.to_string())?.cast().map_err(|e| e.to_string())?;
let handler = ContextMenuRequestedEventHandler::create(Box::new(move |_, args| {
let Some(args) = args else { return Ok(()); };
let mut editable = BOOL(0);
args.ContextMenuTarget()?.IsEditable(&mut editable)?;
if !editable.as_bool() { return Ok(()); }
let mut commands = HashSet::new();
let entries = items(args.MenuItems()?, &mut commands, true)?;
// WebView2 can omit spelling labels and reject their command IDs.
// Its native menu still owns the suggestion text and correction.
if requires_native(&entries) { return Ok(()); }
let Some(window) = app.get_webview_window(&owner) else { return Ok(()); };
let pending = Pending { request: uuid::Uuid::new_v4().to_string(), args: args.clone(), deferral: args.GetDeferral()?, commands };
let menu = Menu { request: pending.request.clone(), items: entries };
args.SetHandled(true)?;
let previous = PENDING.with(|state| state.borrow_mut().insert(owner.clone(), pending));
drop(previous);
if window.emit("spelling-menu", menu).is_err() {
// Restore the native menu if the frontend cannot receive the request.
let _ = args.SetHandled(false);
let pending = PENDING.with(|state| state.borrow_mut().remove(&owner));
drop(pending);
}
Ok(())
}));
let mut token = 0;
core.add_ContextMenuRequested(&handler, &mut token).map_err(|e| e.to_string())?;
INSTALLED.with(|installed| { installed.borrow_mut().insert(label, (core, token)); });
}
Ok(())
}
pub fn select(label: &str, request: &str, command: Option<i32>, fallback: bool) {
let result = PENDING.with(|state| {
let mut state = state.borrow_mut();
let pending = state.get(label)?;
let choice = super::selection(&pending.request, request, command, fallback, &pending.commands);
if choice == super::Selection::Stale { return None; }
Some((state.remove(label)?, choice))
});
if let Some((pending, choice)) = result {
unsafe {
match choice {
super::Selection::Command(id) => { let _ = pending.args.SetSelectedCommandId(id); }
super::Selection::Native => { let _ = pending.args.SetHandled(false); }
_ => {}
}
}
// Drop completes the deferral after the selected command is set.
}
}
pub fn close(label: &str) {
let pending = PENDING.with(|state| state.borrow_mut().remove(label));
drop(pending);
if let Some((core, token)) = INSTALLED.with(|installed| installed.borrow_mut().remove(label)) {
unsafe { let _ = core.remove_ContextMenuRequested(token); }
}
}
}
#[tauri::command]
pub async fn spelling_menu_install(window: tauri::WebviewWindow) -> Result<(), String> {
#[cfg(windows)] {
let (send, receive) = std::sync::mpsc::channel();
let owner = window.clone();
window.with_webview(move |webview| { let _ = send.send(native::install(&owner, webview.controller())); }).map_err(|e| e.to_string())?;
tauri::async_runtime::spawn_blocking(move || receive.recv().map_err(|e| e.to_string())?).await.map_err(|e| e.to_string())?
}
#[cfg(not(windows))] { let _ = window; Ok(()) }
}
#[tauri::command]
pub fn spelling_menu_select(window: tauri::WebviewWindow, request: String, command: Option<i32>, fallback: Option<bool>) -> Result<(), String> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::select(&label, &request, command, fallback.unwrap_or(false))).map_err(|e| e.to_string())?;
}
#[cfg(not(windows))] { let _ = (window, request, command, fallback); }
Ok(())
}
pub fn close_window(app: &tauri::AppHandle, label: &str) {
#[cfg(windows)] {
let label = label.to_owned();
let _ = app.run_on_main_thread(move || native::close(&label));
}
#[cfg(not(windows))] { let _ = (app, label); }
}
#[tauri::command]
pub fn spelling_menu_uninstall(window: tauri::WebviewWindow) -> Result<(), String> {
#[cfg(windows)] {
let label = window.label().to_owned();
window.with_webview(move |_| native::close(&label)).map_err(|e| e.to_string())?;
}
#[cfg(not(windows))] { let _ = window; }
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn stale_requests_cannot_select_or_cancel_a_new_menu() {
for command in [None, Some(42)] {
assert_eq!(selection("new", "old", command, false, &HashSet::from([42])), Selection::Stale);
assert_eq!(selection("new", "old", command, true, &HashSet::from([42])), Selection::Stale);
}
}
#[test]
fn only_enabled_commands_from_the_current_request_can_run() {
let enabled = HashSet::from([42]);
assert_eq!(selection("a", "a", Some(42), false, &enabled), Selection::Command(42));
assert_eq!(selection("a", "a", Some(43), false, &enabled), Selection::Cancel);
assert_eq!(selection("a", "a", None, false, &enabled), Selection::Cancel);
}
#[test]
fn unmatched_editable_target_keeps_the_native_menu() {
assert_eq!(selection("a", "a", None, true, &HashSet::new()), Selection::Native);
}
#[test]
fn blank_commands_keep_native_suggestions_but_separators_do_not() {
assert!(requires_native_label(0, ""));
assert!(requires_native_label(0, " "));
assert!(requires_native_label(4, ""));
assert!(!requires_native_label(3, ""));
assert!(!requires_native_label(0, "received"));
}
}
+445 -45
View File
@@ -392,12 +392,20 @@ fn workspace_info(root: &Path) -> WorkspaceInfo {
}
fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf) -> WsResult<()> {
open_workspace_tab_window(app, state, root, None)
}
fn open_workspace_tab_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf, transfer: Option<String>) -> WsResult<()> {
static NEXT_WINDOW: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let label = format!("workspace-{}", NEXT_WINDOW.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
let watcher = start_watcher(app.clone(), root.clone(), is_network_path(&root))?;
let mut config = app.config().app.windows.first().cloned().ok_or_else(|| err("Missing window configuration"))?;
config.label = label.clone();
config.title = format!("{} — RuneStone", workspace_info(&root).name);
if let Some(token) = transfer {
let id = uuid::Uuid::parse_str(&token).map_err(|_| err("Invalid tab transfer."))?;
config.url = tauri::WebviewUrl::App(format!("index.html?tabTransfer={id}").into());
}
// Bind before building: the new frontend asks for its own root on startup.
state.inner.lock().map_err(|_| err("workspace lock"))?.insert(label.clone(), OpenWorkspace {
root: root.clone(), _watcher: Some(watcher),
@@ -418,10 +426,10 @@ fn open_workspace_window(app: &AppHandle, state: &WorkspaceState, root: PathBuf)
}
#[tauri::command]
pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String) -> WsResult<()> {
pub async fn workspace_open_window(app: AppHandle, state: State<'_, WorkspaceState>, path: String, transfer: Option<String>) -> WsResult<()> {
let root = dunce::canonicalize(path).map_err(|_| err("folder does not exist"))?;
if !root.is_dir() { return Err(err("path is not a folder")); }
open_workspace_window(&app, &state, root)
open_workspace_tab_window(&app, &state, root, transfer)
}
#[tauri::command]
@@ -456,12 +464,16 @@ pub fn workspace_open(
}
#[tauri::command]
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<Vec<TreeEntry>> {
pub fn workspace_list(window: tauri::Window, state: State<WorkspaceState>, rel: String, show_internal: Option<bool>) -> WsResult<Vec<TreeEntry>> {
let root = current_root(&state, window.label())?;
list_entries(&root, &rel)
list_entries_visible(&root, &rel, show_internal.unwrap_or(false))
}
fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
list_entries_visible(root, rel, false)
}
fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> WsResult<Vec<TreeEntry>> {
let dir = resolve_existing(root, rel)?;
if !dir.is_dir() {
return Err(err("path is not a folder"));
@@ -489,7 +501,7 @@ fn list_entries(root: &Path, rel: &str) -> WsResult<Vec<TreeEntry>> {
Some(n) => n.to_string_lossy().into_owned(),
None => continue,
};
if is_internal_name(&name) {
if is_internal_name(&name) && !(show_internal && name == ".runestone") {
continue;
}
let rel_path = match to_rel(&root, path) {
@@ -596,7 +608,7 @@ pub fn workspace_write(
let root = current_root(&state, window.label())?;
let path = resolve_for_write(&root, &rel)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
fs::create_dir_all(parent).map_err(|reason| err(format!("Could not prepare the save folder for {}: {reason}", path.display())))?;
}
write_text(&path, &contents, expected.as_deref())
}
@@ -624,12 +636,13 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&temp)?;
.open(&temp).map_err(|reason| err(format!("Could not create a save file for {}: {reason}", path.display())))?;
let result = (|| -> WsResult<()> {
file.write_all(contents.as_bytes())?;
file.sync_all()?;
file.write_all(contents.as_bytes()).map_err(|reason| err(format!("Could not write the save file for {}: {reason}", path.display())))?;
file.sync_all().map_err(|reason| err(format!("Could not flush the save file for {}: {reason}", path.display())))?;
#[cfg(not(windows))]
if let Ok(metadata) = fs::metadata(path) {
fs::set_permissions(&temp, metadata.permissions())?;
fs::set_permissions(&temp, metadata.permissions()).map_err(|reason| err(format!("Could not preserve file permissions for {}: {reason}", path.display())))?;
}
drop(file);
// Recheck after preparing the replacement to narrow the external-write race.
@@ -640,7 +653,7 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
));
}
}
fs::rename(&temp, path)?;
replace_saved_file(&temp, path, expected.is_none())?;
Ok(())
})();
if result.is_err() {
@@ -649,6 +662,79 @@ fn write_text(path: &Path, contents: &str, expected: Option<&str>) -> WsResult<(
result
}
#[cfg(not(windows))]
fn replace_saved_file(temp: &Path, path: &Path, _allow_create: bool) -> WsResult<()> {
fs::rename(temp, path).map_err(|reason| err(format!(
"Could not replace {}: {reason}. Your edits are still open.", path.display()
)))
}
#[cfg(windows)]
fn replace_saved_file(temp: &Path, path: &Path, allow_create: bool) -> WsResult<()> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::Storage::FileSystem::ReplaceFileW;
let metadata = match fs::metadata(path) {
Ok(metadata) => metadata,
Err(reason) if reason.kind() == std::io::ErrorKind::NotFound && allow_create => {
return fs::rename(temp, path).map_err(|reason| err(format!(
"Could not publish {}: {reason}. Your edits are still open.", path.display()
)));
}
Err(reason) => return Err(err(format!(
"Could not read the destination {}: {reason}. Your edits are still open.", path.display()
))),
};
if metadata.permissions().readonly() {
return Err(err(format!("Cannot save {} because it is read-only. Your edits are still open.", path.display())));
}
// Canonical Windows paths retain the extended prefix for long filenames.
let target = fs::canonicalize(path)?;
let replacement = fs::canonicalize(temp)?;
let backup = target.parent().ok_or_else(|| err("file has no parent"))?
.join(format!(".runestone-save-backup-{}", uuid::Uuid::new_v4()));
if backup.try_exists()? { return Err(err("The save backup path already exists. Retry saving.")); }
let wide = |value: &Path| value.as_os_str().encode_wide().chain(Some(0)).collect::<Vec<_>>();
let target_wide = wide(&target);
let replacement_wide = wide(&replacement);
let backup_wide = wide(&backup);
// ReplaceFile preserves Windows file metadata. A backup allows recovery if
// Windows moves the original but cannot publish its replacement.
let replaced = unsafe { ReplaceFileW(
target_wide.as_ptr(), replacement_wide.as_ptr(), backup_wide.as_ptr(),
0, std::ptr::null(), std::ptr::null(),
) };
if replaced != 0 {
let _ = fs::remove_file(&backup);
return Ok(());
}
let reason = std::io::Error::last_os_error();
if backup.try_exists()? {
if !path.try_exists()? {
if let Err(restore) = restore_save_backup(&backup, path) {
return Err(err(format!(
"Could not save {}: {reason}. Restore failed: {restore}. The original file remains at {}.",
path.display(), backup.display()
)));
}
} else {
return Err(err(format!(
"Could not save {}: {reason}. A recovery copy remains at {}. Your edits are still open.",
path.display(), backup.display()
)));
}
}
Err(err(format!("Could not replace {}: {reason}. Your edits are still open.", path.display())))
}
#[cfg(windows)]
fn restore_save_backup(backup: &Path, path: &Path) -> std::io::Result<()> {
// A concurrent writer must never lose its file during recovery.
fs::hard_link(backup, path)?;
let _ = fs::remove_file(backup);
Ok(())
}
fn is_internal_name(name: &str) -> bool {
matches!(name, ".git" | ".obsidian" | ".runestone") || name.starts_with(".runestone-save-")
}
@@ -694,9 +780,21 @@ fn create_text_if_absent(path: &Path, contents: &str) -> WsResult<()> {
result
}
fn guarded_mutation_root(state: &WorkspaceState, label: &str, expected_root: Option<&str>) -> WsResult<PathBuf> {
let root = current_root(state, label)?;
if let Some(expected) = expected_root {
let changed = || err("The workspace changed. Repeat the operation in the current workspace.");
if !Path::new(expected).is_absolute() { return Err(changed()); }
let expected = dunce::canonicalize(expected).map_err(|_| changed())?;
let current = dunce::canonicalize(&root).map_err(|_| changed())?;
if expected != current { return Err(changed()); }
}
Ok(root)
}
#[tauri::command]
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String) -> WsResult<()> {
let root = current_root(&state, window.label())?;
pub fn workspace_rename(window: tauri::Window, state: State<WorkspaceState>, from: String, to: String, expected_root: Option<String>) -> WsResult<()> {
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
let from_path = resolve_existing(&root, &from)?;
if from_path == root {
return Err(err("the workspace root cannot be renamed"));
@@ -765,7 +863,7 @@ pub fn workspace_read_data_url(window: tauri::Window, state: State<WorkspaceStat
))
}
fn copy_destination(path: &Path) -> PathBuf {
fn copy_destination(path: &Path, number: u32) -> PathBuf {
let parent = path.parent().unwrap_or(path);
let stem = path
.file_stem()
@@ -775,33 +873,41 @@ fn copy_destination(path: &Path) -> PathBuf {
.extension()
.map(|e| format!(".{}", e.to_string_lossy()))
.unwrap_or_default();
let mut n = 1u32;
loop {
let name = if n == 1 {
format!("{stem} copy{ext}")
} else {
format!("{stem} copy {n}{ext}")
};
let dest = parent.join(name);
if !dest.exists() {
return dest;
}
n += 1;
}
let name = if number == 1 { format!("{stem} copy{ext}") } else { format!("{stem} copy {number}{ext}") };
parent.join(name)
}
fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
if from.is_dir() {
fs::create_dir_all(to)?;
for entry in fs::read_dir(from)? {
let entry = entry?;
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
}
let metadata = fs::symlink_metadata(from)?;
if metadata.file_type().is_symlink() {
return Err(std::io::Error::other("Cannot copy symbolic links."));
}
let partial = |reason| std::io::Error::other(format!(
"Could not complete the copy at {}: {reason}. Any copied items remain there.", to.display()
));
if metadata.is_dir() {
// This reserves the directory. Never merge into an existing destination.
fs::create_dir(to)?;
let result = (|| -> std::io::Result<()> {
for entry in fs::read_dir(from)? {
let entry = entry?;
copy_tree(&entry.path(), &to.join(entry.file_name()))?;
}
Ok(())
})();
// Only a root reservation failure can cause a retry with another name.
result.map_err(partial)?;
} else if metadata.is_file() {
let mut source = fs::File::open(from)?;
let mut target = fs::OpenOptions::new().write(true).create_new(true).open(to)?;
let result = (|| -> std::io::Result<()> {
std::io::copy(&mut source, &mut target)?;
target.set_permissions(metadata.permissions())?;
Ok(())
})();
result.map_err(partial)?;
} else {
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(from, to)?;
return Err(std::io::Error::other("Only regular files and folders can be copied."));
}
Ok(())
}
@@ -814,14 +920,37 @@ pub struct CopyResult {
}
#[tauri::command]
pub fn workspace_copy(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<CopyResult> {
let root = current_root(&state, window.label())?;
pub fn workspace_copy(window: tauri::Window, state: State<WorkspaceState>, rel: String, parent: Option<String>, expected_root: Option<String>) -> WsResult<CopyResult> {
let root = guarded_mutation_root(&state, window.label(), expected_root.as_deref())?;
copy_workspace_item(&root, &rel, parent.as_deref())
}
fn copy_workspace_item(root: &Path, rel: &str, parent: Option<&str>) -> WsResult<CopyResult> {
if fs::symlink_metadata(join_rel(root, rel)?)?.file_type().is_symlink() {
return Err(err("Cannot copy symbolic links."));
}
let from = resolve_existing(&root, &rel)?;
let dest = copy_destination(&from);
if !is_inside(&root, dest.parent().unwrap_or(&dest)) {
if from == root { return Err(err("Cannot copy the workspace root.")); }
let candidate = if let Some(parent) = parent {
let folder = resolve_existing(&root, &parent)?;
if !folder.is_dir() { return Err(err("Destination is not a folder.")); }
if from.is_dir() && folder.starts_with(&from) { return Err(err("Cannot copy a folder into itself.")); }
folder.join(from.file_name().ok_or_else(|| err("Cannot copy the workspace root."))?)
} else { from.clone() };
if !is_inside(&root, candidate.parent().unwrap_or(&candidate)) {
return Err(err("path is outside the workspace"));
}
copy_tree(&from, &dest)?;
let mut number = if parent.is_some() { 0 } else { 1 };
let dest = loop {
let dest = if number == 0 { candidate.clone() } else { copy_destination(&candidate, number) };
match copy_tree(&from, &dest) {
Ok(()) => break dest,
Err(reason) if reason.kind() == std::io::ErrorKind::AlreadyExists => {
number = number.checked_add(1).ok_or_else(|| err("No copy name is available."))?;
}
Err(reason) => return Err(reason.into()),
}
};
let rel_path =
to_rel(&root, &dest).ok_or_else(|| err("copied path is outside the workspace"))?;
let name = dest
@@ -843,6 +972,28 @@ pub fn workspace_abs_path(window: tauri::Window, state: State<WorkspaceState>, r
Ok(dunce::simplified(&path).to_string_lossy().into_owned())
}
#[tauri::command]
pub fn workspace_open_default(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?;
app.opener().open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>).map_err(|e| err(e.to_string()))
}
#[tauri::command]
pub fn workspace_open_terminal(window: tauri::Window, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
let root = current_root(&state, window.label())?;
let path = resolve_existing(&root, &rel)?;
let folder = if path.is_dir() { path.as_path() } else { path.parent().ok_or_else(|| err("Folder unavailable."))? };
#[cfg(windows)]
let mut command = { let mut c = std::process::Command::new("powershell.exe"); c.arg("-NoExit"); c };
#[cfg(target_os = "macos")]
let mut command = { let mut c = std::process::Command::new("open"); c.args(["-a", "Terminal"]).arg(folder); c };
#[cfg(all(unix, not(target_os = "macos")))]
let mut command = std::process::Command::new("x-terminal-emulator");
command.current_dir(folder).spawn().map_err(|e| err(e.to_string()))?;
Ok(())
}
#[tauri::command]
pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State<WorkspaceState>, rel: String) -> WsResult<()> {
let root = current_root(&state, window.label())?;
@@ -976,6 +1127,22 @@ mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn optional_internal_folder_only_changes_the_file_tree() {
let root = std::env::temp_dir().join(format!("rs-visible-internal-{}", uuid::Uuid::new_v4()));
for folder in [".runestone", ".git", ".obsidian", "notes"] {
fs::create_dir_all(root.join(folder)).unwrap();
fs::write(root.join(folder).join("sample.md"), "sample").unwrap();
}
let root = dunce::canonicalize(root).unwrap();
assert!(!list_entries(&root, "").unwrap().iter().any(|entry| entry.name == ".runestone"));
let shown = list_entries_visible(&root, "", true).unwrap();
assert!(shown.iter().any(|entry| entry.name == ".runestone"));
assert!(!shown.iter().any(|entry| entry.name == ".git" || entry.name == ".obsidian"));
assert!(!search_entries(&root, "sample").unwrap().iter().any(|entry| entry.rel_path.starts_with(".runestone/")));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn markdown_listing_preserves_discovery_and_excludes_hidden_storage() {
let root = std::env::temp_dir().join(format!("rs-markdown-list-{}", uuid::Uuid::new_v4()));
@@ -1130,6 +1297,101 @@ mod tests {
fs::remove_dir_all(dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_card_updates_preserve_file_streams() {
let dir = std::env::temp_dir().join(format!("rs-card-save-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join("card.md");
create_text_if_absent(&path, "original card").unwrap();
let stream = PathBuf::from(format!("{}:review-tag", path.display()));
fs::write(&stream, "keep this metadata").unwrap();
write_text(&path, "card with second image", Some("original card")).unwrap();
write_text(&path, "updated description", Some("card with second image")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "updated description");
assert_eq!(fs::read_to_string(&stream).unwrap(), "keep this metadata");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_blocked_replacement_keeps_the_original() {
use std::os::windows::fs::OpenOptionsExt;
let dir = std::env::temp_dir().join(format!("rs-locked-save-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join("card.md");
fs::write(&path, "original").unwrap();
let reader = fs::OpenOptions::new().read(true).share_mode(1).open(&path).unwrap();
let error = write_text(&path, "new", Some("original")).unwrap_err().to_string();
assert!(error.contains("Could not replace"), "{error}");
assert!(error.contains("card.md"), "{error}");
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
drop(reader);
write_text(&path, "new", Some("original")).unwrap();
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_read_only_files_remain_protected() {
let dir = std::env::temp_dir().join(format!("rs-readonly-save-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join("card.md");
fs::write(&path, "original").unwrap();
let mut permissions = fs::metadata(&path).unwrap().permissions();
permissions.set_readonly(true);
fs::set_permissions(&path, permissions).unwrap();
let result = write_text(&path, "new", Some("original"));
let mut permissions = fs::metadata(&path).unwrap().permissions();
permissions.set_readonly(false);
fs::set_permissions(&path, permissions).unwrap();
assert!(result.unwrap_err().to_string().contains("read-only"));
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert_eq!(fs::read_dir(&dir).unwrap().count(), 1);
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_save_recovery_never_overwrites_a_newer_file() {
let dir = std::env::temp_dir().join(format!("rs-save-recovery-{}", uuid::Uuid::new_v4()));
fs::create_dir(&dir).unwrap();
let path = dir.join("card.md");
let backup = dir.join("original.backup");
fs::write(&path, "concurrent edit").unwrap();
fs::write(&backup, "original").unwrap();
assert!(restore_save_backup(&backup, &path).is_err());
assert_eq!(fs::read_to_string(&path).unwrap(), "concurrent edit");
assert_eq!(fs::read_to_string(&backup).unwrap(), "original");
fs::remove_file(&path).unwrap();
restore_save_backup(&backup, &path).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "original");
assert!(!backup.exists());
fs::remove_file(&path).unwrap();
fs::remove_dir(&dir).unwrap();
}
#[cfg(windows)]
#[test]
fn windows_save_supports_extended_paths() {
let root = std::env::temp_dir().join(format!("rs-long-save-{}", uuid::Uuid::new_v4()));
let mut dir = root.clone();
for _ in 0..7 { dir.push("long-workspace-directory-name-1234567890"); }
fs::create_dir_all(&dir).unwrap();
let path = dir.join("card.md");
write_text(&path, "original", None).unwrap();
write_text(&path, "updated", Some("original")).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "updated");
assert!(root.starts_with(std::env::temp_dir()));
fs::remove_dir_all(root).unwrap();
}
#[test]
fn deleted_files_are_not_silently_recreated() {
let path = std::env::temp_dir().join(format!("rs-missing-{}.md", std::process::id()));
@@ -1189,15 +1451,153 @@ mod tests {
#[test]
fn copy_destination_appends_copy() {
let dir = std::env::temp_dir().join(format!("rs-copy-{}", std::process::id()));
let dir = std::env::temp_dir().join(format!("rs-copy-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(&dir).unwrap();
let src = dir.join("hello.py");
fs::write(&src, "x").unwrap();
let dest = copy_destination(&src);
let dest = copy_destination(&src, 1);
assert_eq!(dest.file_name().unwrap(), "hello copy.py");
fs::write(&dest, "y").unwrap();
let dest2 = copy_destination(&src);
let dest2 = copy_destination(&src, 2);
assert_eq!(dest2.file_name().unwrap(), "hello copy 2.py");
let _ = fs::remove_dir_all(&dir);
}
#[test]
fn copy_and_rename_guard_rejects_a_changed_window_root_before_mutation() {
let fixture = std::env::temp_dir().join(format!("rs-root-guard-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(fixture.join("first")).unwrap();
fs::create_dir(fixture.join("second")).unwrap();
let first = dunce::canonicalize(fixture.join("first")).unwrap();
let second = dunce::canonicalize(fixture.join("second")).unwrap();
fs::write(first.join("note.md"), "first workspace").unwrap();
fs::write(second.join("note.md"), "second workspace").unwrap();
let state = WorkspaceState::new();
state.bind_terminal("main", first.clone()).unwrap();
state.bind_terminal("other", second.clone()).unwrap();
let expected = first.to_str().unwrap();
assert_eq!(guarded_mutation_root(&state, "main", Some(expected)).unwrap(), first);
assert_eq!(guarded_mutation_root(&state, "main", Some(first.join(".").to_str().unwrap())).unwrap(), first);
assert!(guarded_mutation_root(&state, "other", Some(expected)).is_err());
state.bind_terminal("main", second.clone()).unwrap();
let copy = guarded_mutation_root(&state, "main", Some(expected)).and_then(|root| copy_workspace_item(&root, "note.md", None));
assert!(copy.unwrap_err().to_string().contains("workspace changed"));
let rename = guarded_mutation_root(&state, "main", Some(expected)).and_then(|root| { fs::rename(root.join("note.md"), root.join("renamed.md"))?; Ok(()) });
assert!(rename.is_err());
assert_eq!(fs::read_to_string(first.join("note.md")).unwrap(), "first workspace");
assert_eq!(fs::read_to_string(second.join("note.md")).unwrap(), "second workspace");
assert_eq!(fs::read_dir(&second).unwrap().count(), 1);
assert_eq!(guarded_mutation_root(&state, "main", None).unwrap(), second);
assert!(guarded_mutation_root(&state, "main", Some(".")).is_err());
assert!(guarded_mutation_root(&state, "missing", Some(expected)).is_err());
fs::remove_dir_all(fixture).unwrap();
}
#[test]
fn copy_tree_never_replaces_an_existing_file_or_directory() {
let root = std::env::temp_dir().join(format!("rs-copy-existing-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
fs::write(root.join("source.txt"), "source").unwrap();
fs::write(root.join("existing.txt"), "keep existing").unwrap();
fs::create_dir(root.join("existing-dir")).unwrap();
fs::write(root.join("existing-dir/keep.txt"), "keep directory").unwrap();
for (from, to) in [("source.txt", "existing.txt"), ("source.txt", "existing-dir"), ("existing-dir", "existing.txt"), ("existing-dir", "existing-dir")] {
assert_eq!(copy_tree(&root.join(from), &root.join(to)).unwrap_err().kind(), std::io::ErrorKind::AlreadyExists);
}
assert_eq!(fs::read_to_string(root.join("existing.txt")).unwrap(), "keep existing");
assert_eq!(fs::read_to_string(root.join("existing-dir/keep.txt")).unwrap(), "keep directory");
assert_eq!(fs::read_dir(root.join("existing-dir")).unwrap().count(), 1);
fs::remove_dir_all(root).unwrap();
}
#[test]
fn concurrent_copies_reserve_unique_files_and_directories() {
use std::sync::{Arc, Barrier};
for directory in [false, true] {
let root = std::env::temp_dir().join(format!("rs-copy-race-{}", uuid::Uuid::new_v4()));
fs::create_dir(&root).unwrap();
fs::create_dir(root.join("target")).unwrap();
let root = dunce::canonicalize(root).unwrap();
let mut sources = Vec::new();
for index in 0..8 {
let parent = root.join(format!("source-{index}"));
fs::create_dir(&parent).unwrap();
if directory {
fs::create_dir(parent.join("item")).unwrap();
fs::write(parent.join("item/content.txt"), format!("source {index}")).unwrap();
} else { fs::write(parent.join("item"), format!("source {index}")).unwrap(); }
sources.push(format!("source-{index}/item"));
}
// Existing user content occupies the unsuffixed name.
fs::write(root.join("target/item"), "existing user content").unwrap();
let barrier = Arc::new(Barrier::new(sources.len()));
let threads: Vec<_> = sources.into_iter().enumerate().map(|(index, source)| {
let root = root.clone(); let barrier = barrier.clone();
std::thread::spawn(move || { barrier.wait(); (index, copy_workspace_item(&root, &source, Some("target")).unwrap()) })
}).collect();
let mut destinations = std::collections::HashSet::new();
for thread in threads {
let (index, result) = thread.join().unwrap();
assert!(destinations.insert(result.rel_path.clone()));
let path = root.join(&result.rel_path);
assert_eq!(fs::read_to_string(if directory { path.join("content.txt") } else { path }).unwrap(), format!("source {index}"));
}
assert_eq!(fs::read_to_string(root.join("target/item")).unwrap(), "existing user content");
assert_eq!(fs::read_dir(root.join("target")).unwrap().count(), 9);
fs::remove_dir_all(root).unwrap();
}
}
#[test]
fn copy_rejects_the_workspace_root_and_descendant_destinations() {
let root = std::env::temp_dir().join(format!("rs-copy-root-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(root.join("folder/child")).unwrap();
let root = dunce::canonicalize(root).unwrap();
fs::write(root.join("folder/note.md"), "source").unwrap();
for (source, parent) in [("", None), ("folder", Some("folder")), ("folder", Some("folder/child")), ("folder", Some(".."))] {
assert!(copy_workspace_item(&root, source, parent).is_err());
}
let duplicate = copy_workspace_item(&root, "folder/note.md", None).unwrap();
assert_eq!(duplicate.name, "note copy.md");
assert_eq!(fs::read_to_string(root.join(&duplicate.rel_path)).unwrap(), "source");
assert!(!root.join("folder/child/folder").exists());
fs::remove_dir_all(root).unwrap();
}
#[cfg(any(unix, windows))]
#[test]
fn copy_rejects_source_links_and_preserves_destination_links_and_partial_folders() {
let root = std::env::temp_dir().join(format!("rs-copy-links-{}", uuid::Uuid::new_v4()));
fs::create_dir_all(root.join("source-folder")).unwrap();
fs::create_dir(root.join("target")).unwrap();
let root = dunce::canonicalize(root).unwrap();
fs::write(root.join("original.txt"), "original user content").unwrap();
fs::write(root.join("copy.txt"), "copy content").unwrap();
#[cfg(unix)]
let symlink = std::os::unix::fs::symlink;
#[cfg(windows)]
let symlink = std::os::windows::fs::symlink_file;
if let Err(reason) = symlink(root.join("original.txt"), root.join("source-link")) {
#[cfg(windows)]
if reason.raw_os_error() == Some(1314) { eprintln!("Symbolic-link test requires Windows Developer Mode or symlink privilege."); fs::remove_dir_all(root).unwrap(); return; }
panic!("Could not prepare the link test: {reason}");
}
assert!(copy_workspace_item(&root, "source-link", Some("target")).unwrap_err().to_string().contains("symbolic links"));
symlink(root.join("original.txt"), root.join("target/copy.txt")).unwrap();
let first = copy_workspace_item(&root, "copy.txt", Some("target")).unwrap();
assert_eq!(first.name, "copy copy.txt");
assert_eq!(fs::read_to_string(root.join("original.txt")).unwrap(), "original user content");
assert!(fs::symlink_metadata(root.join("target/copy.txt")).unwrap().file_type().is_symlink());
symlink(root.join("missing.txt"), root.join("target/copy copy 2.txt")).unwrap();
let second = copy_workspace_item(&root, "copy.txt", Some("target")).unwrap();
assert_eq!(second.name, "copy copy 3.txt");
assert!(!root.join("missing.txt").exists());
symlink(root.join("original.txt"), root.join("source-folder/link.txt")).unwrap();
let error = copy_workspace_item(&root, "source-folder", Some("target")).unwrap_err().to_string();
assert!(error.contains("Any copied items remain there"), "{error}");
assert!(root.join("target/source-folder").is_dir());
assert!(!root.join("target/source-folder copy").exists());
assert_eq!(fs::read_to_string(root.join("original.txt")).unwrap(), "original user content");
fs::remove_dir_all(root).unwrap();
}
}
+5 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "RuneStone",
"version": "0.1.10",
"version": "0.1.18",
"identifier": "com.runestone.app",
"build": {
"beforeDevCommand": "pnpm dev",
@@ -34,6 +34,9 @@
"icons/[email protected]",
"icons/icon.icns",
"icons/icon.ico"
]
],
"resources": {
"browser-engine/": "browser-engine/"
}
}
}
+28 -18
View File
@@ -17,9 +17,12 @@ body {
color: var(--rs-text-strong);
font-family: var(--rs-font-ui);
font-size: 13px;
font-weight: var(--rs-font-weight);
line-height: 1.4;
}
h1, h2, h3, h4, h5, h6 { font-family: var(--rs-font-heading); }
button,
input,
textarea,
@@ -96,25 +99,28 @@ button:disabled {
min-width: 0;
margin: 0 auto;
color: var(--rs-text);
font: var(--rs-prose-size)/1.75 var(--rs-font-prose);
font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose);
overflow-wrap: anywhere;
}
.reading h1, .reading h2, .reading h3,
.reading h4, .reading h5, .reading h6 {
.reading h4, .reading h5, .reading h6, .live-writer .writer-heading {
color: var(--rs-text-strong);
font-weight: 650;
line-height: 1.3;
font-family: var(--rs-font-heading);
font-weight: var(--rs-heading-weight);
line-height: 1.4;
letter-spacing: -0.02em;
margin: 1.8em 0 0.65em;
margin: .9em 0 .4em;
scroll-margin-top: 24px;
}
.reading h1 { font-size: 2.1em; margin-top: 0; margin-bottom: 0.8em; }
.reading h2 { font-size: 1.5em; padding-bottom: 0.4em; border-bottom: 1px solid var(--rs-border); }
.reading h3 { font-size: 1.2em; }
.reading h4 { font-size: 1.05em; }
.reading h5, .reading h6 { font-size: 1em; color: var(--rs-text-dim); }
.document-title, .reading .document-title { margin: 0 0 .85em; color: var(--rs-text-strong); font: 650 2em/1.3 var(--rs-font-prose); overflow-wrap: anywhere; }
.reading h1, .live-writer .writer-h1 { font-size: 1.6em; }
.reading h2, .live-writer .writer-h2 { font-size: 1.35em; }
.reading h1:not(.document-title), .reading h2, .live-writer .writer-h1, .live-writer .writer-h2 { padding-bottom: .25em; border-bottom: 1px solid var(--rs-border); }
.reading h3, .live-writer .writer-h3 { font-size: 1.15em; }
.reading h4, .live-writer .writer-h4 { font-size: 1.05em; }
.reading h5, .reading h6, .live-writer .writer-h5, .live-writer .writer-h6 { font-size: 1em; color: var(--rs-text-dim); }
.live-writer .writer-heading { margin: 0; padding-top: .3em; }
.document-title, .reading .document-title { margin: 0 0 .85em; color: var(--rs-text-strong); font: var(--rs-heading-weight) 1.8em/1.3 var(--rs-font-heading); overflow-wrap: anywhere; }
.note-title-button { position: relative; display: inline-flex; align-items: center; gap: 12px; max-width: 100%; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; overflow-wrap: anywhere; cursor: text; }
.note-title-button .action-icon { opacity: .45; }
.note-title-button:hover .action-icon, .note-title-button:focus-visible .action-icon { opacity: 1; color: var(--rs-accent); }
@@ -126,14 +132,14 @@ button:disabled {
.note-title-error { margin: -.8em 0 1em; color: var(--rs-danger, #e57878); font: 13px/1.5 var(--rs-font-ui); }
.note-title-button[hidden], .note-title-input[hidden], .note-title-error[hidden] { display: none; }
.reading > :first-child { margin-top: 0; }
.reading p { margin: 0 0 1.1em; }
.reading strong { font-weight: 650; color: var(--rs-text-strong); }
.reading p { margin: 0 0 .75em; white-space: pre-line; }
.reading strong { font-weight: 600; color: var(--rs-text-strong); }
.reading a { color: var(--rs-accent); text-decoration-thickness: 1px; text-underline-offset: 3px; }
.reading a:hover { color: var(--rs-accent-2); }
.reading hr { border: 0; border-top: 1px solid var(--rs-border); margin: 2em 0; }
.reading ul, .reading ol { padding-left: 1.6em; margin: 0 0 1.2em; }
.reading li { padding-left: 0.25em; margin: 0.35em 0; }
.reading ul, .reading ol { padding-left: 1.6em; margin: 0 0 .75em; }
.reading li { padding-left: 0.25em; margin: .1em 0; }
.reading li::marker { color: var(--rs-text-dim); }
.reading li > p { margin-bottom: 0.6em; }
.reading li > ul, .reading li > ol { margin: 0.35em 0 0.5em; }
@@ -224,7 +230,7 @@ button:disabled {
.rs-fence-copy:hover { color: var(--rs-text-strong); background: var(--rs-bg-active); }
.rs-fence-copy[data-copied] { color: var(--rs-ok); }
.reading .md-table-scroll { overflow-x: auto; margin: 1.4em 0; border: 1px solid var(--rs-border); border-radius: 0; }
.reading .md-table-scroll { width: fit-content; max-width: 100%; overflow-x: auto; margin: 1.4em 0; border: 1px solid var(--rs-border); border-radius: 0; }
.md-table-formula { color: var(--rs-accent); font-variant-numeric: tabular-nums; }
.md-table-formula.is-error { color: var(--rs-danger, #ed8796); text-decoration: underline dotted; }
.table-footer { display: grid; gap: 8px; margin: 0 26px 1.4em; min-width: 0; font: 12px/1.5 var(--rs-font-ui); color: var(--rs-text-dim); white-space: normal; overflow-wrap: anywhere; }
@@ -243,10 +249,11 @@ button:disabled {
.table-formula-hint { padding: 8px 10px; border-left: 2px solid var(--rs-accent); background: var(--rs-bg-elevated); color: var(--rs-text); }
.table-formula-hint[hidden] { display: none; }
.table-edit-help { font: inherit; color: var(--rs-text-dim); }
.reading table { border-collapse: collapse; width: 100%; font-size: 0.9em; overflow-wrap: normal; word-break: normal; }
.reading th, .reading td { padding: 10px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 8rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
.reading table { border-collapse: collapse; width: auto; max-width: 100%; font-size: 0.95em; line-height: var(--rs-table-line-height); overflow-wrap: normal; word-break: normal; }
.reading th, .reading td { padding: var(--rs-table-cell-padding); text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 3rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
.reading :is(th, td):empty::before,
.reading :is(th, td) > p:empty::before { content: "\200b"; }
.reading :is(th, td) > p { margin: 0; }
.reading th { background: var(--rs-bg-active); font-weight: 600; color: var(--rs-text-strong); }
.reading tbody tr:nth-child(even) { background: var(--rs-line-highlight); }
.reading tbody tr:last-child td { border-bottom: 0; }
@@ -388,3 +395,6 @@ button:disabled {
.reading .md-inline-math { font-family: var(--rs-font-mono); font-style: italic; }
.reading .md-inline-comment { display: none; }
.writer-table .md-inline-comment { display: inline; color: var(--rs-text-dim); background: var(--rs-bg-active); }
.reading:not(.cm-content) :is(p, h1, h2, h3, h4, h5, h6):not(td *, th *) { position: relative; }
.reading:not(.cm-content) :is(p, h1, h2, h3, h4, h5, h6):not(td *, th *):hover::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
+20
View File
@@ -0,0 +1,20 @@
<script lang="ts">
import { onMount } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { state as browserState, request } from './client';
let { open }: { open: (profileId: string, url: string) => Promise<void> } = $props();
let error = $state('');
onMount(() => { void request('state').catch(reason => error = String(reason)); });
</script>
<div class="bookmarks">
{#if error}<p role="alert">{error}</p>{/if}
{#each $browserState?.bookmarks || [] as item (item.id)}
<div class="row"><button class="link" title={item.url} onclick={() => void open(item.profileId, item.url)}><Icon icon="globe" /><span>{item.title}</span></button><IconButton icon="close" label={`Remove ${item.title}`} onclick={() => void request('removeBookmark', { id: item.id })} /></div>
{/each}
</div>
<style>
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-bg-active)}
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-accent)}p{color:var(--rs-error);padding:8px;font-size:12px}
</style>
+204
View File
@@ -0,0 +1,204 @@
<script lang="ts">
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { state as browserState, pageErrors, request, frames } from './client';
import { TabSession, type TabStatus } from './tabSession';
import { AutoScroll } from './autoScroll';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
const tabId = $derived(status.tabId);
const ready = $derived(status.phase === 'ready');
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700;
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
let findTimer: ReturnType<typeof setTimeout> | undefined;
const autoScroll = new AutoScroll();
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, wheelPending = false, movePending = false;
let pendingMove: Record<string, unknown> | undefined;
let suppressedRelease = -1;
const result = $derived(current?.find?.text === findText ? current.find : null);
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
$effect(() => {
void documentKey;
untrack(stopScroll);
if (ready && findOpen) untrack(() => { if (findText && !current?.loading) search(); });
});
export async function find() {
findOpen = true;
await tick(); findField?.focus(); findField?.select();
}
export function detach() { connection.detach(); }
export function action(command: string, args: Record<string, unknown> = {}) { return send(command, args); }
function search(next = false, forward = true) {
clearTimeout(findTimer);
void send('find', { text: findText, next, forward });
}
function closeFind() { clearTimeout(findTimer); findOpen = false; void send('stopFind'); surface.focus(); }
function findKey(event: KeyboardEvent) {
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeFind(); }
else if (event.key === 'Enter' && event.target === findField) { event.preventDefault(); event.stopPropagation(); search(true, !event.shiftKey); }
}
$effect(() => { if (!editing && current?.url) address = current.url === 'about:blank' ? '' : current.url; });
$effect(() => {
const id = tabId;
image = '';
if (!id) return;
frames.set(id, frame => {
if (frame.width > 0 && frame.height > 0 && frame.png.startsWith('iVBORw0KGgo')) image = `data:image/png;base64,${frame.png}`;
});
return () => { frames.delete(id); };
});
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
async function send(command: string, args = {}) {
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args);
}
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
if (opening) return;
opening = true;
try { openingError = ''; await newTab(profileId); } catch (error) { openingError = `Could not open a browser tab: ${String(error)}`; }
finally { opening = false; }
}
onMount(() => {
mounted = true;
const offState = browserState.subscribe(value => { if (value) connection.observe(value); });
void connection.connect();
let timer: ReturnType<typeof setTimeout>;
const resize = new ResizeObserver(entries => {
clearTimeout(timer);
timer = setTimeout(syncSize, 100);
});
resize.observe(surface);
return () => { mounted = false; stopScroll(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
});
function syncSize() {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
width = Math.max(100, Math.min(2560, Math.round(rect.width)));
height = Math.max(100, Math.min(1600, Math.round(rect.height)));
void send('resize', { width, height }); void send('visible', { visible: true });
}
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
function stopScroll() { autoScroll.stop(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function scrollStep(time: number) {
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
const delta = autoScroll.delta(time);
if (delta && !wheelPending && (delta.x || delta.y)) {
wheelPending = true;
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { wheelPending = false; stopScroll(); return; }
const anchor = autoScroll.anchor;
void send('input', { input: { type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y } }).finally(() => wheelPending = false);
}
scrollFrame = requestAnimationFrame(scrollStep);
}
function flushMove() {
moveFrame = 0;
if (!pendingMove || movePending) return;
const input = pendingMove; pendingMove = undefined; movePending = true;
void send('input', { input }).finally(() => {
movePending = false;
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
});
}
function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') surface.focus();
const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
if (type === 'mouseDown' && event.button === 1 && ready) {
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
}
if (autoScroll.anchor) {
if (type === 'mouseMove') autoScroll.move(point);
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
if (type === 'mouseWheel') stopScroll(); else return;
}
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x * width / rect.width))), y: Math.max(0, Math.min(height - 1, Math.round(point.y * height / rect.height))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY, deltaX: -event.deltaX } : {}) };
if (type === 'mouseMove') {
pendingMove = input;
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
} else { pendingMove = undefined; void send('input', { input }); }
}
function key(event: KeyboardEvent, type: string) {
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
event.preventDefault(); event.stopPropagation();
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
void send('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void send('input', { input: { type: 'char', keyCode: event.key } });
}
</script>
<svelte:window onblur={stopScroll} />
<svelte:document onvisibilitychange={() => { if (document.hidden) stopScroll(); }} />
<div class="browser" data-browser-tab={tabId} data-browser-state={status.phase}>
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off">
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
<select aria-label="Browser profile" value={current?.profileId} disabled={opening} onchange={event => void openTab(event.currentTarget.value)}>
{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}
</select>
</form>
{#if findOpen}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
<form class="findbar" role="search" aria-label="Find in page" onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
<input bind:this={findField} bind:value={findText} aria-label="Find in page" placeholder="Find in page" maxlength="1000" autocomplete="off" spellcheck="false"
disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}>
<span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span>
<IconButton icon="up" label="Previous match (Shift+Enter)" disabled={!ready || !findText} onclick={() => search(true, false)} />
<IconButton icon="down" label="Next match (Enter)" disabled={!ready || !findText} onclick={() => search(true)} />
<IconButton icon="close" label="Close find (Escape)" onclick={closeFind} />
</form>
{/if}
{#if status.phase === 'connecting'}<p class="status" role="status">{status.message}</p>{/if}
{#if ready && status.message}<p class="error" role="alert">{status.message}</p>{/if}
{#if status.phase === 'disconnected'}
<div class="error" role="alert"><p>{status.message}</p><button class="reconnect" onclick={() => void connection.connect()}>Reconnect</button></div>
{/if}
{#if status.detail}
<details class="diagnostics"><summary>Browser error details</summary><dl>
<dt>Operation</dt><dd>{status.detail.operation}</dd><dt>Reason</dt><dd>{status.detail.reason}</dd>
<dt>Tab</dt><dd>{status.detail.tabId || 'Not created'}</dd><dt>Time</dt><dd>{status.detail.time}</dd>
<dt>Browser</dt><dd>Included with RuneStone</dd>
</dl></details>
{/if}
{#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if}
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) -->
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0"
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false">{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div>
</div>
<style>
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
input,select{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}select{max-width:160px}input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
.reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer}
dl{display:grid;grid-template-columns:auto 1fr;gap:4px 12px}dd{margin:0;overflow-wrap:anywhere;user-select:text}
</style>
+73
View File
@@ -0,0 +1,73 @@
<script lang="ts">
import { onMount } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import WebData from './WebData.svelte';
import { state as browserState, request } from './client';
let selected = $state('user'), name = $state(''), message = $state('');
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
onMount(() => { void request('state').then(value => {
selected = value.profiles[0].id; search = value.settings.search; adblock = value.settings.adblock;
internalLinks = value.settings.linkDestination === 'internal'; rules = value.settings.personalRules;
homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true;
}).catch(error => message = String(error)); });
async function act(command: string, args: Record<string, unknown>) {
try { const next = await request(command, args); message = 'Changes saved.'; return next; } catch (error) { message = String(error); return null; }
}
async function create(duplicate: boolean) {
if (!name.trim()) { message = 'Enter a profile name.'; return; }
const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name });
if (result) { selected = result.profiles.at(-1)!.id; name = ''; }
}
async function save() {
busy = true; message = 'Saving browser settings…';
try {
await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules,
homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) });
} finally { busy = false; }
}
</script>
<div class="settings">
<h2>Browser</h2><p>Choose how you browse within RuneStone.</p>
<h3>General</h3>
<form onsubmit={event => { event.preventDefault(); if (ready && !busy) void save(); }}>
<fieldset disabled={!ready || busy}>
<div class="card">
<label class="row"><span>Open web links in RuneStone<small>Turn this off to use your system browser.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Open web links in RuneStone" bind:checked={internalLinks}></label>
<label class="row"><span>Homepage<small>The page to open in each new browser tab. Leave blank for an empty page.</small></span><input class="address" type="url" aria-label="Homepage" placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
<label class="row"><span>Search engine</span><select bind:value={search}><option value="duckduckgo">DuckDuckGo</option><option value="google">Google</option><option value="bing">Bing</option></select></label>
<label class="row"><span>Block ads and trackers<small>Apply the filter lists and personal rules to all browser tabs.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Block ads and trackers" bind:checked={adblock}></label>
<label class="row list-row"><span>Ad blocking lists<small>One HTTPS filter list URL per line, up to eight lists. New lists download when you save.</small></span><textarea aria-label="Ad blocking lists" rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
</div>
<label class="rules">Personal filter rules<small>Optional rules to add to the selected lists.</small><textarea rows="4" maxlength="100000" bind:value={rules}></textarea></label>
<button type="submit"><Icon icon="save" />{busy ? 'Saving…' : 'Save browser settings'}</button>
</fieldset>
</form>
<h3>Profiles</h3><p>New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.</p>
<div class="card profiles">
<label>Profile<select aria-label="Profile" bind:value={selected}>{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}</select></label>
<label>New profile name<input bind:value={name} maxlength="60" placeholder="Profile name"></label>
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />New blank profile</button><button onclick={() => void create(true)}><Icon icon="copy" />Duplicate profile</button></div>
<p class="note">Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.</p>
</div>
<h3>Web data</h3><p>Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.</p>
<div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>Clear cache</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>Clear cookies</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>Clear history</button></div>
<p role="status">{message}</p>
{#if ready}<WebData profileId={selected} />{/if}
</div>
<style>
.settings{color:var(--rs-text);font-family:var(--rs-font-ui)}h2{margin:0;font-size:var(--rs-settings-heading-size);font-weight:500;color:var(--rs-text-strong)}h3{margin:var(--rs-settings-section-gap) 0 var(--rs-settings-gap);font-size:14px;font-weight:500}
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)}
input,select,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
.switch{appearance:none;position:relative;flex:none;width:44px;height:26px;border:0;border-radius:999px;background:var(--rs-text-dim);padding:0;cursor:pointer;transition:background .15s}
.switch::before{content:'';position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:var(--rs-bg);box-shadow:0 1px 3px #0004;transition:transform .15s}
.switch:checked{background:var(--rs-accent)}.switch:checked::before{transform:translateX(18px)}:disabled{opacity:.6;cursor:wait}
@media(prefers-reduced-motion:reduce){.switch,.switch::before{transition:none}}
@media(max-width:600px){.row{flex-wrap:wrap}.address,.list-row textarea{width:100%;max-width:100%}}
</style>
+54
View File
@@ -0,0 +1,54 @@
<script lang="ts">
import Icon from '$lib/ui/Icon.svelte';
import { request } from './client';
let { profileId }: { profileId: string } = $props();
type Cookie = { id: string; name: string; domain: string; path: string };
type Visit = { id: string; url: string; title: string; at: number };
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
let kind = $state<'cookies' | 'history'>('cookies');
let generation = 0;
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
$effect(() => { const id = profileId; data = null; query = ''; void refresh(id); return () => { generation++; }; });
async function refresh(id = profileId) {
const ticket = ++generation; busy = true; error = '';
try { const next = await request<Data>('webData', { profileId: id }); if (ticket === generation && id === profileId) data = next; }
catch (reason) { if (ticket === generation) error = String(reason); }
finally { if (ticket === generation) busy = false; }
}
async function remove(command: string, id: string) {
const selected = profileId; const ticket = ++generation; busy = true; error = '';
try { await request(command, { profileId: selected, id }); if (ticket === generation && selected === profileId) await refresh(selected); }
catch (reason) { if (ticket === generation) error = String(reason); }
finally { if (ticket === generation) busy = false; }
}
</script>
<section aria-label="Individual web data">
<div class="toolbar">
<label>Show<select aria-label="Web data type" bind:value={kind}><option value="cookies">Cookies</option><option value="history">History</option></select></label>
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label>
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button>
</div>
<p>Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.</p>
{#if error}<p role="alert">{error}</p>{/if}
{#if busy}<p role="status">Please wait…</p>{/if}
<div class="entries" aria-busy={busy}>
{#if kind === 'cookies'}
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || '(unnamed cookie)'}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={`Remove cookie ${cookie.name} from ${cookie.domain} at ${cookie.path}`} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />Remove</button></div>{/each}
{#if data && !cookies.length}<p>No matching cookies.</p>{/if}
{:else}
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={`Remove history entry ${visit.title || visit.url}`} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />Remove</button></div>{/each}
{#if data && !history.length}<p>No matching history.</p>{/if}
{/if}
</div>
</section>
<style>
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
label{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,select,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
</style>
+23
View File
@@ -0,0 +1,23 @@
export type ScrollPoint = { x: number; y: number };
/** Middle-button scrolling uses wheel input because offscreen Chromium has no native scroll cursor. */
export class AutoScroll {
anchor: ScrollPoint | null = null;
private point: ScrollPoint = { x: 0, y: 0 };
private moved = false;
private previous = 0;
start(point: ScrollPoint) { this.anchor = { ...point }; this.point = { ...point }; this.moved = false; this.previous = 0; }
move(point: ScrollPoint) {
this.point = point;
if (this.anchor && Math.hypot(point.x - this.anchor.x, point.y - this.anchor.y) > 12) this.moved = true;
}
release() { if (this.moved) this.stop(); }
stop() { this.anchor = null; this.previous = 0; }
delta(time: number) {
const elapsed = this.previous ? Math.min(50, time - this.previous) : 0;
this.previous = time;
if (!this.anchor) return null;
const speed = (distance: number) => Math.sign(distance) * Math.min(1800, Math.max(0, Math.abs(distance) - 12) * 8);
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
}
}
+43
View File
@@ -0,0 +1,43 @@
import { invoke } from '@tauri-apps/api/core';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
import { writable } from 'svelte/store';
import { SnapshotOrder } from './snapshotOrder';
export type Profile = { id: string; name: string };
export type Tab = { id: string; transferToken?: string; profileId: string; title: string; favicon?: string | null; url: string; loading: boolean; blocked: number; canBack: boolean; canForward: boolean; find?: { text: string; matches: number; activeMatch: number; pending: boolean } | null };
export type Snapshot = {
runtimeId?: string; revision?: number;
profiles: Profile[]; tabs: Tab[];
bookmarks: { id: string; profileId: string; title: string; url: string }[];
settings: { search: string; adblock: boolean; linkDestination: string; personalRules: string; homepage: string; filterLists: string[] };
};
export const state = writable<Snapshot | null>(null);
export const pageErrors = writable<Record<string, string>>({});
export const frames = new Map<string, (frame: { png: string; width: number; height: number }) => void>();
let snapshots = new SnapshotOrder();
let session: string | undefined;
function isSnapshot(value: unknown): value is Snapshot {
if (!value || typeof value !== 'object') return false;
const record = value as Record<string, unknown>;
return Array.isArray(record.profiles) && Array.isArray(record.tabs) && Array.isArray(record.bookmarks) && !!record.settings && typeof record.settings === 'object';
}
export async function request<T = Snapshot>(command: string, args: Record<string, unknown> = {}): Promise<T> {
const result = await invoke<T>('browser_request', { command, args, session });
if (isSnapshot(result) && snapshots.accept(result)) state.set(result);
return result;
}
export async function connect(signal: AbortSignal) {
session = await invoke<string>('browser_connect');
const window = getCurrentWebviewWindow();
const offState = await window.listen<{ event: string; state?: Snapshot; message?: string; tabId?: string }>('browser-state', ({ payload }) => {
if (signal.aborted) return;
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
});
const offFrame = await window.listen<{ tabId: string; png: string; width: number; height: number }>('browser-frame', ({ payload }) => {
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
});
const stop = async () => { offState(); offFrame(); frames.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
if (signal.aborted) await stop();
return stop;
}
+126
View File
@@ -0,0 +1,126 @@
import { mount, unmount } from 'svelte';
import { get } from 'svelte/store';
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
import type { PluginApi, PluginViewOpenOptions } from '$lib/plugins/sdk';
import Browser from './Browser.svelte';
import Settings from './Settings.svelte';
import Bookmarks from './Bookmarks.svelte';
import { connect, request, state } from './client';
import type { TabStatus } from './tabSession';
type BrowserControl = { find(): Promise<void>; detach(): void; action(command: string, args?: Record<string, unknown>): Promise<void> };
type SavedView = { view: string; profileId?: string; url?: string; runtimeId: string; status?: TabStatus; control?: BrowserControl };
export async function activate(api: PluginApi) {
const dispose = await connect(api.signal); api.onDispose(dispose);
const owners = new Map<string, SavedView>();
const offMove = await getCurrentWebviewWindow().listen<{ tabId: string }>('browser-tab-moved', ({ payload }) => {
const saved = owners.get(payload.tabId);
if (!saved) return;
saved.control?.detach();
api.closeView?.(saved.view);
});
api.onDispose(offMove);
const off = state.subscribe(value => {
for (const tab of value?.tabs || []) {
const saved = owners.get(tab.id);
if (saved) {
saved.profileId = tab.profileId; if (tab.url) saved.url = tab.url;
api.updateViewTitle?.(saved.view, `${tab.title || 'Browser'} · ${value!.profiles.find(p => p.id === tab.profileId)?.name || 'User'}`.slice(0, 200));
api.updateViewIcon?.(saved.view, tab.favicon ?? null);
}
}
});
api.onDispose(off);
const mounts = new Set<() => Promise<void>>();
function retain(instance: ReturnType<typeof mount>) {
let result: Promise<void> | undefined;
const cleanup = () => result ??= unmount(instance).then(() => { mounts.delete(cleanup); });
mounts.add(cleanup); return cleanup;
}
api.onDispose(async () => { await Promise.all([...mounts].map(cleanup => cleanup())); });
async function open(profileId?: string, url?: string, options?: PluginViewOpenOptions, tabId?: string, pinned = false) {
const id = `tab-${crypto.randomUUID()}`;
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
const split = (direction: 'right' | 'down') => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
};
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
tabDragData: ({ pinned }) => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
if (saved.status?.phase !== 'ready' || !current?.transferToken) return undefined;
return JSON.stringify({ tabId: current.id, transferToken: current.transferToken, pinned });
},
find: () => { api.openView(id); void saved.control?.find(); },
tabActions: ({ pinned }) => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
const ready = saved.status?.phase === 'ready';
const web = ready && /^https?:\/\//.test(current?.url || '');
return [
{ separator: true },
{ label: 'Move to new window', icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: 'Split right', icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: 'Split down', icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true },
{ label: 'Find…', icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: 'Open in default browser', icon: 'external', disabled: !web, run: () => run('openExternal') },
{ label: 'Bookmark', icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
];
}, mount: container => {
let runtimeId = '';
const instance = mount(Browser, { target: container, props: {
initial: { tabId, profileId: saved.profileId, url: saved.url },
onSessionChange: value => {
saved.status = value;
if (value.tabId !== runtimeId || value.phase === 'closed') {
owners.delete(runtimeId);
runtimeId = value.phase === 'closed' ? '' : value.tabId;
if (runtimeId) owners.set(runtimeId, saved);
}
saved.runtimeId = runtimeId;
api.updateViewIcon?.(saved.view, get(state)?.tabs.find(tab => tab.id === runtimeId)?.favicon ?? null);
if (value.profileId) saved.profileId = value.profileId;
if (value.url) saved.url = value.url;
},
newTab: (profile: string) => open(profile),
} });
tabId = undefined;
saved.control = instance;
const cleanup = retain(instance);
return async () => { await cleanup(); if (saved.control === instance) saved.control = undefined; };
} });
api.openView(id, options);
}
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run: () => open() });
api.contribute('browser', {
newTab: () => open(),
mountSettings: container => retain(mount(Settings, { target: container })),
mountBookmarks: container => retain(mount(Bookmarks, { target: container, props: { open } })),
open: async url => {
const value = await request('state');
if (value.settings.linkDestination === 'external') return false;
await open(undefined, url); return true;
},
});
api.registerTabDrop?.(async data => {
const payload = JSON.parse(data);
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error('Invalid browser tab transfer.');
const existing = owners.get(payload.tabId);
if (existing) { api.openView(existing.view); return; }
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
if (!current) throw new Error('The browser tab is unavailable.');
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
});
const incoming = new URLSearchParams(location.search).get('browserTab');
if (incoming) {
const snapshot = await request('adoptTab', { tabId: incoming });
const current = snapshot.tabs.find(tab => tab.id === incoming);
await open(current?.profileId, current?.url, undefined, incoming, new URLSearchParams(location.search).get('browserPinned') === 'true');
const url = new URL(location.href);
url.searchParams.delete('browserTab'); url.searchParams.delete('browserPinned');
history.replaceState(null, '', url.pathname + url.search);
}
}

Some files were not shown because too many files have changed in this diff Show More