diff --git a/AGENTS.md b/AGENTS.md index 11d9642..0a72d99 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index d21d23d..bf93110 100644 --- a/README.md +++ b/README.md @@ -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__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 diff --git a/docs/archive/README.md b/docs/archive/README.md new file mode 100644 index 0000000..fed8e6f --- /dev/null +++ b/docs/archive/README.md @@ -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 | diff --git a/docs/archive/app-updating-draft.md b/docs/archive/app-updating-draft.md new file mode 100644 index 0000000..7e55dce --- /dev/null +++ b/docs/archive/app-updating-draft.md @@ -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. diff --git a/docs/archive/development-0.1.8.md b/docs/archive/development-0.1.8.md new file mode 100644 index 0000000..9c3d906 --- /dev/null +++ b/docs/archive/development-0.1.8.md @@ -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. diff --git a/docs/archive/kanban-changes-2026-10-08.md b/docs/archive/kanban-changes-2026-10-08.md new file mode 100644 index 0000000..d18e5f3 --- /dev/null +++ b/docs/archive/kanban-changes-2026-10-08.md @@ -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. + diff --git a/docs/archive/kanban-followup-2026-10-08.md b/docs/archive/kanban-followup-2026-10-08.md new file mode 100644 index 0000000..6251d2f --- /dev/null +++ b/docs/archive/kanban-followup-2026-10-08.md @@ -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. diff --git a/docs/archive/kanban-review-2026-10-08.md b/docs/archive/kanban-review-2026-10-08.md new file mode 100644 index 0000000..005dc84 --- /dev/null +++ b/docs/archive/kanban-review-2026-10-08.md @@ -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. \ No newline at end of file diff --git a/docs/builds.md b/docs/builds.md new file mode 100644 index 0000000..a814eec --- /dev/null +++ b/docs/builds.md @@ -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__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. diff --git a/docs/completion.md b/docs/completion.md index 93d2a95..339e01d 100644 --- a/docs/completion.md +++ b/docs/completion.md @@ -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). diff --git a/docs/development.md b/docs/development.md index 2f86280..b7acf46 100644 --- a/docs/development.md +++ b/docs/development.md @@ -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. diff --git a/docs/guides/document-tools.md b/docs/guides/document-tools.md new file mode 100644 index 0000000..ec3df9f --- /dev/null +++ b/docs/guides/document-tools.md @@ -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 `
` 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. + diff --git a/docs/guides/terminal.md b/docs/guides/terminal.md new file mode 100644 index 0000000..3ecd9e2 --- /dev/null +++ b/docs/guides/terminal.md @@ -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. + diff --git a/docs/guides/themes.md b/docs/guides/themes.md new file mode 100644 index 0000000..5a9db50 --- /dev/null +++ b/docs/guides/themes.md @@ -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. diff --git a/docs/installation.md b/docs/installation.md index 0dae8a9..d5863df 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -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__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__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. diff --git a/docs/plugin-names.md b/docs/plugin-names.md new file mode 100644 index 0000000..f50a8ca --- /dev/null +++ b/docs/plugin-names.md @@ -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-.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. diff --git a/docs/plugins.md b/docs/plugins.md index 3b63fb8..6b4717b 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -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. diff --git a/docs/product-scope.md b/docs/product-scope.md index 41b969b..16e6b02 100644 --- a/docs/product-scope.md +++ b/docs/product-scope.md @@ -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. diff --git a/docs/release-0.1.13.md b/docs/release-0.1.13.md new file mode 100644 index 0000000..9809547 --- /dev/null +++ b/docs/release-0.1.13.md @@ -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. diff --git a/docs/release-0.1.14.md b/docs/release-0.1.14.md new file mode 100644 index 0000000..897e9ae --- /dev/null +++ b/docs/release-0.1.14.md @@ -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. \ No newline at end of file diff --git a/docs/release-0.1.15.md b/docs/release-0.1.15.md new file mode 100644 index 0000000..76af771 --- /dev/null +++ b/docs/release-0.1.15.md @@ -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. diff --git a/docs/release-0.1.16.md b/docs/release-0.1.16.md new file mode 100644 index 0000000..71fab92 --- /dev/null +++ b/docs/release-0.1.16.md @@ -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. diff --git a/docs/release-0.1.17.md b/docs/release-0.1.17.md new file mode 100644 index 0000000..f433a45 --- /dev/null +++ b/docs/release-0.1.17.md @@ -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. diff --git a/docs/release-0.1.7.md b/docs/release-0.1.7.md deleted file mode 100644 index 149087e..0000000 --- a/docs/release-0.1.7.md +++ /dev/null @@ -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. diff --git a/docs/releases.md b/docs/releases.md index 981df33..98d63c8 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -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__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. diff --git a/docs/roadmap.md b/docs/roadmap.md index c0d6f2a..309ec74 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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? diff --git a/docs/ui-design.md b/docs/ui-design.md new file mode 100644 index 0000000..c811faa --- /dev/null +++ b/docs/ui-design.md @@ -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. + diff --git a/docs/user-guide.md b/docs/user-guide.md index cd9b246..c560742 100644 --- a/docs/user-guide.md +++ b/docs/user-guide.md @@ -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 `
` 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. diff --git a/output/tab-site-icon-dark.png b/output/tab-site-icon-dark.png index 5c853d5..e18778d 100644 Binary files a/output/tab-site-icon-dark.png and b/output/tab-site-icon-dark.png differ diff --git a/output/tab-site-icon-light.png b/output/tab-site-icon-light.png index 4d37b50..e8b5f51 100644 Binary files a/output/tab-site-icon-light.png and b/output/tab-site-icon-light.png differ diff --git a/package.json b/package.json index 2968428..1050478 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.10", + "version": "0.1.18", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { diff --git a/scripts/appearance.smoke.mjs b/scripts/appearance.smoke.mjs new file mode 100644 index 0000000..658b5f7 --- /dev/null +++ b/scripts/appearance.smoke.mjs @@ -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(); } + + diff --git a/scripts/appearance.spec.ts b/scripts/appearance.spec.ts new file mode 100644 index 0000000..6541987 --- /dev/null +++ b/scripts/appearance.spec.ts @@ -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' }); + } +}); diff --git a/scripts/browserInteraction.smoke.mjs b/scripts/browserInteraction.smoke.mjs new file mode 100644 index 0000000..8958f76 --- /dev/null +++ b/scripts/browserInteraction.smoke.mjs @@ -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=''; 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='

Native scroll fixture

'; 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(); +} diff --git a/scripts/browserWebData.smoke.mjs b/scripts/browserWebData.smoke.mjs new file mode 100644 index 0000000..cfb2403 --- /dev/null +++ b/scripts/browserWebData.smoke.mjs @@ -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(); } diff --git a/scripts/builtinBrowser.smoke.mjs b/scripts/builtinBrowser.smoke.mjs new file mode 100644 index 0000000..b316ad0 --- /dev/null +++ b/scripts/builtinBrowser.smoke.mjs @@ -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(); } diff --git a/scripts/customThemes.spec.ts b/scripts/customThemes.spec.ts new file mode 100644 index 0000000..a0c0a0b --- /dev/null +++ b/scripts/customThemes.spec.ts @@ -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" })); +}); diff --git a/scripts/editorFiles.smoke.mjs b/scripts/editorFiles.smoke.mjs new file mode 100644 index 0000000..c23d02b --- /dev/null +++ b/scripts/editorFiles.smoke.mjs @@ -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(); } diff --git a/scripts/editorInteractions.smoke.mjs b/scripts/editorInteractions.smoke.mjs new file mode 100644 index 0000000..b91c3c4 --- /dev/null +++ b/scripts/editorInteractions.smoke.mjs @@ -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(); } diff --git a/scripts/editorLinks.spec.ts b/scripts/editorLinks.spec.ts new file mode 100644 index 0000000..624e788 --- /dev/null +++ b/scripts/editorLinks.spec.ts @@ -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]( "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 (). Mail .'; + assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:person@example.org"]); +}); diff --git a/scripts/images.smoke.mjs b/scripts/images.smoke.mjs index 48e2fe1..dc0655a 100644 --- a/scripts/images.smoke.mjs +++ b/scripts/images.smoke.mjs @@ -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"); diff --git a/scripts/kanbanWorkspace.smoke.mjs b/scripts/kanbanWorkspace.smoke.mjs new file mode 100644 index 0000000..beda113 --- /dev/null +++ b/scripts/kanbanWorkspace.smoke.mjs @@ -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(); } + diff --git a/scripts/markdownTable.spec.ts b/scripts/markdownTable.spec.ts index c2e0d73..99bce9a 100644 --- a/scripts/markdownTable.spec.ts +++ b/scripts/markdownTable.spec.ts @@ -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
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(//g) || []).length, 2); + assert.match(html, /<\/table>[\s\S]*

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(//g) || []).length, 5); + assert.match(renderMarkdownHtml("> | A |\n> | --- |\n> | B |\n> Paragraph", new Map()), /<\/table>[\s\S]*

Paragraph<\/p>/); + assert.match(renderMarkdownHtml("- Item\n\n | A |\n | --- |\n | B |\n Paragraph", new Map()), /<\/table>[\s\S]*

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" }] }, diff --git a/scripts/menuConsistency.smoke.mjs b/scripts/menuConsistency.smoke.mjs index 23f1827..3e91b1e 100644 --- a/scripts/menuConsistency.smoke.mjs +++ b/scripts/menuConsistency.smoke.mjs @@ -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); diff --git a/scripts/pasteRepeat.smoke.mjs b/scripts/pasteRepeat.smoke.mjs new file mode 100644 index 0000000..1233c34 --- /dev/null +++ b/scripts/pasteRepeat.smoke.mjs @@ -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(); } diff --git a/scripts/pluginAccess.smoke.mjs b/scripts/pluginAccess.smoke.mjs index 739137f..e1273b4 100644 --- a/scripts/pluginAccess.smoke.mjs +++ b/scripts/pluginAccess.smoke.mjs @@ -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); diff --git a/scripts/pluginHostExtensions.spec.ts b/scripts/pluginHostExtensions.spec.ts new file mode 100644 index 0000000..c5e3dbd --- /dev/null +++ b/scripts/pluginHostExtensions.spec.ts @@ -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/); +}); diff --git a/scripts/pluginInstall.smoke.mjs b/scripts/pluginInstall.smoke.mjs index 0862e1c..cc9d8c1 100644 --- a/scripts/pluginInstall.smoke.mjs +++ b/scripts/pluginInstall.smoke.mjs @@ -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(); diff --git a/scripts/pluginTabOrder.smoke.mjs b/scripts/pluginTabOrder.smoke.mjs index b62dfe3..2e3516e 100644 --- a/scripts/pluginTabOrder.smoke.mjs +++ b/scripts/pluginTabOrder.smoke.mjs @@ -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) { diff --git a/scripts/settings.spec.ts b/scripts/settings.spec.ts index 56aae33..1ee9193 100644 --- a/scripts/settings.spec.ts +++ b/scripts/settings.spec.ts @@ -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(); 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/); diff --git a/scripts/settingsDensity.smoke.mjs b/scripts/settingsDensity.smoke.mjs new file mode 100644 index 0000000..d53b4f0 --- /dev/null +++ b/scripts/settingsDensity.smoke.mjs @@ -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(); } diff --git a/scripts/settingsTitlebar.smoke.mjs b/scripts/settingsTitlebar.smoke.mjs new file mode 100644 index 0000000..9b2bae9 --- /dev/null +++ b/scripts/settingsTitlebar.smoke.mjs @@ -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(); } diff --git a/scripts/settingsWindow.smoke.mjs b/scripts/settingsWindow.smoke.mjs index ba8a3ce..8dceb53 100644 --- a/scripts/settingsWindow.smoke.mjs +++ b/scripts/settingsWindow.smoke.mjs @@ -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."); diff --git a/scripts/spellingNative.smoke.mjs b/scripts/spellingNative.smoke.mjs new file mode 100644 index 0000000..3d9c1fa --- /dev/null +++ b/scripts/spellingNative.smoke.mjs @@ -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(); +} diff --git a/scripts/tableDrag.smoke.mjs b/scripts/tableDrag.smoke.mjs index 91f4499..372c25e 100644 --- a/scripts/tableDrag.smoke.mjs +++ b/scripts/tableDrag.smoke.mjs @@ -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(); diff --git a/scripts/tableNavigation.smoke.mjs b/scripts/tableNavigation.smoke.mjs index 55ff3c1..3af2b4a 100644 --- a/scripts/tableNavigation.smoke.mjs +++ b/scripts/tableNavigation.smoke.mjs @@ -1,3 +1,4 @@ +import { mockFeaturePlugins } from "./pluginMocks.mjs"; // Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. import { createRequire } from "node:module"; import assert from "node:assert/strict"; @@ -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**
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; diff --git a/scripts/treeMoveHistory.spec.ts b/scripts/treeMoveHistory.spec.ts new file mode 100644 index 0000000..f74b8f7 --- /dev/null +++ b/scripts/treeMoveHistory.spec.ts @@ -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"]); +}); diff --git a/scripts/treeSelection.smoke.mjs b/scripts/treeSelection.smoke.mjs index 91cec35..978919c 100644 --- a/scripts/treeSelection.smoke.mjs +++ b/scripts/treeSelection.smoke.mjs @@ -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'); diff --git a/scripts/uiDensity.smoke.mjs b/scripts/uiDensity.smoke.mjs new file mode 100644 index 0000000..de65d29 --- /dev/null +++ b/scripts/uiDensity.smoke.mjs @@ -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();} diff --git a/scripts/undoHistory.smoke.mjs b/scripts/undoHistory.smoke.mjs new file mode 100644 index 0000000..8c83793 --- /dev/null +++ b/scripts/undoHistory.smoke.mjs @@ -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(); } diff --git a/scripts/workbenchLayout.smoke.mjs b/scripts/workbenchLayout.smoke.mjs new file mode 100644 index 0000000..16983c1 --- /dev/null +++ b/scripts/workbenchLayout.smoke.mjs @@ -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(); } diff --git a/scripts/workbenchLayout.spec.ts b/scripts/workbenchLayout.spec.ts new file mode 100644 index 0000000..e624aa9 --- /dev/null +++ b/scripts/workbenchLayout.spec.ts @@ -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(); + 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/); +}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 85197e2..172712d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -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", ] diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b4cca6b..12e4b15 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -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 diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 55e5285..ebf8459 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -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", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 5d15e7b..d587223 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -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", diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json index 643d7a7..445ebfb 100644 --- a/src-tauri/capabilities/settings.json +++ b/src-tauri/capabilities/settings.json @@ -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" diff --git a/src-tauri/permissions/autogenerated/browser_connect.toml b/src-tauri/permissions/autogenerated/browser_connect.toml new file mode 100644 index 0000000..a44f0b7 --- /dev/null +++ b/src-tauri/permissions/autogenerated/browser_connect.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_blame.toml b/src-tauri/permissions/autogenerated/git_blame.toml new file mode 100644 index 0000000..af1cf11 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_blame.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_commit.toml b/src-tauri/permissions/autogenerated/git_commit.toml new file mode 100644 index 0000000..b50328b --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_commit.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_commit_details.toml b/src-tauri/permissions/autogenerated/git_commit_details.toml new file mode 100644 index 0000000..aef61c3 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_commit_details.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_commit_diff.toml b/src-tauri/permissions/autogenerated/git_commit_diff.toml new file mode 100644 index 0000000..89b73f4 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_commit_diff.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_diff.toml b/src-tauri/permissions/autogenerated/git_diff.toml new file mode 100644 index 0000000..9fd4c45 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_diff.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_graph.toml b/src-tauri/permissions/autogenerated/git_graph.toml new file mode 100644 index 0000000..c9a7dc7 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_graph.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_pull.toml b/src-tauri/permissions/autogenerated/git_pull.toml new file mode 100644 index 0000000..39384cf --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_pull.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_push.toml b/src-tauri/permissions/autogenerated/git_push.toml new file mode 100644 index 0000000..7d52be8 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_push.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_stage.toml b/src-tauri/permissions/autogenerated/git_stage.toml new file mode 100644 index 0000000..33d2bc8 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_stage.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_status.toml b/src-tauri/permissions/autogenerated/git_status.toml new file mode 100644 index 0000000..c77e803 --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_status.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/git_unstage.toml b/src-tauri/permissions/autogenerated/git_unstage.toml new file mode 100644 index 0000000..db29a8b --- /dev/null +++ b/src-tauri/permissions/autogenerated/git_unstage.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/spelling_menu_install.toml b/src-tauri/permissions/autogenerated/spelling_menu_install.toml new file mode 100644 index 0000000..cee5fa7 --- /dev/null +++ b/src-tauri/permissions/autogenerated/spelling_menu_install.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/spelling_menu_select.toml b/src-tauri/permissions/autogenerated/spelling_menu_select.toml new file mode 100644 index 0000000..11e935a --- /dev/null +++ b/src-tauri/permissions/autogenerated/spelling_menu_select.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/spelling_menu_uninstall.toml b/src-tauri/permissions/autogenerated/spelling_menu_uninstall.toml new file mode 100644 index 0000000..3222ec5 --- /dev/null +++ b/src-tauri/permissions/autogenerated/spelling_menu_uninstall.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/workspace_open_default.toml b/src-tauri/permissions/autogenerated/workspace_open_default.toml new file mode 100644 index 0000000..e3f2d98 --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_open_default.toml @@ -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"] diff --git a/src-tauri/permissions/autogenerated/workspace_open_terminal.toml b/src-tauri/permissions/autogenerated/workspace_open_terminal.toml new file mode 100644 index 0000000..e51764c --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_open_terminal.toml @@ -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"] diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs index 5cb5ff9..ad4ff2b 100644 --- a/src-tauri/src/browser.rs +++ b/src-tauri/src/browser.rs @@ -37,11 +37,15 @@ const COMMANDS: &[&str] = &[ "removeBookmark", "settings", "clearData", + "webData", + "removeCookie", + "removeHistory", "agentSnapshot", ]; #[derive(Default)] pub struct BrowserState { inner: Mutex>, + sessions: Mutex>, } #[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 { + 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 { + state.connect(window.label()) +} #[tauri::command] pub async fn browser_request( app: AppHandle, window: tauri::Window, command: String, args: Value, + session: Option, ) -> Result { let owner = window.label().to_string(); - app.state::() - .require_lease(&app, &owner, PLUGIN)?; + if let Some(token) = session { + app.state::().require_session(&owner, &token)?; + } else { + app.state::() + .require_lease(&app, &owner, PLUGIN)?; + } tauri::async_runtime::spawn_blocking(move || { app.state::() .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()]); diff --git a/src-tauri/src/git.rs b/src-tauri/src/git.rs new file mode 100644 index 0000000..1a9e79c --- /dev/null +++ b/src-tauri/src/git.rs @@ -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, + index: String, + worktree: String, +} +#[derive(Debug, Serialize)] +pub struct GitStatus { + available: bool, + repository: bool, + branch: Option, + changes: Vec, +} +#[derive(Debug, Serialize)] +pub struct GitLineInfo { + commit: String, + author: String, + date: String, + summary: String, +} + +fn read_output(mut stream: impl Read) -> Result, 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 { + 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 { + 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, 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 { + 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 { + 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::() + )); + } + 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, + refs: Vec, + summary: String, + author: String, + date: String, +} + +#[derive(Debug, Serialize)] +pub struct GitGraph { + commits: Vec, +} + +fn graph(root: &Path) -> Result { + 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, + status: String, +} +#[derive(Debug, Serialize)] +pub struct GitCommitDetails { + id: String, + parents: Vec, + author: String, + date: String, + message: String, + files: Vec, +} +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, 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 { + 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 = 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 { + 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, 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 { + dunce::canonicalize(current_root_path(state, window.label()).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string()) +} +async fn task( + action: impl FnOnce() -> Result + Send + 'static, +) -> Result { + 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 { + 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 { + 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, +) -> 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, +) -> 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, 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 { + 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 { + 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 { + 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", "test@example.invalid"]).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"); + } +} diff --git a/src-tauri/src/git_sync_tests.rs b/src-tauri/src/git_sync_tests.rs new file mode 100644 index 0000000..0aa5217 --- /dev/null +++ b/src-tauri/src/git_sync_tests.rs @@ -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", "test@example.invalid"]); + } + 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", + "user.email=test@example.invalid", + "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")); +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index b8c22ba..3a1123c 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -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::().close_window(label); app.state::().close_window(label); app.state::().close_window(label); diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index c50b03b..5b90bf6 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -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() diff --git a/src-tauri/src/spelling.rs b/src-tauri/src/spelling.rs new file mode 100644 index 0000000..a046896 --- /dev/null +++ b/src-tauri/src/spelling.rs @@ -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, fallback: bool, enabled: &std::collections::HashSet) -> 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, + } + #[derive(Clone, Serialize)] + struct Menu { request: String, items: Vec } + 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, + } + impl Drop for Pending { + fn drop(&mut self) { unsafe { let _ = self.deferral.Complete(); } } + } + thread_local! { + static PENDING: RefCell> = RefCell::new(HashMap::new()); + static INSTALLED: RefCell> = RefCell::new(HashMap::new()); + } + + unsafe fn text(read: impl FnOnce(*mut PWSTR) -> windows::core::Result<()>) -> windows::core::Result { + 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, parent_enabled: bool) -> windows::core::Result> { + 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, 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, fallback: Option) -> 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")); + } +} diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index 5c17b3b..04191e4 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -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) -> 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) -> 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, rel: String) -> WsResult> { +pub fn workspace_list(window: tauri::Window, state: State, rel: String, show_internal: Option) -> WsResult> { 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> { + list_entries_visible(root, rel, false) +} + +fn list_entries_visible(root: &Path, rel: &str, show_internal: bool) -> WsResult> { 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> { 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::>(); + 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 { + 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, from: String, to: String) -> WsResult<()> { - let root = current_root(&state, window.label())?; +pub fn workspace_rename(window: tauri::Window, state: State, from: String, to: String, expected_root: Option) -> 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 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, rel: String) -> WsResult { - let root = current_root(&state, window.label())?; +pub fn workspace_copy(window: tauri::Window, state: State, rel: String, parent: Option, expected_root: Option) -> WsResult { + 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 { + 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, r Ok(dunce::simplified(&path).to_string_lossy().into_owned()) } +#[tauri::command] +pub fn workspace_open_default(window: tauri::Window, app: AppHandle, state: State, 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, 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, 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(); + } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 37d8a14..24083ab 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "RuneStone", - "version": "0.1.10", + "version": "0.1.18", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", @@ -34,6 +34,9 @@ "icons/128x128@2x.png", "icons/icon.icns", "icons/icon.ico" - ] + ], + "resources": { + "browser-engine/": "browser-engine/" + } } } diff --git a/src/app.css b/src/app.css index d44ae63..c8d47ee 100644 --- a/src/app.css +++ b/src/app.css @@ -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; } diff --git a/src/lib/browser/Bookmarks.svelte b/src/lib/browser/Bookmarks.svelte new file mode 100644 index 0000000..3db49d0 --- /dev/null +++ b/src/lib/browser/Bookmarks.svelte @@ -0,0 +1,20 @@ + +

+ {#if error}

{error}

{/if} + {#each $browserState?.bookmarks || [] as item (item.id)} +
void request('removeBookmark', { id: item.id })} />
+ {/each} +
+ diff --git a/src/lib/browser/Browser.svelte b/src/lib/browser/Browser.svelte new file mode 100644 index 0000000..2ce84bd --- /dev/null +++ b/src/lib/browser/Browser.svelte @@ -0,0 +1,204 @@ + + + { if (document.hidden) stopScroll(); }} /> +
+
{ event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}> + void send('back')} /> + void send('forward')} /> + void send(current?.loading ? 'stop' : 'reload')} /> + editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off"> + void send('bookmark')} /> + + + {#if findOpen} + +
+ diff --git a/src/lib/browser/Settings.svelte b/src/lib/browser/Settings.svelte new file mode 100644 index 0000000..3a7d838 --- /dev/null +++ b/src/lib/browser/Settings.svelte @@ -0,0 +1,73 @@ + +
+

Browser

Choose how you browse within RuneStone.

+

General

+
{ event.preventDefault(); if (ready && !busy) void save(); }}> +
+
+ + + + + +
+ + +
+
+

Profiles

New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.

+
+ + +
+

Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.

+
+

Web data

Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.

+
+

{message}

+ {#if ready}{/if} +
+ diff --git a/src/lib/browser/WebData.svelte b/src/lib/browser/WebData.svelte new file mode 100644 index 0000000..8b76662 --- /dev/null +++ b/src/lib/browser/WebData.svelte @@ -0,0 +1,54 @@ + +
+
+ + + +
+

Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.

+ {#if error}

{error}

{/if} + {#if busy}

Please wait…

{/if} +
+ {#if kind === 'cookies'} + {#each cookies as cookie (cookie.id)}
{cookie.name || '(unnamed cookie)'}{cookie.domain} · {cookie.path}
{/each} + {#if data && !cookies.length}

No matching cookies.

{/if} + {:else} + {#each history as visit (visit.id)}
{visit.title || visit.url}{visit.url}{new Date(visit.at).toLocaleString()}
{/each} + {#if data && !history.length}

No matching history.

{/if} + {/if} +
+
+ diff --git a/src/lib/browser/autoScroll.ts b/src/lib/browser/autoScroll.ts new file mode 100644 index 0000000..1c5956b --- /dev/null +++ b/src/lib/browser/autoScroll.ts @@ -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 }; + } +} diff --git a/src/lib/browser/client.ts b/src/lib/browser/client.ts new file mode 100644 index 0000000..aef395d --- /dev/null +++ b/src/lib/browser/client.ts @@ -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(null); +export const pageErrors = writable>({}); +export const frames = new Map 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; + return Array.isArray(record.profiles) && Array.isArray(record.tabs) && Array.isArray(record.bookmarks) && !!record.settings && typeof record.settings === 'object'; +} +export async function request(command: string, args: Record = {}): Promise { + const result = await invoke('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('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; +} diff --git a/src/lib/browser/index.ts b/src/lib/browser/index.ts new file mode 100644 index 0000000..e5846eb --- /dev/null +++ b/src/lib/browser/index.ts @@ -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; detach(): void; action(command: string, args?: Record): Promise }; +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(); + 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>(); + function retain(instance: ReturnType) { + let result: Promise | 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) => { 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); + } +} diff --git a/src/lib/browser/snapshotOrder.ts b/src/lib/browser/snapshotOrder.ts new file mode 100644 index 0000000..3040a16 --- /dev/null +++ b/src/lib/browser/snapshotOrder.ts @@ -0,0 +1,18 @@ +export class SnapshotOrder { + private runtimeId = ''; + private revision = -1; + private retired = new Set(); + + accept(value: { runtimeId?: string; revision?: number }): boolean { + if (!value.runtimeId || !Number.isSafeInteger(value.revision)) return true; + if (this.retired.has(value.runtimeId)) return false; + if (value.runtimeId !== this.runtimeId) { + if (this.runtimeId) this.retired.add(this.runtimeId); + this.runtimeId = value.runtimeId; + this.revision = -1; + } + if (value.revision! <= this.revision) return false; + this.revision = value.revision!; + return true; + } +} diff --git a/src/lib/browser/tabSession.ts b/src/lib/browser/tabSession.ts new file mode 100644 index 0000000..7efccaf --- /dev/null +++ b/src/lib/browser/tabSession.ts @@ -0,0 +1,104 @@ +import type { Snapshot } from './client'; + +type Transport = (command: string, args?: Record) => Promise; +export type TabStatus = { + tabId: string; profileId?: string; url?: string; + phase: 'connecting' | 'ready' | 'disconnected' | 'closed'; + message: string; + detail?: { operation: string; reason: string; tabId: string; time: string }; +}; +const connectionLost = (error: unknown) => /Unknown browser tab|stopped responding|timed out|response did not match|broken pipe|os error (109|232|10053|10054)\b/i.test(String(error)); + +export class TabSession { + value: TabStatus; + private transport: Transport; + private changed: (value: TabStatus) => void; + private pending?: Promise; + private closed = false; + private recovered = false; + constructor(transport: Transport, initial: { tabId?: string; profileId?: string; url?: string }, changed: (value: TabStatus) => void) { + this.transport = transport; this.changed = changed; + this.value = { ...initial, tabId: initial.tabId || '', phase: 'connecting', message: 'Opening browser…' }; + } + private update(value: Partial) { + this.value = { ...this.value, ...value }; this.changed(this.value); + } + observe(snapshot: Snapshot) { + const tab = snapshot.tabs.find(tab => tab.id === this.value.tabId); + if (tab) { + this.value.profileId = tab.profileId; + // The first snapshot can arrive before navigation starts. + if (tab.url) this.value.url = tab.url; + } + } + private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') { + this.update({ phase, message: phase === 'ready' ? 'The browser could not complete this request. Check the error details.' : connectionLost(error) + ? 'This tab lost its browser connection. Select Reconnect to restore the page.' + : 'The browser could not complete this request. Check the details, then select Reconnect.', + detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } }); + } + connect(): Promise { + if (this.closed) return Promise.resolve(); + if (this.pending) return this.pending; + this.pending = this.restore().finally(() => { this.pending = undefined; }); + return this.pending; + } + private async restore() { + this.update({ phase: 'connecting', message: this.value.tabId ? 'Reconnecting browser…' : 'Opening browser…' }); + let operation = 'state'; + // The host discards a failed transport before the next request. + for (let attempt = 0; attempt < 2; attempt++) { + try { + operation = 'state'; + const snapshot = await this.transport('state') as Snapshot; + if (this.closed) return; + if (snapshot.tabs.some(tab => tab.id === this.value.tabId)) { + this.observe(snapshot); this.update({ phase: 'ready', message: '' }); return; + } + const profileId = this.value.profileId || snapshot.profiles[0]?.id; + operation = 'newTab'; + const result = await this.transport('newTab', { profileId, ...(this.value.url ? { url: this.value.url } : {}) }) as { tabId: string }; + if (this.closed) { await this.transport('closeTab', { tabId: result.tabId }).catch(() => {}); return; } + this.update({ tabId: result.tabId, profileId }); + operation = 'state'; + const current = await this.transport('state') as Snapshot; + if (this.closed) return; + if (current.tabs.some(tab => tab.id === result.tabId)) { + this.observe(current); this.update({ phase: 'ready', message: '' }); return; + } + if (attempt === 1) throw new Error('The runtime restarted twice while opening this tab.'); + } catch (error) { + if (this.closed) return; + if (attempt === 0 && connectionLost(error)) continue; + this.failure(operation, error); return; + } + } + } + async send(command: string, args: Record = {}) { + if (this.closed || this.value.phase !== 'ready') return; + const tabId = this.value.tabId; + try { + await this.transport(command, { ...args, tabId }); + if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' }); + } catch (error) { + // Replies from the previous connection cannot replace the current error. + if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return; + const lost = connectionLost(error); + this.failure(command, error, tabId, lost ? 'disconnected' : 'ready'); + if (lost && !this.recovered) { + this.recovered = true; + await this.connect(); + // Only an explicit address submission is safe to repeat. + if (command === 'navigate' && this.value.phase === 'ready') await this.send(command, args); + } + } + } + detach() { this.closed = true; this.update({ phase: 'closed' }); } + async close() { + if (this.closed) return; + this.closed = true; + const tabId = this.value.tabId; + this.update({ phase: 'closed' }); + if (tabId) await this.transport('closeTab', { tabId }).catch(() => {}); + } +} diff --git a/src/lib/editor/EditorHost.svelte b/src/lib/editor/EditorHost.svelte index d4fb3cc..1e5265a 100644 --- a/src/lib/editor/EditorHost.svelte +++ b/src/lib/editor/EditorHost.svelte @@ -6,27 +6,32 @@ import { editorSession } from "./sessions"; import { registerSelection } from "./selection"; import { monacoChrome } from "./monacoChrome"; + import { codeFont } from "./codeFont"; import { connectMonacoCompletion } from "$lib/completion/monaco"; import { markdownMenu } from "./markdownMenu"; import type { TableContextActions } from "./tableCellActions"; + import { documentLinks, documentLinkAt } from "./documentLinks"; type Props = { buffer: OpenBuffer; chrome: Chrome; onChange: (value: string, id: string) => void; onInsertImage?: (file: File) => Promise; + onOpenLink?: (kind: "md" | "wiki", target: string) => void; focusLine?: number | null; + onSelectionLine?: (line: number) => void; tableActions?: TableContextActions; shouldFocusOnMount?: () => boolean; }; - let { buffer, chrome, onChange, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props(); + let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props(); let host: HTMLDivElement | undefined = $state(); let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined; let ready = $state(0); let applying = false; let loadError = $state(null); + const documentPath = $derived(buffer.relPath); async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) { if (!isMarkdownPath(buffer.relPath) || !onInsertImage) { @@ -77,6 +82,8 @@ $effect(() => { const el = host; + // Buffer snapshots change on each edit. Only a path change remounts Monaco. + const path = documentPath; if (!el) { return; } @@ -88,19 +95,19 @@ let releaseDrop: (() => void) | undefined; let releaseCompletion: (() => void) | undefined; const listeners: { dispose(): void }[] = []; - void import("./monacoEnv").then(({ monaco }) => { + void import("./monacoEnv").then(({ monaco, currentTheme }) => { if (cancelled || !el.isConnected) { return; } session = editorSession(monaco, untrack(() => buffer)); const mode = untrack(() => chrome); const model = session.model; - const markdown = isMarkdownPath(untrack(() => buffer.relPath)); + const markdown = isMarkdownPath(path); const view = monaco.editor.create(el, { model, - theme: "runestone-dark", + theme: currentTheme, automaticLayout: true, - fontFamily: "Cascadia Code, JetBrains Mono, Consolas, ui-monospace, monospace", + ...codeFont(el), scrollBeyondLastLine: false, smoothScrolling: true, cursorBlinking: "smooth", @@ -112,6 +119,37 @@ ...monacoChrome(mode), }); editor = view; + const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`; + if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", { + provideLinks(candidate) { + if (candidate !== model) return { links: [] }; + return { links: documentLinks(model.getValue()).map(link => { + const from = model.getPositionAt(link.from), to = model.getPositionAt(link.to); + return { range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column), + url: `runestone-link://document${linkPath}${link.kind}?${encodeURIComponent(link.target)}`, tooltip: "Open link" }; + }) }; + }, + })); + listeners.push(monaco.editor.registerLinkOpener({ open(resource) { + const url = resource.toString(true); + if (resource.scheme === "runestone-link" && resource.path.startsWith(linkPath)) { + onOpenLink?.(resource.path.slice(linkPath.length) === "wiki" ? "wiki" : "md", decodeURIComponent(resource.query)); + return true; + } + if (view.hasTextFocus() && /^(https?:|mailto:)/i.test(url) && onOpenLink) { onOpenLink("md", url); return true; } + return false; + } })); + const openSourceLink = (event: MouseEvent) => { + if (!markdown || event.button !== 0 || (!event.ctrlKey && !event.metaKey) || !onOpenLink) return; + const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position; + const link = position && documentLinkAt(model.getValue(), model.getOffsetAt(position)); + if (!link) return; + event.preventDefault(); event.stopImmediatePropagation(); + onOpenLink(link.kind, link.target); + }; + el.addEventListener("mousedown", openSourceLink, true); + listeners.push({ dispose: () => el.removeEventListener("mousedown", openSourceLink, true) }); + listeners.push(view.onDidChangeCursorPosition(event => onSelectionLine?.(event.position.lineNumber))); if (markdown) { releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); }); menu = markdownMenu({ @@ -149,6 +187,7 @@ releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown); releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || ""); if (session.view) view.restoreViewState(session.view); + onSelectionLine?.(view.getPosition()?.lineNumber ?? 1); ready += 1; contentListener = model.onDidChangeContent(() => { if (applying) { diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte index 476e0b7..676b901 100644 --- a/src/lib/editor/LiveWriter.svelte +++ b/src/lib/editor/LiveWriter.svelte @@ -1,9 +1,11 @@ { if (event.target === dialog) { event.preventDefault(); onClose(); } }}> -
-

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

- +
+

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

+ {#if windowControls} + {@render windowControls()} + {:else} + + {/if}
{#if !help} @@ -104,6 +111,10 @@

Choose how RuneStone saves your work.

Files

+
+

Show workspace settings and plugin data in the file tree.

+ apply({ ...settings, showInternalFolder: event.currentTarget.checked })} /> +

Save changed notes and scripts, including background tabs.

{ apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} /> @@ -117,6 +128,8 @@ {#if error}{/if}

{message}

+ {:else if selected.id === "appearance"} + {:else if selected.id === "plugins"} {:else if selected.id === "browser"} @@ -141,40 +154,42 @@ dialog::backdrop { background: #0008; } dialog.standalone { width: 100vw; height: 100dvh; margin: 0; border: 0; border-radius: 0; box-shadow: none; } dialog.help { width: min(650px, calc(100vw - 32px)); } - header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); } - h1 { font-size: 14px; font-weight: 600; margin: 0; } - .body { display: flex; height: calc(100% - 48px); } - aside { width: 220px; flex-shrink: 0; padding: 18px 12px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; } - .search { display: flex; gap: 7px; align-items: center; background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 8px; color: var(--rs-text-dim); } + header { height: var(--rs-titlebar-height); padding: 0 4px 0 12px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); } + header.window-header { padding-right: 0; user-select: none; } + h1 { font-size: 13px; font-weight: 600; margin: 0; } + .body { display: flex; height: calc(100% - var(--rs-titlebar-height)); min-height: 0; } + aside { width: 220px; flex-shrink: 0; padding: 12px 8px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; } + .search { display: flex; gap: var(--rs-settings-gap); align-items: center; min-height: var(--rs-settings-control-height); background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 4px 8px; color: var(--rs-text-dim); } .search:focus-within { outline: 2px solid var(--rs-accent); } .search input { width: 100%; min-width: 0; border: 0; padding: 0; outline: none; background: transparent; color: var(--rs-text); } - .nav-heading { margin: 24px 10px 8px; font-size: 11px; color: var(--rs-text-dim); } - nav { display: flex; flex-direction: column; gap: 4px; } - nav button { display: flex; align-items: center; gap: 10px; width: 100%; padding: 10px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; } + .nav-heading { margin: 16px 8px 6px; font-size: 11px; color: var(--rs-text-dim); } + nav { display: flex; flex-direction: column; gap: 2px; } + nav button { display: flex; align-items: center; gap: var(--rs-settings-gap); width: 100%; min-height: var(--rs-settings-control-height); padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; } nav button:hover { background: var(--rs-bg-active); } nav button.active { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); } .scope { margin: auto 10px 0; padding-top: 24px; color: var(--rs-text-dim); font-size: 12px; } - .content { padding: 30px 32px; flex: 1; min-width: 0; overflow-y: auto; } - h2 { margin: 0; font-size: 23px; font-weight: 600; color: var(--rs-text-strong); } - h3 { margin: 28px 0 12px; font-size: 14px; font-weight: 600; } - p { color: var(--rs-text-dim); line-height: 1.6; } - .intro { margin: 7px 0 24px; } - .card { padding: 0 20px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: 10px; } - .setting-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 22px 0; } + .content { padding: 20px 24px; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; } + h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); } + h3 { margin: var(--rs-settings-section-gap) 0 8px; font-size: 13px; font-weight: 600; } + p { color: var(--rs-text-dim); line-height: 1.45; } + .intro { margin: 6px 0 var(--rs-settings-section-gap); } + .card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); } + .setting-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: var(--rs-settings-row-padding) 0; } + .setting-row > div:first-child { min-width: 0; } .setting-row + .setting-row { border-top: 1px solid var(--rs-border); } .setting-row label { font-weight: 500; } - .setting-row p { margin: 5px 0 0; font-size: 12px; } + .setting-row p { margin: 3px 0 0; font-size: var(--rs-settings-description-size); } .switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; } .switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; } .switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); } .switch:checked::before { transform: translateX(16px); background: var(--rs-bg); } .interval { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; font-size: 11px; color: var(--rs-text-dim); } - .interval input { width: 84px; padding: 9px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 14px; } + .interval input { width: 72px; min-height: var(--rs-settings-control-height); padding: 4px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 13px; } .interval input:disabled { opacity: .45; } .note, .section-footer, .about-note { font-size: 12px; } - .note { margin: 16px 0 24px; } + .note { margin: 10px 0 var(--rs-settings-section-gap); } .section-footer { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; color: var(--rs-text-dim); } - .text-button { border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); padding: 8px 12px; color: var(--rs-text); } + .text-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); padding: 4px 8px; color: var(--rs-text); } .text-button:hover { background: var(--rs-bg-active); } .saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; } .error { color: var(--rs-error); } @@ -193,11 +208,11 @@ .about-note { text-align: center; margin: 20px 0 0; } @media (max-width: 660px) { .body { flex-direction: column; } - aside { width: 100%; padding: 12px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; } - nav { flex-direction: row; margin-top: 10px; } - nav button { width: auto; flex: 1; padding: 8px; gap: 6px; } + aside { width: 100%; max-height: 40%; padding: 8px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; } + nav { flex-direction: row; flex-wrap: wrap; margin-top: 6px; } + nav button { width: auto; flex: 1 1 auto; padding: 5px 8px; gap: 6px; } .nav-heading, .scope { display: none; } - .content { padding: 24px 18px; } + .content { padding: 16px 12px; } .setting-row { gap: 14px; } } diff --git a/src/lib/layout/SettingsWindow.svelte b/src/lib/layout/SettingsWindow.svelte index dee360b..7516992 100644 --- a/src/lib/layout/SettingsWindow.svelte +++ b/src/lib/layout/SettingsWindow.svelte @@ -3,6 +3,7 @@ import { isTauri } from "@tauri-apps/api/core"; import { getCurrentWindow } from "@tauri-apps/api/window"; import SettingsDialog from "./SettingsDialog.svelte"; + import WindowControls from "$lib/ui/WindowControls.svelte"; import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; let settings = $state({ ...DEFAULT_SETTINGS }); @@ -32,4 +33,5 @@ } - void close()} /> +{#snippet controls()} error = message} />{/snippet} + void close()} /> diff --git a/src/lib/layout/TabBar.svelte b/src/lib/layout/TabBar.svelte index 5acad64..c480e63 100644 --- a/src/lib/layout/TabBar.svelte +++ b/src/lib/layout/TabBar.svelte @@ -18,9 +18,10 @@ tabActions?: (tab: WorkbenchTab) => ActionMenuItem[]; tabDragData?: (tab: WorkbenchTab) => string | undefined; onDropTab?: (data: string, index: number) => void; + onDetach?: (tab: WorkbenchTab) => void; }; - let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab }: Props = $props(); + let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props(); const transferType = "application/x-runestone-tab"; let bar: HTMLDivElement; let dragged = $state(null); @@ -168,6 +169,8 @@ cancelDrag(); closeMenu(); suppressClick = false; + const pointerTarget = event.currentTarget as HTMLElement; + pointerTarget.setPointerCapture(event.pointerId); const startX = event.clientX, startY = event.clientY, pointerId = event.pointerId; let x = startX, y = startY, started = false, destination: number | null = null, frame = 0; const update = () => { @@ -192,6 +195,7 @@ frame = requestAnimationFrame(scroll); }; const clean = () => { + if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId); cancelAnimationFrame(frame); dragged = dropBefore = dropAfter = null; window.removeEventListener("pointermove", onMovePointer); @@ -216,6 +220,10 @@ const target = destination; clean(); if (started && target !== null) void move(path, target); + else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) { + const tab = tabs.find(tab => tab.relPath === path); + if (tab) onDetach?.(tab); + } }; const onEscape = (e: KeyboardEvent) => { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); clean(); } @@ -267,7 +275,11 @@ onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }} draggable={!!tab.draggable} ondragstart={(event) => startTabTransfer(event, tab)} - ondragend={finishTabTransfer} + ondragend={(event) => { + const outside = event.clientX < 0 || event.clientY < 0 || event.clientX > window.innerWidth || event.clientY > window.innerHeight; + if (dragged && event.dataTransfer?.dropEffect === "none" && outside) onDetach?.(tab); + finishTabTransfer(); + }} onkeydown={(event) => onKey(event, tab.relPath)} oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }} onmousedown={onMiddleDown} @@ -300,7 +312,7 @@ min-height: 32px; overflow-x: auto; background: var(--rs-bg-elevated); - border-bottom: 1px solid var(--rs-border); + box-shadow: inset 0 -1px var(--rs-border); } .tabs:empty { min-width: 80px; } .tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); } @@ -311,17 +323,19 @@ align-items: center; max-width: 220px; flex-shrink: 0; - border-radius: var(--rs-item-selection-radius); + border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0; border-right: 1px solid var(--rs-border); - background: var(--rs-bg); + background: transparent; + border-bottom: 1px solid var(--rs-border); } .tab.active { - background: var(--rs-item-selection-bg); - box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); + background: var(--rs-bg); + border-bottom-color: transparent; } - .tab:hover { background: var(--rs-bg-active); } + .tab:focus-within { box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); } + .tab:not(.active):hover { background: var(--rs-bg-active); } .tab.dragging { opacity: 0.5; } .tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; } .tab.drop-before::before, .tab.drop-after::after { diff --git a/src/lib/layout/TreeNode.svelte b/src/lib/layout/TreeNode.svelte index 3d0be3c..754492d 100644 --- a/src/lib/layout/TreeNode.svelte +++ b/src/lib/layout/TreeNode.svelte @@ -133,6 +133,7 @@ {#if isRenaming} event.stopPropagation()} @@ -155,7 +156,7 @@ {:else} {label} {/if} - {#if ext} + {#if ext && !isRenaming} {ext} {/if}
@@ -220,7 +221,7 @@ } .row.active { - background: var(--rs-bg-active); + background: var(--rs-item-selection-bg); color: var(--rs-text-strong); } @@ -236,12 +237,15 @@ position: absolute; inset: 0; pointer-events: none; + visibility: hidden; border: var(--rs-item-selection-width) solid var(--rs-item-selection-border); border-top: 0; border-bottom: 0; border-radius: inherit; } + :global(.tree:focus-within) .selection-outline { visibility: visible; } + .selection-outline.full-top { border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border); } .selection-outline.full-bottom { border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border); } diff --git a/src/lib/layout/Workbench.svelte b/src/lib/layout/Workbench.svelte index 309d2bd..b6ecf35 100644 --- a/src/lib/layout/Workbench.svelte +++ b/src/lib/layout/Workbench.svelte @@ -3,10 +3,10 @@ import PluginTools from "$lib/plugins/PluginTools.svelte"; import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte"; import PluginEditor from "$lib/plugins/PluginEditor.svelte"; - import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external"; + import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external"; import { containsPane, paneBounds } from "$lib/workspace/splitLayout"; - import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external"; - import { onMount, tick } from "svelte"; + import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external"; + import { onMount, tick, untrack } from "svelte"; import { selectedEditorText } from "$lib/editor/selection"; import { pluginHost } from "$lib/plugins/registry"; import type { Contributions } from "$lib/plugins/contracts"; @@ -17,7 +17,8 @@ import { Documents } from "$lib/workspace/documents"; import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions"; import { orderWorkbenchTabs, type WorkbenchTab } from "$lib/workspace/workbenchTabs"; - import type { ActionMenuItem } from "$lib/ui/actionMenu"; + import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu"; + import { createNote, noteTemplates, saveNoteTemplate, type NoteTemplate } from "$lib/workspace/templates"; import { requestText } from "$lib/workspace/dialogs.svelte"; import TextDialog from "./TextDialog.svelte"; import QuickOpen from "./QuickOpen.svelte"; @@ -25,6 +26,7 @@ import SettingsDialog from "./SettingsDialog.svelte"; import BrowserSlot from "$lib/plugins/BrowserSlot.svelte"; import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings"; + import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout"; import FileTree from "./FileTree.svelte"; import EditorPane from "./EditorPane.svelte"; import TabBar from "./TabBar.svelte"; @@ -79,13 +81,15 @@ let error = $state(null); let refreshToken = $state(0); let view = $state("Writing"); - let leftWidth = $state(260); - let rightWidth = $state(240); + let layoutReady = $state(false); + let leftWidth = $state(DEFAULT_WORKBENCH_LAYOUT.leftWidth); + let rightWidth = $state(DEFAULT_WORKBENCH_LAYOUT.rightWidth); let bottomHeight = $state(180); - let leftView = $state<"files" | "search" | "bookmarks">("files"); + let leftView = $state(DEFAULT_WORKBENCH_LAYOUT.leftView); let searchRequest = $state<{ text: string; id: number } | null>(null); - let leftOpen = $state(true); - let rightOpen = $state(true); + let leftOpen = $state(DEFAULT_WORKBENCH_LAYOUT.leftOpen); + let rightOpen = $state(DEFAULT_WORKBENCH_LAYOUT.rightOpen); + $effect(() => { if ($pluginSidebar) leftOpen = true; }); let terminalOpen = $state(false); let reading = $state(false); let quickOpen = $state(false); @@ -94,6 +98,8 @@ let terminalDock: TerminalSlot | undefined = $state(); const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); const terminalEnabled = $derived(!!terminalContribution); + const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar" && !item.toolbar)); + const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar)); const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); }); let browserOpening = $state(false); async function openBrowser() { @@ -125,6 +131,7 @@ let saving = $state(false); let switching = false; + let workbenchReady = $state(false); let documents: Documents | null = null; let editorPane: EditorPane | undefined = $state(); let closingTabs = false; @@ -165,6 +172,13 @@ })), ]); const workingTabs = $derived(orderWorkbenchTabs(availableTabs, tabOrder)); + $effect(() => { + if (workbenchReady && !availableTabs.length) untrack(() => { + const previousError = error; + newTab(); + error = previousError; + }); + }); function workingTabDragData(tab: WorkbenchTab) { const view = $pluginEditors.find(view => view.key === tab.id); return view ? pluginTabDragData(view) : undefined; @@ -241,7 +255,9 @@ } function selectLeft(next: "files" | "search" | "bookmarks") { - if (leftOpen && leftView === next) { + const hadSidebar = !!$pluginSidebar; + closePluginSidebar(); + if (!hadSidebar && leftOpen && leftView === next) { leftOpen = false; return; } @@ -270,9 +286,31 @@ documents = createDocuments(); status = workspace.root; refreshToken += 1; + const token = new URLSearchParams(location.search).get("tabTransfer"); + if (token && /^[0-9a-f-]{36}$/i.test(token)) { + const key = `runestone.tab-transfer.${token}`; + const raw = localStorage.getItem(key); + if (raw) { + const transfer = JSON.parse(raw); + if (transfer.root === workspace.root && transfer.created > Date.now() - 120000 + && (transfer.buffer || transfer.plugin)) { + if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") documents.importTab(transfer.buffer); + else if (transfer.plugin) { + const deadline = Date.now() + 15000; + while (!await restorePluginTab(transfer.plugin)) { + if (Date.now() > deadline) throw new Error("Enable the plugin before moving this tab."); + await new Promise(resolve => setTimeout(resolve, 100)); + } + } else throw new Error("Invalid tab transfer."); + reading = transfer.reading === true; + localStorage.setItem(key + ".accepted", "true"); + localStorage.removeItem(key); + } + } + } } } catch (err) { error = String(err); } - finally { switching = false; } + finally { switching = false; workbenchReady = true; } } function selectTab(relPath: string) { @@ -307,7 +345,40 @@ } function workingTabActions(item: WorkbenchTab): ActionMenuItem[] { const tab = workingTabs.find(tab => tab.id === item.id); - return tab && "plugin" in tab ? pluginTabActions(tab.plugin) : []; + const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : []; + if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions; + return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : []; + } + async function detachTab(item: WorkbenchTab) { + const tab = workingTabs.find(tab => tab.id === item.id); + if (!tab || !workspace || !desktop) return; + if ("plugin" in tab) { + const action = pluginTabActions(tab.plugin).find(action => "label" in action && /(?:move|open).*new window/i.test(action.label)); + if (action && "run" in action && !action.disabled) { action.run?.(); return; } + } + const current = documents; + const snapshot = JSON.stringify("buffer" in tab ? tab.buffer : pluginTabState(tab.plugin)); + const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`; + let timer: ReturnType; + const finish = () => { + window.removeEventListener("storage", accepted); + clearTimeout(timer); + localStorage.removeItem(key); + localStorage.removeItem(key + ".accepted"); + }; + const accepted = (event: StorageEvent) => { + if (event.key !== key + ".accepted" || event.newValue !== "true") return; + if ("buffer" in tab) { + if (documents === current && JSON.stringify(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath); + } else if (JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key); + finish(); + }; + try { + localStorage.setItem(key, JSON.stringify({ root: workspace.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading })); + window.addEventListener("storage", accepted); + timer = setTimeout(() => { finish(); error = "The new window did not accept the tab. The source tab remains open."; }, 30000); + await workspaceOpenWindow(workspace.root, token); + } catch (reason) { finish(); error = String(reason); } } function pinWorkingTab(path: string) { const tab = workingTabs.find(tab => tab.relPath === path); @@ -372,6 +443,7 @@ const items: ActionMenuItem[] = []; if (tab.kind === "text" && isMarkdownPath(tab.relPath)) { items.push( + { label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } }, { label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() }, { label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome }, ); @@ -544,8 +616,47 @@ } } + async function saveTemplate(entry: TreeEntry) { + const name = await requestText("Template name", entry.name.replace(/\.md$/i, "")); + if (!name) return; + try { + const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path); + await saveNoteTemplate(name, contents); + status = `Saved template: ${name}`; + } catch (reason) { error = String(reason); } + } + + async function newNote(event?: MouseEvent) { + if (!workspace) return; + const create = async (template?: NoteTemplate) => { + try { + const path = await createNote("", template); + refreshToken++; + await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" }); + } catch (reason) { error = String(reason); } + }; + const templates = await noteTemplates(); + if (!templates.length || !event) { await create(); return; } + const anchor = event.currentTarget instanceof HTMLElement ? event.currentTarget : document.activeElement as HTMLElement; + const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); }; + const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); }; + const menu = actionMenu(event.clientX, event.clientY, [ + { label: "Blank note", icon: "file-plus", run: () => { close(); void create(); } }, + ...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })), + ], close, "New note"); + window.addEventListener("pointerdown", outside); + } + function onPreferencesKeydown(event: KeyboardEvent) { if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return; + if (event.ctrlKey && !event.altKey && !event.metaKey && event.key === "Tab" && workingTabs.length) { + event.preventDefault(); event.stopPropagation(); + const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath); + const next = (index + (event.shiftKey ? -1 : 1) + workingTabs.length) % workingTabs.length; + selectWorkingTab(workingTabs[next].relPath); + return; + } + if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") { event.preventDefault(); event.stopPropagation(); void openSettings(); } @@ -699,7 +810,7 @@ const shell = event.currentTarget as HTMLElement; const rect = shell.getBoundingClientRect(); if (dragging === "left") { - leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - ($pluginNavigation.length ? 44 : 0))); + leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - (ribbonNavigation.length ? 44 : 0))); } if (dragging === "right") { rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX)); @@ -715,6 +826,20 @@ settings = { ...next }; } + onMount(() => { + try { + const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY)); + ({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout); + layoutReady = true; + } catch { error = "Could not read your layout. Default layout applies for this window."; } + }); + + $effect(() => { + if (!layoutReady) return; + try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); } + catch { error = "Could not save your layout. Layout changes apply for this window only."; } + }); + onMount(() => { try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); } catch { error = "Could not read your settings. Default settings apply until you save new settings."; } @@ -741,6 +866,9 @@ void restoreLast(); let disposed = false; const unlisteners: (() => void)[] = []; + unlisteners.push(handlePluginFileOpen(async path => { + await openFile({ name: path.split("/").pop() ?? path, rel_path: path, kind: "file" }); + })); unlisteners.push(handlePluginDocumentRename(async (from, name) => { const current = documents; if (!current || switching) throw new Error("Open a workspace before renaming a document."); @@ -801,7 +929,7 @@
0} + class:has-ribbon={ribbonNavigation.length > 0} class:left-open={leftOpen} class:right-open={rightOpen} role="application" @@ -818,34 +946,48 @@ selectLeft("files")} /> selectLeft("search")} /> selectLeft("bookmarks")} /> + {#each sidebarNavigation as item (`${item.owner}:${item.id}`)} + openPluginView(item.owner, item.id)} + /> + {/each}
void closeTabs(path, scope)} onPin={pinWorkingTab} fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab} + onDetach={(tab) => { void detachTab(tab); }} tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} /> - + {#if desktop}
{/if}
+ {#each $pluginNavigation.filter(item => item.toolbar) as item (item.owner + ":" + item.id)} + openPluginView(item.owner, item.id)} /> + {/each} - + void save()} /> {#if terminalEnabled}{/if}
-