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

Autocomplete integration test

diff --git a/output/plugin-access-card.png b/output/plugin-access-card.png new file mode 100644 index 0000000..4ab2608 Binary files /dev/null and b/output/plugin-access-card.png differ diff --git a/output/tab-site-icon-dark.png b/output/tab-site-icon-dark.png new file mode 100644 index 0000000..5c853d5 Binary files /dev/null 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 new file mode 100644 index 0000000..4d37b50 Binary files /dev/null and b/output/tab-site-icon-light.png differ diff --git a/package.json b/package.json index a443400..2968428 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "runestone", - "version": "0.1.7", + "version": "0.1.10", "description": "Desktop editor for a local workspace", "type": "module", "scripts": { diff --git a/scripts/browserPlugin.spec.ts b/scripts/browserPlugin.spec.ts new file mode 100644 index 0000000..836d3cc --- /dev/null +++ b/scripts/browserPlugin.spec.ts @@ -0,0 +1,44 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { ContributionRegistry } from "../src/lib/plugins/registry.ts"; +import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; +import type { PluginApi } from "../src/lib/plugins/sdk.ts"; + +test("browser contributions and view updates are revoked when the plugin stops", async () => { + const registry = new ContributionRegistry(); + let api!: PluginApi; + let disposed = false; + const received: string[] = []; + const session = new ExternalSession("runestone.browser", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() }, + }, () => {}, () => {}, registry); + await session.start({ activate(value) { + api = value; + api.registerView({ id: "tab-test", title: "Browser", placement: "editor", icon: "globe", mount: () => {} }); + api.registerTabDrop!(data => { received.push(data); }); + api.contribute("browser", { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => true }); + api.onDispose(() => { disposed = true; }); + } }); + assert.ok(registry.get("browser")); + await session.dropTab("live-tab"); + assert.deepEqual(received, ["live-tab"]); + api.updateViewTitle!("tab-test", "Example · User"); + assert.equal(session.views.get("tab-test")?.title, "Example · User"); + const icon = "data:image/png;base64,aW1hZ2U="; + api.updateViewIcon!("tab-test", icon); + assert.equal(session.views.get("tab-test")?.iconImage, icon); + assert.throws(() => api.updateViewIcon!("tab-test", "https://example.com/icon.png"), /Invalid/); + assert.throws(() => api.updateViewIcon!("tab-test", "data:text/html;base64,aW1hZ2U="), /Invalid/); + assert.throws(() => api.updateViewIcon!("tab-test", "data:image/png;base64," + "a".repeat(90_000)), /Invalid/); + api.updateViewIcon!("tab-test", null); + assert.equal(session.views.get("tab-test")?.iconImage, null); + await session.stop(); + assert.equal(registry.get("browser"), undefined); + assert.equal(disposed, true); + assert.throws(() => api.updateViewTitle!("tab-test", "Other"), /disabled/); + assert.throws(() => api.updateViewIcon!("tab-test", icon), /disabled/); + await assert.rejects(session.dropTab("closed-tab"), /disabled/); + assert.throws(() => api.registerTabDrop!(() => {}), /disabled/); + assert.deepEqual(received, ["live-tab"]); +}); diff --git a/scripts/completion.spec.ts b/scripts/completion.spec.ts new file mode 100644 index 0000000..762c400 --- /dev/null +++ b/scripts/completion.spec.ts @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { CompletionHub, eligible } from '../src/lib/completion/hub.ts'; +import type { CompletionSnapshot } from '../src/lib/completion/contracts.ts'; +const snapshot = (): CompletionSnapshot => ({ documentId: 'doc', revision: 1, text: 'The ', caret: 4, selectionEnd: 4, focused: true, kind: 'prose' }); +const tick = () => new Promise(resolve => setTimeout(resolve, 0)); +test('sensitive fields, composition, selections, code blocks and link targets are excluded', () => { + assert(eligible(snapshot())); + for (const change of [{ sensitive: true }, { composing: true }, { readOnly: true }, { selectionEnd: 0 }, { focused: false }]) assert(!eligible({ ...snapshot(), ...change })); + for (const text of ['```js\nlet ', '[name](http', '| cell ', '`source', '---\nname: ']) assert(!eligible({ ...snapshot(), text, caret: text.length, selectionEnd: text.length })); + assert(eligible({ ...snapshot(), kind: 'code', text: 'let ', caret: 4 })); +}); +test('a new revision blocks stale insertion even when the provider ignores cancellation', async () => { + const hub = new CompletionHub(); let state = snapshot(), emit!: (text: string) => void, finish!: (text: string) => void, visible = '', edits = 0; + hub.registerProvider({ id: 'model', complete: (_request, publish) => { emit = publish; return new Promise(resolve => finish = resolve); } }); + const field = hub.registerSurface({ id: 'field', snapshot: () => state, preview: text => visible = text || '', insert: () => { edits++; return true; } }); + field.request(); emit('harbor'); assert.equal(visible, 'harbor'); + state = { ...state, revision: 2, text: 'The old ', caret: 8, selectionEnd: 8 }; + assert.equal(field.accept(), false); finish('late'); await tick(); assert.equal(visible, ''); assert.equal(edits, 0); field.dispose(); +}); +test('acceptance is explicit and provider removal clears all surfaces', async () => { + const hub = new CompletionHub(); let visible = '', inserted = ''; + const remove = hub.registerProvider({ id: 'model', complete: async () => 'quiet harbor' }); + const field = hub.registerSurface({ id: 'field', snapshot, preview: text => visible = text || '', insert: text => { inserted = text; return true; } }); + field.request(); await tick(); assert.equal(inserted, ''); assert.equal(visible, 'quiet harbor'); + assert(field.accept(true)); assert.equal(inserted, 'quiet '); assert.equal(visible, ''); + field.request(); await tick(); remove(); assert.equal(visible, ''); assert.equal(field.accept(), false); field.dispose(); +}); +test('moving between fields cancels the previous request', async () => { + const hub = new CompletionHub(); const signals: AbortSignal[] = []; + hub.registerProvider({ id: 'model', complete: request => { signals.push(request.signal); return new Promise(() => {}); } }); + const a = hub.registerSurface({ id: 'a', snapshot, preview() {}, insert: () => true }); + const b = hub.registerSurface({ id: 'b', snapshot, preview() {}, insert: () => true }); + a.request(); b.request(); assert(signals[0].aborted); assert(!signals[1].aborted); a.dispose(); b.dispose(); +}); diff --git a/scripts/externalPlugins.spec.ts b/scripts/externalPlugins.spec.ts index cedc078..4cda00f 100644 --- a/scripts/externalPlugins.spec.ts +++ b/scripts/externalPlugins.spec.ts @@ -11,6 +11,24 @@ function fixture() { }, () => {}, () => {}); return { session, writes: () => writes }; } + +test("native Markdown discovery remains optional and is revoked on disable", async () => { + let api!: PluginApi; + let scans = 0; + const session = new ExternalSession("org.test.scan", { + workspace: { list: async () => [], listMarkdown: async () => { scans++; return ["Notes/task.md"]; }, read: async () => "", write: async () => {} }, + settings: { read: async () => null, write: async () => {} }, + assets: { read: async () => new Uint8Array() }, + }, () => {}, () => {}); + await session.start({ activate(value) { api = value; } }); + assert.deepEqual(await api.workspace.listMarkdown!(), ["Notes/task.md"]); + await session.stop(); + assert.throws(() => api.workspace.listMarkdown!(), /disabled/); + assert.equal(scans, 1); + const old = fixture().session; + await old.start({ activate(value) { assert.equal(value.workspace.listMarkdown, undefined); } }); + await old.stop(); +}); test("external commands run and all host access stops before cleanup", async () => { const { session, writes } = fixture(); let api!: PluginApi; let ran = 0; await session.start({ activate(value) { diff --git a/scripts/markdownPaste.smoke.mjs b/scripts/markdownPaste.smoke.mjs new file mode 100644 index 0000000..df55ab1 --- /dev/null +++ b/scripts/markdownPaste.smoke.mjs @@ -0,0 +1,112 @@ +// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); +page.setDefaultTimeout(10000); +const errors = []; +await mkdir(".audit", { recursive: true }); +page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); }); +page.on("pageerror", error => errors.push(error.message)); +await page.addInitScript(() => { + window.isTauri = true; + const root = "C:\\smoke-workspace"; + const files = new Map([ + ["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"], + ["notes/second.md", "# Second note\n"], + ["src/hello.py", "print('hello')\n"], + ]); + const callbacks = new Map(); + const listeners = new Map(); + let sequence = 0; + const calls = []; + const emit = (event, payload) => { + for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); + }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + calls.push({ command, args }); + if (command === "plugin:event|listen") { + const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; + } + if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } + if (command === "workspace_last_path") return root; + if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } + if (command === "workspace_write") { + if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk"); + files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return; + } + if (command === "workspace_list") { + const prefix = args.rel ? args.rel + "/" : ""; + const entries = new Map(); + for (const path of files.keys()) { + if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue; + const tail = path.slice(prefix.length); const name = tail.split("/")[0]; + entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" }); + } + return [...entries.values()]; + } + if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; } + if (command === "workspace_search") return []; + if (command === "pty_open") { + const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")]; + emit("pty-data", { id: args.id, data: data.slice(0, 8) }); + emit("pty-data", { id: args.id, data: data.slice(8) }); + await new Promise(resolve => setTimeout(resolve, 50)); + return; + } + if (command.startsWith("pty_")) return; + if (command === "plugin:dialog|message") return "Cancel"; + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + window.__TEST__ = { files, calls, emit, root }; +}); + +try { + await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420"); + await page.getByText("smoke-workspace", { exact: true }).waitFor(); + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md"); + await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click(); + await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor(); + await page.evaluate(async () => { + const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js"); + window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content")); + }); + for (const count of [3, 1000, 5000]) { + const result = await page.evaluate(async count => { + const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js"); + const view = window.__CM__; + const source = Array.from({ length: count }, (_, i) => "## Heading " + i + "\n\n**Bold** and *italic*\n\n").join(""); + view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } }); + view.focus(); + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", source); + view.contentDOM.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData })); + view.dispatch({ selection: { anchor: 0 } }); + const { forceParsing, syntaxTree } = await import("/node_modules/.vite/deps/@codemirror_language.js"); + forceParsing(view, view.state.doc.length, 5000); + const nodes = []; + syntaxTree(view.state).iterate({ enter(node) { if (node.name === "StrongEmphasis") nodes.push(node.from); } }); + const marks = []; + for (const set of view.state.facet(EditorView.decorations)) { + if (typeof set !== "function") set.between(0, view.state.doc.length, (from, to, decoration) => { if (decoration.spec.class === "writer-strong") marks.push(from); }); + } + return { correctSource: view.state.sliceDoc() === source, nodes: nodes.length, marks: marks.length }; + }, count); + console.log({ count, ...result }); + assert.equal(result.correctSource, true); + assert.equal(result.nodes, count); + assert.equal(result.marks, count); + } + assert.deepEqual(errors, []); +} finally { await browser.close(); } diff --git a/scripts/menuConsistency.smoke.mjs b/scripts/menuConsistency.smoke.mjs index 3b90c7a..23f1827 100644 --- a/scripts/menuConsistency.smoke.mjs +++ b/scripts/menuConsistency.smoke.mjs @@ -81,7 +81,15 @@ try { await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } }); await file.waitFor(); assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles"); - await dismiss(); + assert.equal(await item("Show in Explorer").locator("svg.action-icon").count(), 1); + await page.keyboard.press("End"); + assert.equal(await item("Show in Explorer").evaluate(node => node === document.activeElement), true); + await page.keyboard.press("Enter"); + await file.waitFor({ state: "detached" }); + assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "", "Pane action opens the workspace root"); + await row.click({ button: "right" }); + await item("Show in Explorer").click(); + assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "a.md", "File action reveals the selected file"); await page.locator('[data-tree-rel="notes"]').click({ button: "right" }); assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles"); await dismiss(); diff --git a/scripts/pluginAccess.smoke.mjs b/scripts/pluginAccess.smoke.mjs new file mode 100644 index 0000000..739137f --- /dev/null +++ b/scripts/pluginAccess.smoke.mjs @@ -0,0 +1,117 @@ +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420"; +const context = await browser.newContext({ viewport: { width: 1440, height: 900 } }); +const errors = []; +await mkdir(".audit", { recursive: true }); +await context.addInitScript(() => { + window.isTauri = true; + const callbacks = new Map(), listeners = new Map(); + let sequence = 0; + const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); }; + const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" }); + const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("runestone.browser", "Browser"), manifest("org.example.tasks", "Tasks")]; + const modules = { + "runestone.local-autocomplete": `export function activate(api) { + window.accessTest = { mounts: 0, disposed: 0, settings: 0 }; + api.settings.subscribe?.(() => { window.accessTest.settings++; }); + api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) { + window.accessTest.mounts++; + container.innerHTML = '

Local Autocomplete

'; + container.querySelector('p').textContent = context?.surface; + container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value }); + return () => { window.accessTest.disposed++; }; + }}); + api.registerCommand({ id: 'configure', title: 'Configure local autocomplete', run: () => api.openView('settings') }); + api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } }); + }`, + "runestone.browser": `export function activate(api) { + api.registerCommand({ id: 'new-tab', title: 'New browser tab', run() { + const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id); + }}); + }`, + "org.example.tasks": `export function activate(api) { + api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', mount(container) { container.textContent = 'Task content'; } }); + api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } }); + }`, + }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; } + if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; } + if (command === 'workspace_last_path') return null; + if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) }; + if (command === 'plugins_load') return modules[args.id]; + if (command === 'plugins_data') { + if (args.value !== null) { localStorage.setItem('settings:' + args.id, args.value); emit('plugin-settings-changed', args.id); } + return localStorage.getItem('settings:' + args.id) || 'null'; + } + if (command === 'plugins_set_enabled') { if (!args.enabled) localStorage.setItem('disabled', 'true'); emit('plugins-changed', {}); return; } + if (command === 'plugins_release' || command === 'settings_open_window') return; + if (command.startsWith('plugin:window|')) return false; + throw new Error('Unhandled IPC: ' + command); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + window.addEventListener('storage', event => { if (event.key?.startsWith('settings:')) emit('plugin-settings-changed', event.key.slice(9)); if (event.key === 'disabled') emit('plugins-changed', {}); }); +}); +const main = await context.newPage(), settings = await context.newPage(); +for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); } +try { + await main.goto(origin); + const open = main.getByRole('button', { name: 'Open tab or view', exact: true }); + await open.click(); + const menu = main.getByRole('menu', { name: 'Open tab or view', exact: true }); + await menu.waitFor(); + assert.equal(await menu.getByRole('menuitem').count(), 3); + assert.equal(await menu.getByText('Local Autocomplete').count(), 0); + await open.click(); await menu.waitFor({ state: 'detached' }); + await open.focus(); await main.keyboard.press('Enter'); await main.keyboard.press('End'); await main.keyboard.press('Escape'); + assert(await open.evaluate(element => element === document.activeElement)); + await open.click(); await menu.getByRole('menuitem', { name: /New browser tab/ }).click(); + await main.getByText('Browser content', { exact: true }).waitFor(); + await open.click(); assert.equal(await menu.getByRole('menuitem').count(), 3); + await menu.getByRole('menuitem', { name: /Task summary/ }).click(); + await main.getByRole('dialog', { name: 'Task summary' }).waitFor(); + await main.keyboard.press('Escape'); + await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu.png' }); await main.keyboard.press('Escape'); + await main.evaluate(() => document.documentElement.dataset.theme = 'light'); + await open.click(); await main.screenshot({ path: '.audit/plugin-access-menu-light.png' }); await main.keyboard.press('Escape'); + await main.evaluate(() => document.documentElement.dataset.theme = 'dark'); + await main.getByRole('button', { name: 'Commands', exact: true }).click(); + await main.getByRole('menuitem', { name: /Failed command/ }).click(); + await main.getByRole('alert').filter({ hasText: 'Command failed for test' }).waitFor(); + await main.getByRole('button', { name: 'Dismiss', exact: true }).click(); + await settings.goto(origin + '/?settingsWindow=true'); + await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click(); + await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model'); + assert.equal(await settings.locator('.mount-context').innerText(), 'settings'); + await settings.waitForTimeout(5500); + assert.equal(await settings.getByRole('textbox', { name: 'Model', exact: true }).inputValue(), 'unsaved-model'); + assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1); + await settings.getByRole('button', { name: 'Save model', exact: true }).click(); + await main.waitForFunction(() => window.accessTest.settings === 1); + await settings.screenshot({ path: '.audit/plugin-access-settings.png' }); + await settings.getByRole('button', { name: 'General', exact: true }).click(); + await settings.waitForFunction(() => window.accessTest.disposed === 1); + await settings.getByRole('textbox', { name: 'Search settings' }).fill('Local'); + await settings.getByRole('textbox', { name: 'Model', exact: true }).waitFor(); + await settings.getByRole('textbox', { name: 'Search settings' }).fill(''); + await settings.getByRole('button', { name: 'Plug-ins', exact: true }).click(); + await settings.getByRole('switch', { name: 'Local Autocomplete', exact: true }).uncheck(); + await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' }); + await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' }); + assert.deepEqual(errors, []); + console.log('Plugin access smoke passed: launchers, dynamic tabs, keyboard focus, dialog, settings search, stable forms, cross-window settings, disable cleanup.'); +} catch (error) { + await settings.screenshot({ path: '.audit/plugin-access-failure.png' }); + console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors); + throw error; +} finally { await browser.close(); } diff --git a/scripts/pluginAccess.spec.ts b/scripts/pluginAccess.spec.ts new file mode 100644 index 0000000..389efa4 --- /dev/null +++ b/scripts/pluginAccess.spec.ts @@ -0,0 +1,75 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { pluginAccess } from "../src/lib/plugins/access.ts"; +import { ExternalSession } from "../src/lib/plugins/externalSession.ts"; +import type { PluginApi, PluginCommand, PluginView } from "../src/lib/plugins/sdk.ts"; + +const view = (id: string, extra: Partial = {}): PluginView => ({ id, title: id, mount() {}, ...extra }); +const command = (id: string, extra: Partial = {}): PluginCommand => ({ id, title: id, run() {}, ...extra }); + +test("plugin access separates settings, launchers, and commands without reading titles", () => { + const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]); + assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]); +}); + +test("installed RuneStone packages retain access before their next package update", () => { + assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings"); + assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]); + assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open"); + assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open"); + assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands"); +}); + +test("settings listeners are removable and revoked before plugin cleanup", async () => { + let api!: PluginApi, notify!: () => void; + let received = 0, disposed = 0; + const session = new ExternalSession("org.example.settings", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + assets: { read: async () => new Uint8Array() }, + settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } }, + }, () => {}, () => {}); + await session.start({ activate(value) { api = value; } }); + const off = api.settings.subscribe!(() => { received++; }); + notify(); assert.equal(received, 1); + await off(); await off(); assert.equal(disposed, 1); + api.settings.subscribe!(() => { received++; }); + await session.stop(); notify(); + assert.equal(received, 1); assert.equal(disposed, 2); + assert.throws(() => api.settings.subscribe!(() => {}), /disabled/); +}); + +test("invalid access metadata fails registration", async () => { + for (const activate of [ + (api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })), + (api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })), + (api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })), + ]) { + const session = new ExternalSession("org.example.invalid", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} }, + }, () => {}, () => {}); + await assert.rejects(session.start({ activate }), /category|boolean/); + await session.stop(); + } +}); + +test("settings windows permit model checks and cancellation", () => { + const capability = JSON.parse(readFileSync(new URL("../src-tauri/capabilities/settings.json", import.meta.url), "utf8")); + for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission)); +}); + +test("view mount context distinguishes Settings from editor and dialog views", async () => { + const surfaces: string[] = []; + const session = new ExternalSession("org.example.context", { + workspace: { list: async () => [], read: async () => "", write: async () => {} }, + assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} }, + }, () => {}, () => {}); + await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } }); + const target = { replaceChildren() {} } as unknown as HTMLElement; + const disposeView = await session.mount("settings", target); + await disposeView(); + const disposeSettings = await session.mount("settings", target, undefined, "settings"); + await disposeSettings(); await session.stop(); + assert.deepEqual(surfaces, ["view", "settings"]); +}); diff --git a/scripts/pluginInstall.smoke.mjs b/scripts/pluginInstall.smoke.mjs index 865dfd7..0862e1c 100644 --- a/scripts/pluginInstall.smoke.mjs +++ b/scripts/pluginInstall.smoke.mjs @@ -7,10 +7,15 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' }); const page = await context.newPage(); +const settingsPage = await context.newPage(); +settingsPage.setDefaultTimeout(10000); +await context.exposeBinding("settingsHostInvoke", (_source, command, args) => + page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args })); page.setDefaultTimeout(10000); 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)); +settingsPage.on("pageerror", error => errors.push(error.message)); const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8')); const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n'; await page.context().addInitScript(({ manifest, pluginCode }) => { @@ -38,7 +43,10 @@ await page.context().addInitScript(({ manifest, pluginCode }) => { transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, unregisterCallback: id => callbacks.delete(id), invoke: async (command, args = {}) => { + if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|")) + return window.settingsHostInvoke(command, args); calls.push({ command, args }); + if (command === "settings_open_window") return; if (command === "plugin:window|is_maximized") return false; if (command.startsWith("plugin:window|")) return null; if (command === "plugins_snapshot") return snapshot(); @@ -117,10 +125,11 @@ async function quickOpen(name) { } -const settingsDialog = page.getByRole('dialog', { name: 'Settings', exact: true }); +const settingsDialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true }); const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); async function settings() { await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); + await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true'); await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); } async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); } @@ -131,13 +140,13 @@ try { assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0); assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0); await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click(); - let review = page.getByRole('dialog', { name: 'Review plugin installation', exact: true }); + let review = settingsPage.getByRole('dialog', { name: 'Review plugin installation', exact: true }); await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor(); await review.getByRole('button', { name: 'Cancel', exact: true }).click(); assert.equal(await count('plugins_install'), 0); const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true }); await gitButton.click(); - const gitDialog = page.getByRole('dialog', { name: 'Install from Git link', exact: true }); + const gitDialog = settingsPage.getByRole('dialog', { name: 'Install from Git link', exact: true }); await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git'); await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing'); await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token'); @@ -156,8 +165,8 @@ try { assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z'); assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/); - await page.screenshot({ path: '.audit/plugin-manager-installed.png' }); - await page.keyboard.press('Escape'); + 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(); const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true }); @@ -165,7 +174,7 @@ try { await view.getByRole('button', { name: 'Close plugin view', exact: true }).click(); await settings(); await uninstall(); - const confirmation = page.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true }); + const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true }); assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement)); assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0); await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click(); @@ -173,27 +182,27 @@ try { assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); await uninstall(); await confirmation.waitFor(); - await page.keyboard.press('Escape'); + await settingsPage.keyboard.press('Escape'); assert(await settingsDialog.isVisible()); assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked()); assert.equal(await count('plugins_remove'), 0); await uninstall(); await confirmation.waitFor(); - await page.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' }); + await settingsPage.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' }); await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor(); assert.equal(await count('plugins_remove'), 1); assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true); assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true); - await page.keyboard.press('Escape'); + await settingsPage.keyboard.press('Escape'); assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0); - await page.setViewportSize({ width: 590, height: 820 }); + await settingsPage.setViewportSize({ width: 590, height: 820 }); await settings(); - await page.screenshot({ path: '.audit/plugin-manager-narrow.png' }); + await settingsPage.screenshot({ path: '.audit/plugin-manager-narrow.png' }); assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false); await gitButton.click(); await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git'); - await page.screenshot({ path: '.audit/plugin-git-narrow.png' }); + await settingsPage.screenshot({ path: '.audit/plugin-git-narrow.png' }); assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false); await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click(); await review.getByRole('button', { name: 'Install', exact: true }).click(); diff --git a/scripts/pluginTabOrder.smoke.mjs b/scripts/pluginTabOrder.smoke.mjs new file mode 100644 index 0000000..b62dfe3 --- /dev/null +++ b/scripts/pluginTabOrder.smoke.mjs @@ -0,0 +1,255 @@ +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; + +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); +const page = await context.newPage(); +await context.exposeBinding("settingsHostInvoke", (_source, command, args) => + page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args })); +page.setDefaultTimeout(10000); +const errors = []; +page.on("pageerror", error => errors.push(error.message)); +const pluginCode = `export function activate(api) { + window.tabTest.api = api; + const mount = (id, container) => { + window.tabTest.mounts[id] = (window.tabTest.mounts[id] || 0) + 1; + const input = document.createElement("input"); + input.setAttribute("aria-label", id + " state"); + container.append(input); + return () => { + window.tabTest.disposals[id] = (window.tabTest.disposals[id] || 0) + 1; + input.remove(); + }; + }; + for (const [id, title, icon] of [["overview", "Overview", "puzzle"], ["browser", "Browser", "globe"]]) { + api.registerView({ id, title, icon, placement: "editor", navigation: true, mount: container => mount(id, container) }); + } + api.registerDocumentType({ + id: "board", title: "Board", icon: "kanban", extensions: ["board"], + identify: (path, source) => ({ id: source }), + mount: (container, document) => mount(document.id, container), + }); +}`; +await context.addInitScript(({ pluginCode }) => { + window.isTauri = true; + localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 })); + const root = "C:\\plugin-tab-workspace"; + const files = new Map(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`])); + files.set("project.board", "project-board"); + const callbacks = new Map(), listeners = new Map(); + let sequence = 0, enabled = true; + const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" }; + const emit = (event, payload) => { + for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); + }; + window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, files }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|")) + return window.settingsHostInvoke(command, args); + if (command === "settings_open_window") return; + if (command === "plugin:event|listen") { + const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; + } + if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; } + if (command === "plugin:window|is_maximized") return false; + if (command.startsWith("plugin:window|")) return; + if (command === "plugins_snapshot") return { root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] }; + if (command === "plugins_load") return pluginCode; + if (command === "plugins_data") return "null"; + if (command === "plugins_release") return; + if (command === "plugins_set_enabled") { enabled = args.enabled; emit("plugins-changed"); return; } + if (command === "workspace_last_path") return location.search.includes("no-workspace") ? null : root; + if (command === "workspace_open") return { root, name: "plugin-tab-workspace", watch_mode: "native" }; + if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); } + if (command === "workspace_write") { files.set(args.rel, args.contents); return; } + if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" })); + if (command === "workspace_search") return []; + if (command === "plugin:dialog|message") { window.tabTest.prompts++; return window.tabTest.answer; } + throw new Error(`Unhandled IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; +}, { pluginCode }); + +const tab = name => page.getByRole("tab", { name, exact: true }); +const bar = page.getByRole("tablist", { name: "Working tabs" }); +const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim())); +const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); +async function openFile(name) { + await page.keyboard.press("Control+p"); + await page.getByRole("textbox", { name: "Find a file" }).fill(name); + await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click(); + await settle(); +} +async function openView(name) { + await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click(); + await tab(name).waitFor(); +} +async function drag(from, to, side = "before", cancel) { + const source = await tab(from).boundingBox(), target = await tab(to).boundingBox(); + await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); + await page.mouse.down(); + await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 }); + if (cancel === "escape") await page.keyboard.press("Escape"); + if (cancel === "outside") await page.mouse.move(target.x, target.y + 100); + await page.mouse.up(); + await settle(); +} +async function menu(name) { + await tab(name).click({ button: "right" }); + await page.getByRole("menu", { name: "Tab actions" }).waitFor(); +} + +try { + const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; + await page.goto(url); + await page.getByText("plugin-tab-workspace", { exact: true }).waitFor(); + await openFile("a.md"); + await openFile("b.md"); + await openView("Overview"); + await page.getByRole("textbox", { name: "overview state" }).fill("Keep this state"); + await openView("Browser"); + const siteIcon = "data:image/svg+xml;base64," + Buffer.from('').toString('base64'); + await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon); + await tab("Browser").locator("img.tab-icon").waitFor(); + await page.waitForFunction(() => document.querySelector('.header img.tab-icon')?.naturalWidth === 16); + assert.equal(await tab("Browser").locator("img").getAttribute("alt"), ""); + assert.equal(await tab("Browser").locator("img").getAttribute("draggable"), "false"); + for (const theme of ["dark", "light"]) { + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + await mkdir("output", { recursive: true }); + await page.locator(".header").screenshot({ path: `output/tab-site-icon-${theme}.png` }); + } + await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", "data:image/png;base64,aW1hZ2U=")); + await tab("Browser").locator("img").waitFor({ state: "detached" }); + assert.equal(await tab("Browser").locator("svg").count(), 1); + await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon); + await tab("Browser").locator("img").waitFor(); + await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", null)); + await tab("Browser").locator("img").waitFor({ state: "detached" }); + assert.equal(await tab("Browser").locator("svg").count(), 1); + console.log("PASS: site icons appear in both themes and missing or broken icons use the fallback"); + await openFile("project.board"); + await tab("project").waitFor(); + assert.equal(await page.locator(".header").getByRole("tablist").count(), 1); + assert.deepEqual(await order(), ["a.md", "b.md", "Overview", "Browser", "project"]); + await drag("Overview", "a.md"); + await drag("project", "b.md"); + await drag("a.md", "Browser", "after"); + const mixed = ["Overview", "project", "b.md", "Browser", "a.md"]; + assert.deepEqual(await order(), mixed); + assert.equal(await tab("project").getAttribute("aria-selected"), "true"); + for (const cancel of ["escape", "outside"]) { + await drag("Browser", "Overview", "before", cancel); + assert.deepEqual(await order(), mixed); + } + await tab("Browser").press("Alt+Shift+Home"); + assert.equal((await order())[0], "Browser"); + await tab("Browser").press("ArrowRight"); + assert.equal(await tab("Overview").getAttribute("aria-selected"), "true"); + assert.equal(await page.getByRole("textbox", { name: "overview state" }).inputValue(), "Keep this state"); + await tab("Overview").press("ArrowRight"); + assert.equal(await tab("project").getAttribute("aria-selected"), "true"); + await page.evaluate(() => window.tabTest.api.updateViewTitle("browser", "Browser page")); + await tab("Browser page").waitFor(); + assert.equal((await order())[0], "Browser page"); + assert.deepEqual(await page.evaluate(() => window.tabTest.mounts), { overview: 1, browser: 1, "project-board": 1 }); + assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), {}); + assert.equal(await tab("project").getAttribute("aria-controls"), await page.getByRole("tabpanel", { name: "project" }).getAttribute("id")); + for (const theme of ["dark", "light"]) { + await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); + await menu("Browser page"); + assert.equal(await page.getByRole("menuitem", { name: "Pin", exact: true }).count(), 1); + await page.getByRole("menuitem", { name: "Move tab", exact: true }).click(); + await page.getByRole("menuitem", { name: "Move tab right", exact: true }).click(); + } + console.log("PASS: mixed file, feature, and plugin document tabs move without remounting or changing selection"); + + await tab("Browser page").press("Alt+Shift+End"); + await tab("project").press("Alt+Shift+End"); + await tab("a.md").press("Alt+Shift+Home"); + await tab("Overview").press("Alt+Shift+Home"); + await tab("b.md").press("Alt+Shift+Home"); + await menu("b.md"); + await page.getByRole("menuitem", { name: "Pin", exact: true }).click(); + await tab("a.md").click(); + await page.locator(".cm-content").fill("Unsaved text"); + await tab("a.md •").waitFor(); + assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]); + await menu("Overview"); + await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click(); + await page.waitForFunction(() => window.tabTest.prompts === 1); + assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]); + await page.evaluate(() => window.tabTest.answer = "Ok"); + await menu("Overview"); + await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click(); + await tab("project").waitFor({ state: "detached" }); + assert.deepEqual(await order(), ["b.md", "Overview"]); + assert.equal(await tab("Overview").getAttribute("aria-selected"), "true"); + await menu("Overview"); + await page.getByRole("menuitem", { name: "Close all", exact: true }).click(); + await tab("Overview").waitFor({ state: "detached" }); + assert.deepEqual(await order(), ["b.md"]); + assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), { browser: 1, "project-board": 1, overview: 1 }); + console.log("PASS: mixed close actions follow visual order, preserve pins, and respect cancelled discards"); + + await openView("Overview"); + for (let index = 0; index < 14; index++) await openFile(`note-${index}.md`); + await tab("Overview").press("Alt+Shift+Home"); + const source = await tab("Overview").boundingBox(), bounds = await bar.boundingBox(); + await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 }); + await page.waitForFunction(() => { + const bar = document.querySelector('[aria-label="Working tabs"]'); + return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2; + }); + await page.mouse.up(); + await settle(); + assert.equal((await order()).at(-1), "Overview"); + await page.keyboard.press("Control+t"); + await tab("New tab").press("Alt+Shift+Home"); + await openFile("c.md"); + assert.equal((await order())[0], "c.md"); + const fileOrder = (await order()).filter(name => name !== "Overview"); + await page.keyboard.press("Control+,"); + const settingsPage = await context.newPage(); + settingsPage.on("pageerror", error => errors.push(error.message)); + await settingsPage.goto(url + '/?settingsWindow=true'); + await settingsPage.getByRole("button", { name: "Plug-ins", exact: true }).click(); + await settingsPage.getByRole("switch", { name: "Tab fixtures", exact: true }).click(); + await settingsPage.waitForFunction(() => document.getElementById("external-test.tabs")?.checked === false); + await tab("Overview").waitFor({ state: "detached" }); + assert.deepEqual(await order(), fileOrder); + console.log("PASS: plugin drag auto-scroll, empty-tab replacement, and plugin disable preserve the mixed order"); + await settingsPage.close(); + + await page.goto(`${url}?no-workspace`); + await openView("Overview"); + await openView("Browser"); + await drag("Browser", "Overview"); + assert.deepEqual(await order(), ["Browser", "Overview"]); + await page.setViewportSize({ width: 880, height: 700 }); + await mkdir(".audit", { recursive: true }); + await page.screenshot({ path: ".audit/plugin-tab-order.png" }); + await tab("Browser").click({ button: "middle" }); + assert.deepEqual(await order(), ["Overview"]); + await page.getByRole("button", { name: "Close Overview", exact: true }).click(); + assert.equal(await page.getByRole("tab").count(), 0); + assert.deepEqual(errors, []); + console.log("PASS: plugin tabs reorder and close without an open workspace"); +} catch (error) { + await mkdir(".audit", { recursive: true }); + await page.screenshot({ path: ".audit/plugin-tab-order-failure.png" }); + console.error("Browser errors:", errors); + throw error; +} finally { + await browser.close(); +} diff --git a/scripts/plugins.smoke.mjs b/scripts/plugins.smoke.mjs index 377f195..f9677b3 100644 --- a/scripts/plugins.smoke.mjs +++ b/scripts/plugins.smoke.mjs @@ -6,11 +6,15 @@ const require = createRequire(import.meta.url); const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } }); +await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: 'Closed settings' })); const page = await context.newPage(); +const settingsPage = await context.newPage(); page.setDefaultTimeout(10000); +settingsPage.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)); +settingsPage.on("pageerror", error => errors.push(error.message)); await page.context().addInitScript(() => { window.isTauri = true; const root = "C:\\smoke-workspace"; @@ -32,6 +36,7 @@ await page.context().addInitScript(() => { unregisterCallback: id => callbacks.delete(id), invoke: async (command, args = {}) => { calls.push({ command, args }); + if (command === "settings_open_window") return; if (command === "plugin:event|listen") { const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler; } @@ -83,16 +88,17 @@ async function quickOpen(name) { const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n'; const table = page.locator('.live-writer table'); -const dialog = page.getByRole('dialog', { name: 'Settings', exact: true }); +const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true }); const switchFor = name => dialog.getByRole('switch', { name, exact: true }); async function settings() { await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click(); + await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true'); await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click(); } async function closeSettings() { - await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); - await page.keyboard.press('Escape'); - await dialog.waitFor({ state: 'hidden' }); + await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); + await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/__settings-closed'); + await page.bringToFront(); } const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command); try { @@ -137,7 +143,7 @@ try { await settings(); await switchFor('Terminal').uncheck(); await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close')); - await page.screenshot({ path: '.audit/plugins-settings.png' }); + await settingsPage.screenshot({ path: '.audit/plugins-settings.png' }); await closeSettings(); assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0); const opened = await count('pty_open'); @@ -169,9 +175,9 @@ try { await settings(); assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0); for (const name of ['Terminal', 'Table formulas']) { - await page.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); - await dialog.locator('.card').filter({ has: page.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click(); - const confirmation = page.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true }); + await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled)); + await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click(); + const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true }); await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click(); await confirmation.waitFor({ state: 'hidden' }); await switchFor(name).waitFor({ state: 'detached' }); @@ -187,6 +193,8 @@ try { assert.deepEqual(errors, []); console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.'); } catch (error) { + await settingsPage.screenshot({ path: ".audit/plugins-settings-failure.png" }); + console.log("Settings page:", settingsPage.url(), await settingsPage.locator('body').innerText()); await page.screenshot({ path: ".audit/plugins-failure.png" }); console.log(await page.locator('.md-page').allTextContents()); console.log(errors); diff --git a/scripts/settings.smoke.mjs b/scripts/settings.smoke.mjs index f5cb44e..beb659a 100644 --- a/scripts/settings.smoke.mjs +++ b/scripts/settings.smoke.mjs @@ -9,8 +9,10 @@ const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); const context = await browser.newContext({ viewport: { width: 1100, height: 800 } }); const page = await context.newPage(); +const settingsPage = await context.newPage(); const errors = []; page.on("pageerror", error => errors.push(error.message)); +settingsPage.on("pageerror", error => errors.push(error.message)); await context.addInitScript(() => { window.isTauri = true; const disk = { "note.txt": "Original note" }; @@ -32,8 +34,18 @@ await context.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; }); const url = process.env.SMOKE_URL || "http://127.0.0.1:1420"; -const settings = page.getByRole("dialog", { name: "Settings", exact: true }); +const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true }); const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }); +async function showSettings(shortcut = false) { + if (shortcut) await page.keyboard.press("Control+,"); + else await trigger.click(); + await settingsPage.goto(`${url}/?settingsWindow=true`); + await settings.waitFor(); +} +async function closeSettings() { + await settingsPage.goto("about:blank"); + await page.bringToFront(); +} const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" }); const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true }); async function changeSeconds(value) { @@ -51,15 +63,14 @@ try { await page.clock.install(); await page.goto(url); await page.locator(".ws").filter({ hasText: "Notes" }).waitFor(); - await trigger.click(); + await showSettings(); assert.equal(await interval.inputValue(), "5"); assert(await enabled.isChecked()); await changeSeconds(2); await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor(); - await page.keyboard.press("Escape"); - assert(await trigger.evaluate(element => element === document.activeElement), "Closing restores focus"); + await closeSettings(); await page.reload(); - await trigger.click(); + await showSettings(); assert.equal(await interval.inputValue(), "2", "Interval survives reload"); await changeSeconds(0); await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor(); @@ -71,17 +82,17 @@ try { await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting"); await settings.getByText("No settings found", { exact: true }).waitFor(); await settings.getByRole("button", { name: "Clear search" }).click(); - await page.screenshot({ path: ".audit/settings-general.png" }); - await page.keyboard.press("Escape"); + await settingsPage.screenshot({ path: ".audit/settings-general.png" }); + await closeSettings(); await page.keyboard.press("Control+p"); await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt"); await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click(); await page.locator(".monaco-editor textarea").waitFor(); await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000)); - await trigger.click(); + await showSettings(); await changeSeconds(3); - await page.keyboard.press("Escape"); + await closeSettings(); await edit("Saved at three seconds"); const before = await writes(); await page.clock.runFor(2100); @@ -90,53 +101,52 @@ try { assert.equal(await writes(), before + 1, "New interval saves the dirty buffer"); await page.clock.runFor(3100); assert.equal(await writes(), before + 1, "Clean files are not rewritten"); - await trigger.click(); + await showSettings(); await enabled.uncheck(); assert(await interval.isDisabled()); - await page.keyboard.press("Escape"); + await closeSettings(); await edit("Manual save while auto-save is disabled"); await page.clock.runFor(10000); assert.equal(await writes(), before + 1); await page.keyboard.press("Control+s"); await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2); await page.locator(".monaco-editor textarea").focus(); - await page.keyboard.press("Control+,"); + await showSettings(true); await settings.waitFor(); - await page.keyboard.press("Escape"); + await closeSettings(); await page.locator(".monaco-editor textarea").focus(); await page.keyboard.press("F1"); await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor(); await page.keyboard.press("Escape"); const other = await context.newPage(); - await other.goto(url); - await other.getByRole("button", { name: "Settings (Ctrl+,)" }).click(); + await other.goto(`${url}/?settingsWindow=true`); assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3"); assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false); await other.getByRole("button", { name: "Restore defaults" }).click(); await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled); - await trigger.click(); + await showSettings(); await enabled.waitFor(); assert(await enabled.isChecked(), "Other windows receive changes"); assert.equal(await interval.inputValue(), "5"); - await page.keyboard.press("Escape"); + await closeSettings(); await edit("Auto-save enabled from another window"); await page.clock.runFor(5100); assert.equal(await writes(), before + 3); await other.close(); - await trigger.click(); - await page.evaluate(() => { + await showSettings(); + await settingsPage.evaluate(() => { window.__SET_ITEM__ = Storage.prototype.setItem; Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); }; }); await changeSeconds(7); await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor(); - await page.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; }); - await page.keyboard.press("Escape"); - await trigger.click(); + await settingsPage.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; }); + await closeSettings(); + await showSettings(); assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings"); - await page.keyboard.press("Escape"); + await closeSettings(); await page.getByRole("button", { name: "Help and about (F1)" }).click(); const help = page.getByRole("dialog", { name: "Help and about", exact: true }); @@ -145,19 +155,19 @@ try { await page.screenshot({ path: ".audit/settings-help.png" }); await page.keyboard.press("Escape"); await page.keyboard.press("Control+b"); - await page.keyboard.press("Control+,"); + await showSettings(true); await settings.waitFor(); - await page.keyboard.press("Escape"); + await closeSettings(); await page.keyboard.press("F1"); await help.waitFor(); await page.keyboard.press("Escape"); - await page.setViewportSize({ width: 420, height: 650 }); - await page.keyboard.press("Control+,"); + await settingsPage.setViewportSize({ width: 540, height: 420 }); + await showSettings(true); await settings.waitFor(); assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits"); - await page.screenshot({ path: ".audit/settings-narrow.png" }); + await settingsPage.screenshot({ path: ".audit/settings-narrow.png" }); for (let i = 0; i < 12; i++) { - await page.keyboard.press("Tab"); + await settingsPage.keyboard.press("Tab"); assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal"); } assert.deepEqual(errors, []); diff --git a/scripts/settingsWindow.smoke.mjs b/scripts/settingsWindow.smoke.mjs new file mode 100644 index 0000000..ba8a3ce --- /dev/null +++ b/scripts/settingsWindow.smoke.mjs @@ -0,0 +1,91 @@ +// Run against pnpm dev. Native IPC is mocked; this does not test the operating system title bar. +import { createRequire } from "node:module"; +import assert from "node:assert/strict"; +import { mkdir } from "node:fs/promises"; +const require = createRequire(import.meta.url); +const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright"); +const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) }); +const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420"; +const errors = []; +const context = await browser.newContext({ viewport: { width: 1100, height: 760 } }); +const watch = page => page.on("pageerror", error => errors.push(error.message)); +try { + const main = await context.newPage(); watch(main); + await main.goto(origin); + await main.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click(); + assert.equal(await main.locator("dialog:modal").count(), 1, "Browser preview retains the settings dialog"); + const settings = await context.newPage(); watch(settings); + await settings.goto(`${origin}/?settingsWindow=true`); + await settings.getByRole("heading", { name: "General", exact: true }).waitFor(); + assert.equal(await settings.locator(".workbench").count(), 0); + const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" }); + await interval.fill("17"); await interval.press("Tab"); + await main.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "17"); + await main.getByRole("spinbutton", { name: "Auto-save interval" }).fill("29"); + await main.getByRole("spinbutton", { name: "Auto-save interval" }).press("Tab"); + await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29"); + await settings.reload(); + await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29"); + await interval.fill("301"); await interval.press("Tab"); + await settings.getByRole("alert").filter({ hasText: "Choose a whole number" }).waitFor(); + assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29); + await settings.evaluate(() => { Storage.prototype.setItem = () => { throw new Error("Storage full"); }; }); + await interval.fill("40"); await interval.press("Tab"); + await settings.getByRole("alert").filter({ hasText: "Could not save these settings" }).waitFor(); + assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29); + await settings.reload(); + await settings.getByRole("button", { name: "Plug-ins", exact: true }).click(); + await settings.getByRole("heading", { name: "Plug-ins", exact: true }).waitFor(); + await settings.getByRole("button", { name: "General", exact: true }).click(); + await mkdir(".audit", { recursive: true }); + await settings.screenshot({ path: ".audit/settings-window.png" }); + await settings.setViewportSize({ width: 540, height: 420 }); + assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + await settings.keyboard.press("Escape"); + await settings.waitForURL(`${origin}/`); + + const desktop = await context.newPage(); watch(desktop); + await desktop.addInitScript(() => { + window.isTauri = true; + const callbacks = new Map(); + let sequence = 0; + window.settingsTest = { opens: 0, fail: false, closes: 0 }; + window.__TAURI_INTERNALS__ = { + metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } }, + transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; }, + unregisterCallback: id => callbacks.delete(id), + invoke: async (command, args = {}) => { + if (command === "settings_open_window") { + window.settingsTest.opens++; + if (window.settingsTest.fail) throw new Error("Native window creation failed"); + await new Promise(resolve => setTimeout(resolve, 150)); + return; + } + if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] }; + if (command === "workspace_last_path") return null; + if (command === "plugin:event|listen") return args.handler; + if (command === "plugin:event|unlisten") return; + if (command === "plugin:window|close") { window.settingsTest.closes++; return; } + throw new Error(`Unexpected IPC: ${command}`); + }, + }; + window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; + }); + await desktop.goto(origin); + await desktop.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).dblclick(); + assert.equal(await desktop.evaluate(() => window.settingsTest.opens), 1, "Rapid requests share the pending native open"); + assert.equal(await desktop.locator("dialog:modal").count(), 0, "Native open does not block the workbench"); + await desktop.waitForTimeout(180); + await desktop.keyboard.press("Control+,"); + await desktop.waitForFunction(() => window.settingsTest.opens === 2); + await desktop.waitForTimeout(180); + await desktop.evaluate(() => { window.settingsTest.fail = true; }); + await desktop.keyboard.press("Control+,"); + await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor(); + await desktop.goto(`${origin}/?settingsWindow=true`); + await desktop.getByRole("heading", { name: "General", exact: true }).waitFor(); + await desktop.getByRole("button", { name: "Close settings", exact: true }).click(); + assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1); + assert.deepEqual(errors, []); + console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close."); +} finally { await browser.close(); } diff --git a/scripts/splitLayout.spec.ts b/scripts/splitLayout.spec.ts new file mode 100644 index 0000000..8e80d7f --- /dev/null +++ b/scripts/splitLayout.spec.ts @@ -0,0 +1,18 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { splitPane, removePane, paneBounds, containsPane } from "../src/lib/workspace/splitLayout.ts"; + +test("nested splits preserve the source and divide the requested pane", () => { + const right = splitPane("a", "a", "b", "right"); + const nested = splitPane(right, "b", "c", "down"); + assert.deepEqual(paneBounds(nested), { + a: { left: 0, top: 0, width: 50, height: 100 }, + b: { left: 50, top: 0, width: 50, height: 50 }, + c: { left: 50, top: 50, width: 50, height: 50 }, + }); + assert.equal(containsPane(nested, "c"), true); + const closed = removePane(nested, "b")!; + assert.deepEqual(paneBounds(closed).c, { left: 50, top: 0, width: 50, height: 100 }); + assert.equal(removePane(closed, "a"), "c"); + assert.equal(removePane("c", "c"), null); +}); diff --git a/scripts/tabOrder.smoke.mjs b/scripts/tabOrder.smoke.mjs index 015d6a0..84b994b 100644 --- a/scripts/tabOrder.smoke.mjs +++ b/scripts/tabOrder.smoke.mjs @@ -34,7 +34,7 @@ await page.addInitScript(() => { window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} }; }); const tab = name => page.getByRole("tab", { name, exact: true }); -const order = () => page.getByRole("tablist", { name: "Open files" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)); +const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)); const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))); async function open(name) { await page.keyboard.press("Control+p"); @@ -100,7 +100,7 @@ try { console.log("PASS: empty tabs and middle-click close after reorder"); for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`); - const bar = page.getByRole("tablist", { name: "Open files" }); + const bar = page.getByRole("tablist", { name: "Working tabs" }); assert.ok(await bar.evaluate(node => node.scrollLeft > 0)); await tab("note-15.md").press("Alt+Shift+Home"); assert.equal((await order())[0], "note-15.md"); @@ -111,7 +111,7 @@ try { await page.mouse.down(); await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 }); await page.waitForFunction(() => { - const bar = document.querySelector('[aria-label="Open files"]'); + const bar = document.querySelector('[aria-label="Working tabs"]'); return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2; }); await page.mouse.up(); diff --git a/scripts/workbenchTabs.spec.ts b/scripts/workbenchTabs.spec.ts new file mode 100644 index 0000000..cd5d0d8 --- /dev/null +++ b/scripts/workbenchTabs.spec.ts @@ -0,0 +1,38 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { orderWorkbenchTabs } from "../src/lib/workspace/workbenchTabs.ts"; +import { tabsToClose } from "../src/lib/workspace/tabActions.ts"; +import { Documents } from "../src/lib/workspace/documents.ts"; + +test("mixed tabs retain their positions through title changes, closes, and new tabs", () => { + const tabs = [ + { id: "a", relPath: "a.md", name: "a.md", pinned: true }, + { id: "b", relPath: "renamed.md", name: "renamed.md" }, + { id: "plugin-a", relPath: "plugin:a", name: "New page title" }, + { id: "plugin-b", relPath: "plugin:b", name: "Board" }, + ]; + const ordered = orderWorkbenchTabs(tabs, ["plugin-a", "b", "a", "closed", "plugin-a"]); + assert.deepEqual(ordered.map(tab => tab.id), ["plugin-a", "b", "a", "plugin-b"]); + assert.equal(ordered[0].name, "New page title"); + assert.deepEqual(tabsToClose(ordered, "plugin:a", "after").map(tab => tab.id), ["b", "plugin-b"]); + assert.deepEqual(tabsToClose(ordered, "renamed.md", "others").map(tab => tab.id), ["plugin-a", "plugin-b"]); + assert.deepEqual(tabsToClose(ordered, "plugin:b", "all").map(tab => tab.id), ["plugin-a", "b", "plugin-b"]); +}); + +test("replacing an empty or current document retains its tab position and creates a new buffer", async () => { + const docs = new Documents({ + read: async path => path, write: async () => {}, image: async () => "", + kind: () => "text", chrome: () => "Writing", + }, () => {}); + docs.newTab(); + const emptyId = docs.active!.id; + const order = ["plugin-a", emptyId, "plugin-b"]; + for (const rel_path of ["a.md", "b.md"]) { + const previousBuffer = docs.active!.id; + await docs.open({ rel_path, name: rel_path, kind: "file" }, "current"); + assert.notEqual(docs.active!.id, previousBuffer); + assert.equal(docs.active!.tabId, emptyId); + const tabs = [{ id: "plugin-a" }, { id: "plugin-b" }, { id: docs.active!.tabId! }]; + assert.deepEqual(orderWorkbenchTabs(tabs, order).map(tab => tab.id), order); + } +}); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 82283cf..85197e2 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3130,7 +3130,7 @@ dependencies = [ [[package]] name = "runestone" -version = "0.1.7" +version = "0.1.10" dependencies = [ "base64 0.23.1", "dunce", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b8d074b..b4cca6b 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "runestone" -version = "0.1.7" +version = "0.1.10" description = "Writing workspace plus script editor" authors = ["you"] edition = "2021" @@ -22,7 +22,6 @@ notify = "8.2.0" ignore = "0.4.33" dunce = "1.0.5" tauri-plugin-dialog = "2.7.3" -windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } base64 = "0.23.1" portable-pty = "0.9.0" zip = { version = "8.6.0", default-features = false, features = ["deflate"] } @@ -30,6 +29,9 @@ sha2 = "0.10" uuid = { version = "1", features = ["v4"] } reqwest = { version = "0.13.5", default-features = false, features = ["blocking", "native-tls"] } +[target.'cfg(windows)'.dependencies] +windows-sys = { version = "0.61.2", features = ["Win32_Storage_FileSystem", "Win32_UI_Input_KeyboardAndMouse"] } + # Read the optimization guideline for more details: https://tauri.app/concept/size/#cargo-configuration [profile.release] diff --git a/src-tauri/build.rs b/src-tauri/build.rs index c776ae5..55e5285 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -2,12 +2,18 @@ fn main() { tauri_build::try_build( tauri_build::Attributes::new().app_manifest( tauri_build::AppManifest::new().commands(&[ + "settings_open_window", + "completion_request", + "completion_cancel", + "browser_request", + "browser_stop", "workspace_open", "workspace_open_window", "workspace_last_path", "workspace_recent", "workspace_new", "workspace_list", + "workspace_list_markdown", "workspace_read", "workspace_read_bytes", "workspace_write", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 8f9ce3e..5d15e7b 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -2,8 +2,13 @@ "$schema": "../gen/schemas/desktop-schema.json", "identifier": "default", "description": "Capability for the main window", - "windows": ["main", "workspace-*", "terminal-*"], + "windows": ["main", "workspace-*", "terminal-*", "browser-*"], "permissions": [ + "allow-settings-open-window", + "allow-completion-request", + "allow-completion-cancel", + "allow-browser-request", + "allow-browser-stop", "core:default", "core:window:allow-destroy", "core:window:allow-close", @@ -18,6 +23,7 @@ "allow-workspace-recent", "allow-workspace-new", "allow-workspace-list", + "allow-workspace-list-markdown", "allow-workspace-read", "allow-workspace-read-bytes", "allow-workspace-write", diff --git a/src-tauri/capabilities/settings.json b/src-tauri/capabilities/settings.json new file mode 100644 index 0000000..643d7a7 --- /dev/null +++ b/src-tauri/capabilities/settings.json @@ -0,0 +1,29 @@ +{ + "$schema": "../gen/schemas/desktop-schema.json", + "identifier": "settings", + "description": "Settings windows and their plugin settings", + "windows": ["settings-main", "settings-workspace-*"], + "permissions": [ + "core:default", + "core:window:allow-close", + "dialog:default", + "allow-plugins-snapshot", + "allow-plugins-choose", + "allow-plugins-from-git", + "allow-plugins-cancel", + "allow-plugins-install", + "allow-plugins-set-enabled", + "allow-plugins-load", + "allow-plugins-release", + "allow-plugins-prepare-remove", + "allow-plugins-remove", + "allow-plugins-retry-remove", + "allow-plugins-reveal", + "allow-plugins-data", + "allow-plugins-asset", + "allow-browser-request", + "allow-browser-stop", + "allow-completion-request", + "allow-completion-cancel" + ] +} diff --git a/src-tauri/permissions/autogenerated/browser_request.toml b/src-tauri/permissions/autogenerated/browser_request.toml new file mode 100644 index 0000000..5301df4 --- /dev/null +++ b/src-tauri/permissions/autogenerated/browser_request.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-browser-request" +description = "Enables the browser_request command without any pre-configured scope." +commands.allow = ["browser_request"] + +[[permission]] +identifier = "deny-browser-request" +description = "Denies the browser_request command without any pre-configured scope." +commands.deny = ["browser_request"] diff --git a/src-tauri/permissions/autogenerated/browser_stop.toml b/src-tauri/permissions/autogenerated/browser_stop.toml new file mode 100644 index 0000000..fbb9301 --- /dev/null +++ b/src-tauri/permissions/autogenerated/browser_stop.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-browser-stop" +description = "Enables the browser_stop command without any pre-configured scope." +commands.allow = ["browser_stop"] + +[[permission]] +identifier = "deny-browser-stop" +description = "Denies the browser_stop command without any pre-configured scope." +commands.deny = ["browser_stop"] diff --git a/src-tauri/permissions/autogenerated/completion_cancel.toml b/src-tauri/permissions/autogenerated/completion_cancel.toml new file mode 100644 index 0000000..5510230 --- /dev/null +++ b/src-tauri/permissions/autogenerated/completion_cancel.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-completion-cancel" +description = "Enables the completion_cancel command without any pre-configured scope." +commands.allow = ["completion_cancel"] + +[[permission]] +identifier = "deny-completion-cancel" +description = "Denies the completion_cancel command without any pre-configured scope." +commands.deny = ["completion_cancel"] diff --git a/src-tauri/permissions/autogenerated/completion_request.toml b/src-tauri/permissions/autogenerated/completion_request.toml new file mode 100644 index 0000000..24ed71d --- /dev/null +++ b/src-tauri/permissions/autogenerated/completion_request.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-completion-request" +description = "Enables the completion_request command without any pre-configured scope." +commands.allow = ["completion_request"] + +[[permission]] +identifier = "deny-completion-request" +description = "Denies the completion_request command without any pre-configured scope." +commands.deny = ["completion_request"] diff --git a/src-tauri/permissions/autogenerated/settings_open_window.toml b/src-tauri/permissions/autogenerated/settings_open_window.toml new file mode 100644 index 0000000..2eb2e5f --- /dev/null +++ b/src-tauri/permissions/autogenerated/settings_open_window.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-settings-open-window" +description = "Enables the settings_open_window command without any pre-configured scope." +commands.allow = ["settings_open_window"] + +[[permission]] +identifier = "deny-settings-open-window" +description = "Denies the settings_open_window command without any pre-configured scope." +commands.deny = ["settings_open_window"] diff --git a/src-tauri/permissions/autogenerated/workspace_list_markdown.toml b/src-tauri/permissions/autogenerated/workspace_list_markdown.toml new file mode 100644 index 0000000..b06da94 --- /dev/null +++ b/src-tauri/permissions/autogenerated/workspace_list_markdown.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-workspace-list-markdown" +description = "Enables the workspace_list_markdown command without any pre-configured scope." +commands.allow = ["workspace_list_markdown"] + +[[permission]] +identifier = "deny-workspace-list-markdown" +description = "Denies the workspace_list_markdown command without any pre-configured scope." +commands.deny = ["workspace_list_markdown"] diff --git a/src-tauri/src/browser.rs b/src-tauri/src/browser.rs new file mode 100644 index 0000000..5cb5ff9 --- /dev/null +++ b/src-tauri/src/browser.rs @@ -0,0 +1,639 @@ +use serde_json::{json, Value}; +use std::{ + collections::{HashMap, HashSet}, + fs, + io::{BufRead, BufReader, Read, Write}, + net::TcpStream, + path::{Path, PathBuf}, + process::{Child, Command, Stdio}, + sync::{mpsc, Arc, Mutex}, + time::{Duration, Instant}, +}; +use tauri::{AppHandle, Emitter, Manager, State}; + +type Result = std::result::Result; +const PLUGIN: &str = "runestone.browser"; +const COMMANDS: &[&str] = &[ + "state", + "newTab", + "closeTab", + "navigate", + "back", + "forward", + "reload", + "stop", + "find", + "stopFind", + "openExternal", + "moveToWindow", + "adoptTab", + "resize", + "visible", + "input", + "createProfile", + "renameProfile", + "duplicateProfile", + "bookmark", + "removeBookmark", + "settings", + "clearData", + "agentSnapshot", +]; +#[derive(Default)] +pub struct BrowserState { + inner: Mutex>, +} +#[derive(Default)] +struct WindowTabs { + windows: HashSet, + owners: HashMap, + pending: HashMap, + transfer_tokens: HashMap, +} +impl WindowTabs { + fn snapshot(&self, mut value: Value, owner: &str) -> Value { + if let Some(tabs) = value.get_mut("tabs").and_then(Value::as_array_mut) { + tabs.retain(|tab| tab["id"].as_str().and_then(|id| self.owners.get(id)).is_some_and(|window| window == owner)); + for tab in tabs { + if let Some(token) = tab["id"].as_str().and_then(|id| self.transfer_tokens.get(id)) { + tab["transferToken"] = json!(token); + } + } + } + value + } + fn close(&mut self, owner: &str) -> Vec { + self.windows.remove(owner); + self.pending.retain(|_, target| target != owner); + let closed: Vec = self.owners.iter().filter(|(id, window)| !self.windows.contains(*window) && !self.pending.contains_key(*id)).map(|(id, _)| id.clone()).collect(); + for id in &closed { self.owners.remove(id); self.transfer_tokens.remove(id); } + closed + } + fn assign(&mut self, id: &str, owner: &str) { + self.owners.insert(id.into(), owner.into()); + self.transfer_tokens.insert(id.into(), uuid::Uuid::new_v4().to_string()); + } + fn adopt(&mut self, id: &str, owner: &str, token: Option<&str>) -> Result { + let source = self.owners.get(id).cloned().ok_or("Unknown browser tab.")?; + if source == owner { return Err("This browser tab already belongs to this window.".into()); } + let pending = self.pending.get(id).map(String::as_str); + let dragged = pending.is_none() && token.is_some() && self.transfer_tokens.get(id).map(String::as_str) == token; + if pending != Some(owner) && !dragged { return Err("This browser tab has no valid transfer to this window.".into()); } + self.assign(id, owner); + self.pending.remove(id); + Ok(source) + } +} +struct Worker { + child: Child, + input: Box, + replies: mpsc::Receiver, + routing: Arc>, + sequence: u64, + healthy: bool, +} + +fn fail(error: impl std::fmt::Display) -> String { + error.to_string() +} +fn root(app: &AppHandle) -> Result { + Ok(app.path().app_data_dir().map_err(fail)?.join("browser")) +} +fn executable(app: &AppHandle) -> Result { + let name = if cfg!(windows) { + "RuneStone-Browser.exe" + } else { + "RuneStone-Browser" + }; + let packaged = app + .path() + .resource_dir() + .map_err(fail)? + .join("browser-engine") + .join(name); + if packaged.is_file() { + return Ok(packaged); + } + #[cfg(debug_assertions)] + { + let development = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("browser-engine") + .join(name); + if development.is_file() { + return Ok(development); + } + } + Err("The browser runtime is missing. Build RuneStone with its browser runtime.".into()) +} + +fn authenticate_connection( + stream: TcpStream, + token: &str, +) -> Result)>> { + stream.set_nonblocking(false).map_err(fail)?; + stream.set_nodelay(true).map_err(fail)?; + stream.set_read_timeout(Some(Duration::from_secs(1))).map_err(fail)?; + let mut reader = BufReader::new(stream.try_clone().map_err(fail)?); + let mut bytes = Vec::new(); + let read = reader.by_ref().take(256).read_until(b'\n', &mut bytes); + let received = serde_json::from_slice::(&bytes) + .ok() + .and_then(|value| value["token"].as_str().map(str::to_string)); + if read.is_err() || received.as_deref() != Some(token) { + return Ok(None); + } + // Windows keeps the timeout on the cloned socket after the original changes. + reader.get_ref().set_read_timeout(None).map_err(fail)?; + stream.set_read_timeout(None).map_err(fail)?; + Ok(Some((stream, reader))) +} + +impl Worker { + fn start(app: &AppHandle, routing: Arc>) -> Result { + let directory = root(app)?; + fs::create_dir_all(&directory).map_err(fail)?; + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(fail)?; + listener.set_nonblocking(true).map_err(fail)?; + let port = listener.local_addr().map_err(fail)?.port(); + let token = format!( + "{}{}", + uuid::Uuid::new_v4().simple(), + uuid::Uuid::new_v4().simple() + ); + let mut command = Command::new(executable(app)?); + command + .arg(format!("--rs-connect={port}")) + .arg(format!("--rs-browser-root={}", directory.display())) + .env("RUNESTONE_BROWSER_TOKEN", &token) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + command + .env_remove("ELECTRON_RUN_AS_NODE") + .env_remove("NODE_OPTIONS") + .env_remove("ELECTRON_DISABLE_SANDBOX"); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x08000000); + } + let mut child = command.spawn().map_err(fail)?; + let deadline = Instant::now() + Duration::from_secs(30); + let (input, output): (Box, Box) = loop { + if let Ok((stream, _)) = listener.accept() { + if let Some((stream, reader)) = authenticate_connection(stream, &token)? { + break (Box::new(stream), Box::new(reader)); + } + } + if Instant::now() >= deadline || child.try_wait().map_err(fail)?.is_some() { + let _ = child.kill(); + let _ = child.wait(); + return Err("The browser runtime did not start.".into()); + } + std::thread::sleep(Duration::from_millis(20)); + }; + drop(listener); + let (send, replies) = mpsc::sync_channel(16); + let handle = app.clone(); + let routes = routing.clone(); + std::thread::spawn(move || { + let mut reader = BufReader::new(output); + loop { + let mut bytes = Vec::new(); + match reader + .by_ref() + .take(6_000_001) + .read_until(b'\n', &mut bytes) + { + Ok(0) | Err(_) => break, + Ok(_) if bytes.len() > 6_000_000 || !bytes.ends_with(b"\n") => break, + _ => {} + } + let Ok(value) = serde_json::from_slice::(&bytes) else { + continue; + }; + match value.get("event").and_then(Value::as_str) { + Some("frame") => { + if let Ok(routes) = routes.lock() { + if let Some(target) = value["tabId"].as_str().and_then(|id| routes.owners.get(id)) { + let _ = handle.emit_to(target, "browser-frame", &value); + } + } + } + Some("state") | Some("error") => { + if let Ok(routes) = routes.lock() { + for target in &routes.windows { + if let Some(id) = value["tabId"].as_str() { + if routes.owners.get(id) != Some(target) { continue; } + } + let mut payload = value.clone(); + if value.get("state").is_some() { payload["state"] = routes.snapshot(value["state"].clone(), target); } + let _ = handle.emit_to(target, "browser-state", &payload); + } + } + } + _ => { + if send.try_send(value).is_err() { + break; + } + } + } + } + }); + let mut worker = Self { + child, + input, + replies, + routing, + sequence: 0, + healthy: true, + }; + match worker.replies.recv_timeout(Duration::from_secs(30)) { + Ok(value) if value["event"] == "ready" => Ok(worker), + _ => { + let _ = worker.child.kill(); + let _ = worker.child.wait(); + Err("The browser runtime did not start.".into()) + } + } + } + fn request(&mut self, command: &str, args: Value) -> Result { + let response = match self.exchange(command, args) { + Ok(response) => response, + Err(error) => { + self.healthy = false; + return Err(error); + } + }; + if let Some(error) = response["error"].as_str() { + return Err(error.into()); + } + Ok(response["result"].clone()) + } + fn exchange(&mut self, command: &str, args: Value) -> Result { + self.sequence += 1; + let message = json!({ "id": self.sequence, "command": command, "args": args }); + writeln!(self.input, "{}", message).map_err(fail)?; + self.input.flush().map_err(fail)?; + let response = self + .replies + .recv_timeout(Duration::from_secs(30)) + .map_err(|_| { + "The browser stopped responding. Open a new browser tab to restart it.".to_string() + })?; + if response["id"].as_u64() != Some(self.sequence) { + return Err("The browser response did not match the request.".into()); + } + Ok(response) + } + fn stop(&mut self) -> Result<()> { + if !self.healthy { + let _ = self.child.kill(); + let _ = self.child.wait(); + return Ok(()); + } + let requested = self.request("shutdown", json!({})); + let deadline = Instant::now() + Duration::from_secs(5); + while Instant::now() < deadline { + if self.child.try_wait().map_err(fail)?.is_some() { + return requested.map(|_| ()); + } + std::thread::sleep(Duration::from_millis(20)); + } + let _ = self.child.kill(); + let _ = self.child.wait(); + Err("The browser did not stop cleanly. Profile duplication was cancelled.".into()) + } +} +impl Drop for Worker { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +fn profile_id(value: &str) -> bool { + !value.is_empty() + && value.len() <= 64 + && value + .bytes() + .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-') +} +fn copy_profile(source: &Path, target: &Path, files: &mut usize, bytes: &mut u64) -> Result<()> { + if !source.exists() { + fs::create_dir_all(target).map_err(fail)?; + return Ok(()); + } + let metadata = fs::symlink_metadata(source).map_err(fail)?; + if metadata.file_type().is_symlink() { + return Err("Profile links cannot be duplicated.".into()); + } + if metadata.is_dir() { + fs::create_dir_all(target).map_err(fail)?; + for entry in fs::read_dir(source).map_err(fail)? { + let entry = entry.map_err(fail)?; + copy_profile(&entry.path(), &target.join(entry.file_name()), files, bytes)?; + } + } else if metadata.is_file() { + *files += 1; + *bytes += metadata.len(); + if *files > 50_000 || *bytes > 2_000_000_000 { + return Err("This profile exceeds the duplication limit.".into()); + } + fs::copy(source, target).map_err(fail)?; + } else { + return Err("Unsupported profile entry.".into()); + } + Ok(()) +} +impl BrowserState { + pub fn close_window(&self, owner: &str) { + if let Ok(mut guard) = self.inner.lock() { + let Some(worker) = guard.as_mut() else { return; }; + let (closed, empty) = match worker.routing.lock() { + Ok(mut routes) => { let closed = routes.close(owner); (closed, routes.windows.is_empty()) }, + Err(_) => return, + }; + for id in closed { let _ = worker.request("closeTab", json!({ "tabId": id })); } + if empty { + if let Some(mut worker) = guard.take() { let _ = worker.stop(); } + } + } + } + pub fn close_all(&self) { + if let Ok(mut guard) = self.inner.lock() { + if let Some(mut worker) = guard.take() { + let _ = worker.stop(); + } + } + } + fn request(&self, app: &AppHandle, owner: &str, command: &str, args: Value) -> Result { + if !COMMANDS.contains(&command) || args.to_string().len() > 180_000 || !args.is_object() { + return Err("Invalid browser request.".into()); + } + let mut guard = self.inner.lock().map_err(fail)?; + if guard.as_ref().is_some_and(|worker| !worker.healthy) { + guard.take(); + } + if guard.is_none() { + *guard = Some(Worker::start(app, Arc::new(Mutex::new(WindowTabs::default())))?); + } + let worker = guard.as_mut().unwrap(); + worker.routing.lock().map_err(fail)?.windows.insert(owner.to_string()); + if command == "adoptTab" { + let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; + let result = worker.request("state", json!({}))?; + if !result["tabs"].as_array().is_some_and(|tabs| tabs.iter().any(|tab| tab["id"] == id)) { + return Err("Unknown browser tab.".into()); + } + let source = { + let mut routes = worker.routing.lock().map_err(fail)?; + routes.adopt(id, owner, args["transferToken"].as_str())? + }; + let _ = app.emit_to(&source, "browser-tab-moved", json!({ "tabId": id })); + return Ok(worker.routing.lock().map_err(fail)?.snapshot(result, owner)); + } + if ["closeTab", "navigate", "back", "forward", "reload", "stop", "find", "stopFind", "openExternal", "moveToWindow", "resize", "visible", "input", "bookmark", "agentSnapshot"].contains(&command) { + let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; + match worker.routing.lock().map_err(fail)?.owners.get(id) { + Some(window) if window == owner => {}, + Some(_) => return Err("This browser tab belongs to another window.".into()), + None => return Err("Unknown browser tab.".into()), + } + } + if command == "moveToWindow" { + let id = args["tabId"].as_str().ok_or("Invalid browser tab.")?; + let label = format!("browser-{}", uuid::Uuid::new_v4()); + { + let mut routes = worker.routing.lock().map_err(fail)?; + if routes.pending.contains_key(id) { return Err("This tab already has a pending window move.".into()); } + routes.pending.insert(id.into(), label.clone()); + routes.windows.insert(label.clone()); + } + let mut url = tauri::Url::parse("http://localhost/").map_err(fail)?; + url.query_pairs_mut().append_pair("browserWindow", "true"); + url.query_pairs_mut().append_pair("browserTab", id); + if args["pinned"] == true { url.query_pairs_mut().append_pair("browserPinned", "true"); } + let result = tauri::WebviewWindowBuilder::new(app, &label, tauri::WebviewUrl::App(format!("?{}", url.query().unwrap_or_default()).into())) + .title("RuneStone Browser").inner_size(1100.0, 750.0).min_inner_size(500.0, 300.0).decorations(false).drag_and_drop(false).build(); + if let Err(error) = result { + worker.routing.lock().map_err(fail)?.close(&label); + return Err(fail(error)); + } + return Ok(json!({ "windowLabel": label })); + } + if command != "duplicateProfile" { + let result = worker.request(command, args.clone())?; + let mut routes = worker.routing.lock().map_err(fail)?; + if command == "newTab" { + if let Some(id) = result["tabId"].as_str() { routes.assign(id, owner); } + } else if command == "closeTab" { + if let Some(id) = args["tabId"].as_str() { routes.owners.remove(id); routes.pending.remove(id); routes.transfer_tokens.remove(id); } + } + return Ok(routes.snapshot(result, owner)); + } + let plan = guard.as_mut().unwrap().request("prepareDuplicate", args)?; + let source_id = plan["sourceId"] + .as_str() + .filter(|id| profile_id(id)) + .ok_or("Invalid source profile.")?; + let target_id = plan["id"] + .as_str() + .filter(|id| uuid::Uuid::parse_str(id).is_ok()) + .ok_or("Invalid destination profile.")?; + let mut worker = guard.take().unwrap(); + let routing = worker.routing.clone(); + worker.stop()?; + drop(worker); + // Chromium is fully stopped before its databases are copied. + let partitions = root(app)?.join("Partitions"); + let source = partitions.join(format!("runestone-{source_id}")); + let destination = partitions.join(format!("runestone-{target_id}")); + if destination.exists() { + return Err("The destination profile already exists.".into()); + } + copy_profile(&source, &destination, &mut 0, &mut 0)?; + *guard = Some(Worker::start(app, routing.clone())?); + let result = guard.as_mut().unwrap().request("commitDuplicate", plan)?; + let snapshot = routing.lock().map_err(fail)?.snapshot(result, owner); + Ok(snapshot) + } +} + +#[tauri::command] +pub async fn browser_request( + app: AppHandle, + window: tauri::Window, + command: String, + args: Value, +) -> Result { + let owner = window.label().to_string(); + app.state::() + .require_lease(&app, &owner, PLUGIN)?; + tauri::async_runtime::spawn_blocking(move || { + app.state::() + .request(&app, &owner, &command, args) + }) + .await + .map_err(fail)? +} +#[tauri::command] +pub async fn browser_stop(state: State<'_, BrowserState>, window: tauri::Window) -> Result<()> { + state.close_window(window.label()); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn drag_transfer_requires_the_owner_token_and_rejects_replays() { + let mut routes = WindowTabs::default(); + routes.windows.extend(["main".into(), "browser-other".into()]); + routes.assign("a", "browser-other"); + let snapshot = json!({ "tabs": [{ "id": "a" }] }); + let token = routes.snapshot(snapshot.clone(), "browser-other")["tabs"][0]["transferToken"].as_str().unwrap().to_string(); + assert!(routes.snapshot(snapshot, "main")["tabs"].as_array().unwrap().is_empty()); + assert!(routes.adopt("a", "main", None).is_err()); + assert!(routes.adopt("a", "main", Some("wrong-token")).is_err()); + assert_eq!(routes.owners["a"], "browser-other"); + assert_eq!(routes.adopt("a", "main", Some(&token)).unwrap(), "browser-other"); + assert!(routes.adopt("a", "browser-other", Some(&token)).is_err()); + assert!(routes.close("browser-other").is_empty()); + assert_eq!(routes.owners["a"], "main"); + assert_ne!(routes.transfer_tokens["a"], token); + assert_eq!(routes.close("main"), vec!["a"]); + assert!(routes.transfer_tokens.is_empty()); + } + #[test] + fn a_pending_window_move_cannot_be_taken_by_a_drag() { + let mut routes = WindowTabs::default(); + routes.assign("a", "main"); + let token = routes.transfer_tokens["a"].clone(); + routes.pending.insert("a".into(), "browser-target".into()); + assert!(routes.adopt("a", "browser-other", Some(&token)).is_err()); + assert_eq!(routes.adopt("a", "browser-target", None).unwrap(), "main"); + assert!(routes.pending.is_empty()); + } + #[test] + fn window_routing_preserves_moved_tabs_and_filters_snapshots() { + let mut routes = WindowTabs::default(); + routes.windows.extend(["main".into(), "browser-other".into()]); + routes.owners.insert("a".into(), "main".into()); + routes.owners.insert("b".into(), "browser-other".into()); + let snapshot = json!({ "tabs": [{ "id": "a" }, { "id": "b" }], "profiles": [{ "id": "user" }] }); + assert_eq!(routes.snapshot(snapshot.clone(), "main")["tabs"], json!([{ "id": "a" }])); + assert_eq!(routes.snapshot(snapshot, "browser-other")["tabs"], json!([{ "id": "b" }])); + routes.pending.insert("a".into(), "browser-other".into()); + assert!(routes.close("main").is_empty()); + assert!(routes.owners.contains_key("a")); + let mut closed = routes.close("browser-other"); + closed.sort(); + assert_eq!(closed, vec!["a", "b"]); + assert!(routes.owners.is_empty()); + } + #[test] + fn cancelled_window_move_keeps_the_source_tab() { + let mut routes = WindowTabs::default(); + routes.windows.extend(["main".into(), "browser-other".into()]); + routes.owners.insert("a".into(), "main".into()); + routes.pending.insert("a".into(), "browser-other".into()); + assert!(routes.close("browser-other").is_empty()); + assert_eq!(routes.owners.get("a").map(String::as_str), Some("main")); + assert!(routes.pending.is_empty()); + } + #[test] + fn authenticated_connection_survives_idle_period() { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let address = listener.local_addr().unwrap(); + let sender = std::thread::spawn(move || { + let mut stream = TcpStream::connect(address).unwrap(); + writeln!(stream, "{}", json!({ "token": "test-token" })).unwrap(); + std::thread::sleep(Duration::from_millis(1500)); + writeln!(stream, "{}", json!({ "id": 1, "result": { "tabs": [] } })).unwrap(); + }); + let (stream, _) = listener.accept().unwrap(); + let (input, mut reader) = authenticate_connection(stream, "test-token").unwrap().unwrap(); + assert_eq!(input.read_timeout().unwrap(), None); + assert_eq!(reader.get_ref().read_timeout().unwrap(), None); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["id"], 1); + sender.join().unwrap(); + } + #[test] + fn authentication_preserves_buffered_messages_and_rejects_other_tokens() { + for accepted in [false, true] { + let listener = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let address = listener.local_addr().unwrap(); + let sender = std::thread::spawn(move || { + let mut stream = TcpStream::connect(address).unwrap(); + stream.write_all(b"{\"token\":\"test-token\"}\n{\"event\":\"ready\"}\n").unwrap(); + }); + let (stream, _) = listener.accept().unwrap(); + let connection = authenticate_connection(stream, if accepted { "test-token" } else { "other-token" }).unwrap(); + if accepted { + let (_, mut reader) = connection.unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + assert_eq!(serde_json::from_str::(&line).unwrap()["event"], "ready"); + } else { + assert!(connection.is_none()); + } + sender.join().unwrap(); + } + } + fn test_worker(replies: mpsc::Receiver) -> Worker { + Worker { + child: Command::new(std::env::current_exe().unwrap()) + .arg("--list") + .stdout(Stdio::null()) + .spawn() + .unwrap(), + input: Box::new(Vec::::new()), + replies, + routing: Arc::new(Mutex::new(WindowTabs::default())), + sequence: 0, + healthy: true, + } + } + #[test] + fn broken_transport_requires_a_fresh_worker() { + let (send, replies) = mpsc::channel(); + drop(send); + let mut worker = test_worker(replies); + assert!(worker.request("state", json!({})).is_err()); + assert!(!worker.healthy); + assert!(worker.stop().is_ok()); + } + #[test] + fn invalid_settings_do_not_discard_the_worker() { + let (send, replies) = mpsc::channel(); + send.send(json!({ "id": 1, "error": "Invalid browser settings." })).unwrap(); + send.send(json!({ "id": 2, "result": { "tabs": [] } })).unwrap(); + let mut worker = test_worker(replies); + assert!(worker.request("settings", json!({})).is_err()); + assert!(worker.healthy); + assert_eq!(worker.request("state", json!({})).unwrap(), json!({ "tabs": [] })); + } + #[test] + fn profile_names_cannot_escape_storage() { + for value in ["../other", "a/b", "a\\b", "C:", "", "."] { + assert!(!profile_id(value)); + } + assert!(profile_id("user")); + assert!(profile_id("a-b-123")); + } + #[test] + fn protocol_does_not_expose_raw_execution_or_copy_commands() { + for name in [ + "executeJavaScript", + "shell", + "prepareDuplicate", + "commitDuplicate", + "shutdown", + ] { + assert!(!COMMANDS.contains(&name)); + } + } +} diff --git a/src-tauri/src/completion.rs b/src-tauri/src/completion.rs new file mode 100644 index 0000000..ed08a10 --- /dev/null +++ b/src-tauri/src/completion.rs @@ -0,0 +1,81 @@ +use std::{collections::HashMap, io::{BufRead, BufReader}, sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}, time::Duration}; +use reqwest::{blocking::Client, Url}; +use serde::Deserialize; +use tauri::{ipc::Channel, State, WebviewWindow}; + +#[derive(Default)] +pub struct CompletionState { requests: Mutex>> } +impl CompletionState { + pub fn close_window(&self, window: &str) { + if let Ok(mut requests) = self.requests.lock() { + requests.retain(|key, flag| { if key.starts_with(&format!("{window}:")) { flag.store(true, Ordering::Relaxed); false } else { true } }); + } + } +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CompletionRequest { endpoint: String, route: String, body: Option, timeout_ms: Option } +fn target(endpoint: &str, route: &str) -> Result { + let mut url = Url::parse(endpoint).map_err(|_| "Enter a local server URL.")?; + if !matches!(url.scheme(), "http" | "https") || !matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost")) + || !url.username().is_empty() || url.password().is_some() || url.query().is_some() || url.fragment().is_some() + || !matches!(url.path(), "" | "/" | "/v1" | "/v1/") { + return Err("This trial connects only to a loopback model server.".into()); + } + if !matches!(route, "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate") { return Err("Unsupported completion route.".into()); } + if url.host_str() == Some("localhost") { url.set_host(Some("127.0.0.1")).map_err(|_| "Invalid local host.")?; } + url.set_path(route); Ok(url) +} +#[tauri::command] +pub fn completion_cancel(window: WebviewWindow, state: State<'_, CompletionState>, id: String) { + if let Ok(requests) = state.requests.lock() { if let Some(flag) = requests.get(&format!("{}:{id}", window.label())) { flag.store(true, Ordering::Relaxed); } } +} +#[tauri::command] +pub async fn completion_request(window: WebviewWindow, state: State<'_, CompletionState>, id: String, request: CompletionRequest, on_line: Channel) -> Result<(), String> { + if id.len() > 80 || request.body.as_ref().is_some_and(|v| v.len() > 32768) { return Err("Completion request is too large.".into()); } + let url = target(&request.endpoint, &request.route)?; + let flag = Arc::new(AtomicBool::new(false)); + let key = format!("{}:{id}", window.label()); + { + let mut requests = state.requests.lock().map_err(|_| "Completion state is unavailable.")?; + if requests.len() >= 16 { return Err("The local server is busy. Wait before retrying.".into()); } + requests.insert(key.clone(), flag.clone()); + } + let result = tauri::async_runtime::spawn_blocking(move || { + let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()) + .connect_timeout(Duration::from_secs(2)).timeout(Duration::from_millis(request.timeout_ms.unwrap_or(5000).clamp(100, 15000))) + .build().map_err(|_| "Could not create a local connection.".to_string())?; + if flag.load(Ordering::Relaxed) { return Ok(()); } + let call = if let Some(body) = request.body { client.post(url).header("Content-Type", "application/json").body(body) } else { client.get(url) }; + let response = call.send().map_err(|e| if e.is_timeout() { "The local model timed out." } else { "Cannot connect to the local model server." }.to_string())?; + if !response.status().is_success() { return Err(format!("Local server returned HTTP {}.", response.status().as_u16())); } + let mut reader = BufReader::new(response); + let mut total = 0; + loop { + if flag.load(Ordering::Relaxed) { return Ok(()); } + let mut bytes = Vec::new(); + let count = std::io::Read::take(&mut reader, 65537).read_until(b'\n', &mut bytes).map_err(|_| "The local response ended unexpectedly.".to_string())?; + if count == 0 { break; } + total += count; + if count > 65536 || total > 262144 { return Err("Local response exceeded the size limit.".into()); } + if flag.load(Ordering::Relaxed) { return Ok(()); } + let line = String::from_utf8(bytes).map_err(|_| "Local response is not UTF-8.".to_string())?; + if on_line.send(line).is_err() { break; } + } + Ok(()) + }).await.map_err(|_| "Local completion task stopped.".to_string()); + if let Ok(mut requests) = state.requests.lock() { requests.remove(&key); } + result? +} +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn only_loopback_and_fixed_routes() { + assert_eq!(target("http://localhost:8080/v1", "/v1/models").unwrap().as_str(), "http://127.0.0.1:8080/v1/models"); + for address in ["https://example.com", "http://127.0.0.1.example.com", "http://user@localhost", "file:///a", "http://localhost/?key=x", "http://localhost/path"] { + assert!(target(address, "/v1/models").is_err(), "{address}"); + } + assert!(target("http://127.0.0.1:8080", "/shutdown").is_err()); + } +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 8d21f23..b8c22ba 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -2,6 +2,9 @@ mod pty; mod plugins; mod plugin_sources; mod workspace; +mod browser; +mod completion; +mod settings; use pty::PtyState; use tauri::Manager; @@ -15,13 +18,22 @@ pub fn run() { .manage(WorkspaceState::new()) .manage(PtyState::new()) .manage(plugins::PluginState::default()) + .manage(browser::BrowserState::default()) + .manage(completion::CompletionState::default()) + .manage(settings::SettingsState::default()) .invoke_handler(tauri::generate_handler![ + settings::settings_open_window, + completion::completion_request, + completion::completion_cancel, + browser::browser_request, + browser::browser_stop, workspace::workspace_open, workspace::workspace_open_window, workspace::workspace_last_path, workspace::workspace_recent, workspace::workspace_new, workspace::workspace_list, + workspace::workspace_list_markdown, workspace::workspace_read, workspace::workspace_read_bytes, workspace::workspace_write, @@ -60,12 +72,16 @@ pub fn run() { .expect("error while building tauri application") .run(|app, event| { if let tauri::RunEvent::WindowEvent { label, event: tauri::WindowEvent::Destroyed, .. } = &event { + settings::close_owned_window(app, label); app.state::().close_window(label); + app.state::().close_window(label); + app.state::().close_window(label); app.state::().close_window(label); app.state::().close_window(label); } if matches!(event, tauri::RunEvent::Exit) { app.state::().close_all(); + app.state::().close_all(); } }); } diff --git a/src-tauri/src/plugins.rs b/src-tauri/src/plugins.rs index a5de99a..f2aa73c 100644 --- a/src-tauri/src/plugins.rs +++ b/src-tauri/src/plugins.rs @@ -861,6 +861,13 @@ impl Service { } } impl PluginState { + pub fn require_lease(&self, app: &AppHandle, owner: &str, id: &str) -> Result<()> { + self.with(app, |service| { + let enabled = service.catalog.plugins.get(id).is_some_and(|record| record.enabled && record.removal.is_none()); + let leased = service.leases.get(id).is_some_and(|windows| windows.contains(owner)); + if enabled && leased { Ok(()) } else { Err("The browser plugin is not enabled in this window.".into()) } + }) + } fn with( &self, app: &AppHandle, @@ -1019,6 +1026,7 @@ pub async fn plugins_set_enabled( enabled: bool, hash: Option, ) -> Result<()> { + let stop_browser = id == "runestone.browser" && !enabled; state.with(&app, |service| { if service.removing.contains_key(&id) { return Err("Wait for plugin removal to finish.".into()); @@ -1047,6 +1055,7 @@ pub async fn plugins_set_enabled( } Ok(()) })?; + if stop_browser { app.state::().close_all(); } changed(&app); Ok(()) } @@ -1183,7 +1192,8 @@ pub async fn plugins_data( id: String, value: Option, ) -> Result { - state.with(&app, |service| { + let changed = value.is_some(); + let result = state.with(&app, |service| { if !service.row(&id)?.enabled { return Err("The plugin is disabled.".into()); } @@ -1211,7 +1221,11 @@ pub async fn plugins_data( } else { Ok("null".into()) } - }) + })?; + if changed { + let _ = app.emit("plugin-settings-changed", &id); + } + Ok(result) } #[tauri::command] pub async fn plugins_asset( diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs new file mode 100644 index 0000000..c50b03b --- /dev/null +++ b/src-tauri/src/settings.rs @@ -0,0 +1,222 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, atomic::{AtomicBool, Ordering}}; +use tauri::{AppHandle, Manager, State}; +use crate::workspace::{current_root_path, WorkspaceState}; + +#[derive(Default)] +pub struct SettingsState(Mutex>>); + +struct PendingOpen<'a> { + state: &'a SettingsState, + label: String, + cancelled: Arc, +} + +impl SettingsState { + fn reserve(&self, label: &str) -> Result>, String> { + let mut pending = self.0.lock().map_err(|_| "Settings window lock failed.")?; + if let Some(cancelled) = pending.get(label) { + return if cancelled.load(Ordering::SeqCst) { + Err("The workspace changed while settings opened. Try again.".into()) + } else { Ok(None) }; + } + let cancelled = Arc::new(AtomicBool::new(false)); + pending.insert(label.into(), cancelled.clone()); + Ok(Some(PendingOpen { state: self, label: label.into(), cancelled })) + } + + fn cancel(&self, label: &str) { + if let Ok(pending) = self.0.lock() { + if let Some(cancelled) = pending.get(label) { cancelled.store(true, Ordering::SeqCst); } + } + } +} + +impl PendingOpen<'_> { + fn can_publish(&self, owner_exists: bool, expected: &Option, current: &Option) -> bool { + !self.cancelled.load(Ordering::SeqCst) && owner_exists && expected == current + } +} + +impl Drop for PendingOpen<'_> { + fn drop(&mut self) { + if let Ok(mut pending) = self.state.0.lock() { pending.remove(&self.label); } + } +} + +fn settings_label(owner: &str) -> Result { + if owner == "main" || owner.starts_with("workspace-") { + Ok(format!("settings-{owner}")) + } else { + Err("Open settings from a workspace window.".into()) + } +} + +fn bind_workspace(workspace: &WorkspaceState, owner: &str, label: &str) -> Result<(), String> { + if let Ok(root) = current_root_path(workspace, owner) { + workspace.bind_terminal(label, root).map_err(|error| error.to_string())?; + } else { + workspace.close_window(label); + } + Ok(()) +} + +#[tauri::command] +pub async fn settings_open_window( + app: AppHandle, + window: tauri::Window, + state: State<'_, SettingsState>, + workspace: State<'_, WorkspaceState>, +) -> Result<(), String> { + let label = settings_label(window.label())?; + // The reservation survives native calls, but its mutex guard never does. + let Some(pending) = state.reserve(&label)? else { return Ok(()); }; + let root = current_root_path(&workspace, window.label()).ok(); + let valid = || pending.can_publish( + app.get_webview_window(window.label()).is_some(), + &root, ¤t_root_path(&workspace, window.label()).ok(), + ); + if !valid() { return Err("The workspace closed while settings opened.".into()); } + bind_workspace(&workspace, window.label(), &label)?; + let settings = if let Some(existing) = app.get_webview_window(&label) { + existing + } else { + let title = root.as_ref() + .and_then(|root| root.file_name().map(|name| format!("Settings — {} — RuneStone", name.to_string_lossy()))) + .unwrap_or_else(|| "Settings — RuneStone".into()); + match tauri::WebviewWindowBuilder::new( + &app, &label, tauri::WebviewUrl::App("?settingsWindow=true".into()), + ) + .title(title) + .inner_size(920.0, 650.0) + .min_inner_size(540.0, 420.0) + .decorations(true) + .resizable(true) + .visible(false) + .disable_drag_drop_handler() + .build() { + Ok(settings) => settings, + Err(error) => { workspace.close_window(&label); return Err(error.to_string()); } + } + }; + let result = (|| { + if !valid() { return Err("The workspace changed while settings opened.".into()); } + settings.unminimize().map_err(|error| error.to_string())?; + settings.show().map_err(|error| error.to_string())?; + settings.set_focus().map_err(|error| error.to_string())?; + if !valid() { return Err("The workspace changed while settings opened.".into()); } + Ok(()) + })(); + if result.is_err() { + let _ = settings.destroy(); + workspace.close_window(&label); + } + result +} + +pub fn close_owned_window(app: &AppHandle, owner: &str) { + if let Ok(label) = settings_label(owner) { + app.state::().cancel(&label); + if let Some(window) = app.get_webview_window(&label) { let _ = window.destroy(); } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pending_opens_deduplicate_without_holding_the_state_lock() { + let state = SettingsState::default(); + let first = state.reserve("settings-main").unwrap().unwrap(); + assert!(state.0.try_lock().is_ok()); + assert!(state.reserve("settings-main").unwrap().is_none()); + assert!(state.reserve("settings-workspace-2").unwrap().is_some()); + drop(first); + assert!(state.reserve("settings-main").unwrap().is_some()); + } + + #[test] + fn lifecycle_cancellation_does_not_wait_for_an_inflight_build() { + let state = Arc::new(SettingsState::default()); + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (resume_tx, resume_rx) = std::sync::mpsc::channel(); + let worker_state = state.clone(); + let worker = std::thread::spawn(move || { + let pending = worker_state.reserve("settings-main").unwrap().unwrap(); + started_tx.send(()).unwrap(); + // Stand in for a native build waiting for the UI thread. + resume_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + assert!(!pending.can_publish(true, &None, &None)); + }); + started_rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + state.cancel("settings-main"); + assert!(state.reserve("settings-main").is_err()); + resume_tx.send(()).unwrap(); + worker.join().unwrap(); + assert!(state.reserve("settings-main").unwrap().is_some()); + } + + #[test] + fn completed_build_rejects_closed_owners_and_changed_workspaces() { + let state = SettingsState::default(); + let pending = state.reserve("settings-main").unwrap().unwrap(); + let root = Some(PathBuf::from("/one")); + assert!(pending.can_publish(true, &root, &root)); + assert!(!pending.can_publish(false, &root, &root)); + assert!(!pending.can_publish(true, &None, &root)); + assert!(!pending.can_publish(true, &root, &Some(PathBuf::from("/two")))); + state.cancel("settings-main"); + assert!(!pending.can_publish(true, &root, &root)); + } + + #[test] + fn failed_build_releases_its_reservation_for_retry() { + let state = SettingsState::default(); + let failed = || -> Result<(), String> { + let _pending = state.reserve("settings-main")?.unwrap(); + Err("Native build failed".into()) + }; + assert!(failed().is_err()); + assert!(state.reserve("settings-main").unwrap().is_some()); + } + + #[test] + fn each_workspace_reuses_its_own_settings_label() { + assert_eq!(settings_label("main").unwrap(), "settings-main"); + assert_eq!(settings_label("workspace-12").unwrap(), "settings-workspace-12"); + assert_ne!(settings_label("main").unwrap(), settings_label("workspace-12").unwrap()); + } + + #[test] + fn auxiliary_windows_cannot_create_settings_windows() { + for owner in ["settings-main", "terminal-123", "browser-123", "external"] { + assert!(settings_label(owner).is_err()); + } + } + + #[test] + fn settings_use_only_the_owners_workspace_and_release_it_on_close() { + let workspace = WorkspaceState::new(); + workspace.bind_terminal("workspace-1", "/one".into()).unwrap(); + workspace.bind_terminal("workspace-2", "/two".into()).unwrap(); + bind_workspace(&workspace, "workspace-1", "settings-workspace-1").unwrap(); + bind_workspace(&workspace, "workspace-2", "settings-workspace-2").unwrap(); + assert_eq!(current_root_path(&workspace, "settings-workspace-1").unwrap(), std::path::PathBuf::from("/one")); + assert_eq!(current_root_path(&workspace, "settings-workspace-2").unwrap(), std::path::PathBuf::from("/two")); + workspace.close_window("settings-workspace-1"); + assert!(current_root_path(&workspace, "settings-workspace-1").is_err()); + assert!(current_root_path(&workspace, "workspace-1").is_ok()); + } + + #[test] + fn settings_without_a_workspace_never_use_the_recent_workspace() { + let workspace = WorkspaceState::new(); + bind_workspace(&workspace, "main", "settings-main").unwrap(); + assert!(current_root_path(&workspace, "settings-main").is_err()); + workspace.bind_terminal("main", "/opened-later".into()).unwrap(); + bind_workspace(&workspace, "main", "settings-main").unwrap(); + assert_eq!(current_root_path(&workspace, "settings-main").unwrap(), std::path::PathBuf::from("/opened-later")); + } +} diff --git a/src-tauri/src/workspace.rs b/src-tauri/src/workspace.rs index 9d2313f..5c17b3b 100644 --- a/src-tauri/src/workspace.rs +++ b/src-tauri/src/workspace.rs @@ -450,6 +450,8 @@ pub fn workspace_open( }); } let _ = window.set_title(&format!("{} — RuneStone", workspace_info(&root).name)); + // A settings session opened before this workspace must start with its new context. + crate::settings::close_owned_window(&app, window.label()); Ok(workspace_info(&root)) } @@ -510,6 +512,39 @@ fn list_entries(root: &Path, rel: &str) -> WsResult> { Ok(entries) } +#[tauri::command] +pub async fn workspace_list_markdown(window: tauri::Window, state: State<'_, WorkspaceState>) -> WsResult> { + let root = current_root_path(&state, window.label())?; + tauri::async_runtime::spawn_blocking(move || markdown_paths(&root)) + .await.map_err(|error| err(format!("Markdown scan failed: {error}")))? +} + +fn markdown_paths(root: &Path) -> WsResult> { + let mut folders = vec![root.to_path_buf()]; + let mut paths = Vec::new(); + while let Some(folder) = folders.pop() { + for entry in fs::read_dir(folder)? { + let entry = entry?; + let name = entry.file_name(); + // Match PM discovery without a desktop request for every directory. + if name.to_string_lossy().starts_with('.') { continue; } + let kind = entry.file_type()?; + if kind.is_symlink() { continue; } + let path = entry.path(); + if kind.is_dir() { + folders.push(path); + } else if kind.is_file() { + let extension = path.extension().and_then(|value| value.to_str()).unwrap_or("").to_ascii_lowercase(); + if matches!(extension.as_str(), "md" | "markdown" | "mdown") { + if let Some(rel) = to_rel(root, &path) { paths.push(rel); } + } + } + } + } + paths.sort(); + Ok(paths) +} + #[tauri::command] pub fn workspace_read(window: tauri::Window, state: State, rel: String, missing_ok: Option) -> WsResult> { let root = current_root(&state, window.label())?; @@ -812,6 +847,11 @@ pub fn workspace_abs_path(window: tauri::Window, state: State, r pub fn workspace_reveal(window: tauri::Window, app: AppHandle, state: State, rel: String) -> WsResult<()> { let root = current_root(&state, window.label())?; let path = resolve_existing(&root, &rel)?; + if rel.is_empty() { + return app.opener() + .open_path(dunce::simplified(&path).to_string_lossy().into_owned(), None::<&str>) + .map_err(|e| err(e.to_string())); + } if app.opener().reveal_item_in_dir(&path).is_ok() { return Ok(()); } @@ -936,6 +976,30 @@ mod tests { use super::*; use std::path::PathBuf; + #[test] + fn markdown_listing_preserves_discovery_and_excludes_hidden_storage() { + let root = std::env::temp_dir().join(format!("rs-markdown-list-{}", uuid::Uuid::new_v4())); + for rel in ["Notes", "target/deep", ".runestone/pm/cards", "Notes/.hidden", ".git"] { + fs::create_dir_all(root.join(rel)).unwrap(); + } + for rel in ["Board.MD", "Notes/one.markdown", "target/deep/two.mdown", ".runestone/pm/cards/private.md", "Notes/.hidden/secret.md", ".git/hidden.md", "Notes/.hidden.md", "Notes/plain.txt"] { + fs::write(root.join(rel), "text").unwrap(); + } + fs::write(root.join(".gitignore"), "Notes/\ntarget/\n").unwrap(); + assert_eq!(markdown_paths(&root).unwrap(), vec!["Board.MD", "Notes/one.markdown", "target/deep/two.mdown"]); + fs::remove_dir_all(&root).unwrap(); + assert!(markdown_paths(&root).is_err()); + } + + #[test] + #[ignore = "Set RUNESTONE_SCAN_BENCH_ROOT to an existing workspace."] + fn markdown_listing_workspace_benchmark() { + let root = dunce::canonicalize(std::env::var("RUNESTONE_SCAN_BENCH_ROOT").unwrap()).unwrap(); + let start = std::time::Instant::now(); + let paths = markdown_paths(&root).unwrap(); + println!("Native Markdown discovery: {} paths, {:?}", paths.len(), start.elapsed()); + } + #[test] fn binary_reads_preserve_bytes_and_enforce_workspace_and_size_limits() { let fixture = std::env::temp_dir().join(format!("rs-binary-{}", std::process::id())); diff --git a/src-tauri/tauri.browser.conf.json b/src-tauri/tauri.browser.conf.json new file mode 100644 index 0000000..f2853ae --- /dev/null +++ b/src-tauri/tauri.browser.conf.json @@ -0,0 +1,7 @@ +{ + "bundle": { + "resources": { + "browser-engine/": "browser-engine/" + } + } +} diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 2a8d275..37d8a14 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.7", + "version": "0.1.10", "identifier": "com.runestone.app", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/lib/completion/codemirror.ts b/src/lib/completion/codemirror.ts new file mode 100644 index 0000000..126ab24 --- /dev/null +++ b/src/lib/completion/codemirror.ts @@ -0,0 +1,62 @@ +import { Prec, StateEffect, StateField } from "@codemirror/state"; +import { Decoration, EditorView, keymap, ViewPlugin, WidgetType } from "@codemirror/view"; +import { isolateHistory } from "@codemirror/commands"; +import { completionHub } from "./hub"; +import type { CompletionHandle } from "./contracts"; +class Ghost extends WidgetType { + constructor(readonly text: string) { super(); } + eq(other: Ghost) { return other.text === this.text; } + toDOM() { const span = document.createElement("span"); span.className = "rs-completion-ghost"; span.textContent = this.text; span.setAttribute("aria-hidden", "true"); return span; } +} +const preview = StateEffect.define<{ text: string; caret: number } | null>(); +const ghosts = StateField.define({ + create: () => Decoration.none, + update(value, transaction) { + if (transaction.docChanged || transaction.selection) value = Decoration.none; + for (const effect of transaction.effects) if (effect.is(preview)) value = effect.value + ? Decoration.set([Decoration.widget({ widget: new Ghost(effect.value.text), side: 1 }).range(effect.value.caret)]) : Decoration.none; + return value; + }, + provide: field => EditorView.decorations.from(field), +}); +const handles = new WeakMap(); +export function completionExtension(documentId: string) { + return [ghosts, EditorView.baseTheme({ ".rs-completion-ghost": { opacity: "0.65", fontStyle: "italic", pointerEvents: "none" } }), + ViewPlugin.fromClass(class { + handle: CompletionHandle; + disposed = false; + sequence = 0; + revision = 0; + constructor(readonly view: EditorView) { + this.handle = completionHub.registerSurface({ + id: `writer:${documentId}:${crypto.randomUUID()}`, + snapshot: () => ({ documentId, revision: this.revision, text: view.state.doc.toString(), caret: view.state.selection.main.head, + selectionEnd: view.state.selection.ranges.length > 1 ? -1 : view.state.selection.main.anchor, + focused: view.hasFocus, composing: view.composing, readOnly: view.state.readOnly, kind: "prose", language: "markdown" }), + preview: text => { + const sequence = ++this.sequence, caret = view.state.selection.main.head; + queueMicrotask(() => { if (!this.disposed && this.sequence === sequence) view.dispatch({ effects: preview.of(text ? { text, caret } : null) }); }); + }, + insert: (text, expected) => { + if (this.revision !== expected.revision || view.state.selection.main.head !== expected.caret) return false; + view.dispatch({ changes: { from: expected.caret, insert: text }, selection: { anchor: expected.caret + text.length }, userEvent: "input.complete", annotations: isolateHistory.of("full") }); + return true; + }, + }); + handles.set(view, this.handle); + } + update(update: import("@codemirror/view").ViewUpdate) { + if (update.docChanged) this.revision++; + if (update.docChanged || update.selectionSet || update.focusChanged) this.handle.changed(); + } + destroy() { this.disposed = true; this.handle.dispose(); handles.delete(this.view); } + }), + Prec.high(keymap.of([ + { key: "Tab", run: view => !view.composing && !!handles.get(view)?.accept() }, + { key: "Escape", run: view => !!handles.get(view)?.dismiss() }, + { key: "Mod-Alt-Space", run: view => { handles.get(view)?.request(); return true; } }, + { key: "Mod-Alt-ArrowRight", run: view => !!handles.get(view)?.accept(true) }, + ])), + EditorView.domEventHandlers({ compositionstart: (_event, view) => { handles.get(view)?.dismiss(); } }), + ]; +} diff --git a/src/lib/completion/contracts.ts b/src/lib/completion/contracts.ts new file mode 100644 index 0000000..60be153 --- /dev/null +++ b/src/lib/completion/contracts.ts @@ -0,0 +1,58 @@ +export type CompletionDispose = () => void; +export interface CompletionSnapshot { + documentId: string; + revision: string | number; + text: string; + caret: number; + selectionEnd: number; + focused: boolean; + composing?: boolean; + sensitive?: boolean; + readOnly?: boolean; + kind: "prose" | "code"; + language?: string; +} +export interface CompletionRequest { + surfaceId: string; + documentId: string; + revision: string | number; + prefix: string; + suffix: string; + kind: "prose" | "code"; + language: string; + manual: boolean; + signal: AbortSignal; +} +export interface CompletionProvider { + id: string; + delayMs?: number; + timeoutMs?: number; + complete(request: CompletionRequest, publish: (text: string) => void): Promise; +} +export interface CompletionSurface { + id: string; + snapshot(): CompletionSnapshot; + preview(text: string | null): void; + insert(text: string, expected: CompletionSnapshot): boolean; +} +export interface CompletionHandle { + changed(): void; + request(): void; + accept(word?: boolean): boolean; + dismiss(): boolean; + dispose(): void; +} +export interface CompletionTransportRequest { + endpoint: string; + route: "/v1/models" | "/v1/chat/completions" | "/api/tags" | "/api/generate"; + body?: string; + timeoutMs?: number; +} +export interface CompletionApi { + version: 1; + registerProvider(provider: CompletionProvider): CompletionDispose; + registerSurface(surface: CompletionSurface): CompletionHandle; + registerInput(element: HTMLInputElement | HTMLTextAreaElement, options: { id: string; kind?: "prose" | "code"; sensitive?: boolean }): CompletionHandle; + invalidate(): void; + transport?(request: CompletionTransportRequest, signal: AbortSignal, onLine: (line: string) => void): Promise; +} diff --git a/src/lib/completion/hub.ts b/src/lib/completion/hub.ts new file mode 100644 index 0000000..7a460d1 --- /dev/null +++ b/src/lib/completion/hub.ts @@ -0,0 +1,89 @@ +import type { CompletionHandle, CompletionProvider, CompletionSnapshot, CompletionSurface } from "./contracts.ts"; + +export function eligible(s: CompletionSnapshot): boolean { + if (!s.focused || s.composing || s.sensitive || s.readOnly || s.caret !== s.selectionEnd || s.caret < 0 || s.caret > s.text.length) return false; + if (s.kind === "code") return true; + const before = s.text.slice(0, s.caret), line = before.slice(before.lastIndexOf("\n") + 1); + if (/^\s*\|/.test(line) || /\]\([^)]*$/.test(line) || /<[^>]*$/.test(line)) return false; + if ((line.match(/`/g)?.length ?? 0) % 2) return false; + if (/^---\r?\n/.test(s.text) && !/^---\r?$/m.test(before.slice(before.indexOf("\n") + 1))) return false; + let fence = ""; + for (const part of before.split("\n")) { + const match = /^\s{0,3}(`{3,}|~{3,})/.exec(part); + if (match) { if (!fence) fence = match[1]; else if (match[1][0] === fence[0] && match[1].length >= fence.length) fence = ""; } + } + return !fence; +} +function same(a: CompletionSnapshot, b: CompletionSnapshot) { + return a.documentId === b.documentId && a.revision === b.revision && a.caret === b.caret && a.selectionEnd === b.selectionEnd && eligible(b); +} +export class CompletionHub { + private provider?: CompletionProvider; + private surfaces = new Map(); + private cancelActive?: () => void; + registerProvider(provider: CompletionProvider): () => void { + if (this.provider) throw new Error("Another autocomplete provider is active."); + if (!provider.id || typeof provider.complete !== "function") throw new Error("Invalid autocomplete provider."); + this.provider = provider; + return () => { if (this.provider === provider) { this.provider = undefined; this.invalidate(); } }; + } + invalidate() { for (const handle of this.surfaces.values()) handle.dismiss(); } + registerSurface(surface: CompletionSurface): CompletionHandle { + if (!surface.id || this.surfaces.has(surface.id)) throw new Error("Duplicate completion field."); + let timer: ReturnType | undefined; + let timeout: ReturnType | undefined; + let controller: AbortController | undefined; + let expected: CompletionSnapshot | undefined; + let candidate = "", disposed = false, serial = 0; + const dismiss = () => { + const visible = !!candidate; + serial++; clearTimeout(timer); clearTimeout(timeout); controller?.abort(); controller = undefined; + candidate = ""; expected = undefined; surface.preview(null); + return visible; + }; + const run = async (manual: boolean) => { + if (disposed || !this.provider) return; + const snapshot = surface.snapshot(), provider = this.provider; + if (!eligible(snapshot) || !snapshot.text.slice(0, snapshot.caret).trim()) return; + this.cancelActive?.(); dismiss(); this.cancelActive = dismiss; + const version = serial, abort = new AbortController(); controller = abort; expected = snapshot; + timeout = setTimeout(() => { + if (serial !== version) return; + if (candidate && same(snapshot, surface.snapshot())) abort.abort(); + else dismiss(); + }, manual ? 10000 : Math.max(300, Math.min(provider.timeoutMs ?? 1000, 5000))); + const publish = (text: string) => { + if (disposed || serial !== version || abort.signal.aborted || this.provider !== provider || !same(snapshot, surface.snapshot())) return; + if (typeof text !== "string" || text.length > 2000 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text)) return; + candidate = text; surface.preview(text || null); + }; + try { + const result = await provider.complete({ surfaceId: surface.id, documentId: snapshot.documentId, revision: snapshot.revision, + prefix: snapshot.text.slice(Math.max(0, snapshot.caret - 3000), snapshot.caret), suffix: snapshot.text.slice(snapshot.caret, snapshot.caret + 600), + kind: snapshot.kind, language: snapshot.language ?? "", manual, signal: abort.signal }, publish); + if (result) publish(result); + } catch { if (serial === version) dismiss(); } + finally { if (serial === version) { clearTimeout(timeout); controller = undefined; } } + }; + const handle: CompletionHandle = { + changed: () => { + dismiss(); + if (disposed || !this.provider || !eligible(surface.snapshot())) return; + timer = setTimeout(() => { void run(false); }, Math.max(100, Math.min(this.provider.delayMs ?? 200, 1000))); + }, + request: () => { dismiss(); void run(true); }, + dismiss, + accept: (word = false) => { + if (!candidate || !expected || !same(expected, surface.snapshot())) { dismiss(); return false; } + const text = word ? (candidate.match(/^\s*\S+\s*/u)?.[0] ?? candidate) : candidate; + const snapshot = expected; + dismiss(); + return surface.insert(text, snapshot); + }, + dispose: () => { if (disposed) return; disposed = true; dismiss(); this.surfaces.delete(surface.id); if (this.cancelActive === dismiss) this.cancelActive = undefined; }, + }; + this.surfaces.set(surface.id, handle); + return handle; + } +} +export const completionHub = new CompletionHub(); diff --git a/src/lib/completion/input.ts b/src/lib/completion/input.ts new file mode 100644 index 0000000..4da9785 --- /dev/null +++ b/src/lib/completion/input.ts @@ -0,0 +1,47 @@ +import { completionHub } from "./hub.ts"; +import type { CompletionApi, CompletionHandle } from "./contracts.ts"; + +export const registerCompletionInput: CompletionApi["registerInput"] = (element, options) => { + let revision = 0, composing = false; + const hint = document.createElement("div"); + hint.className = "rs-completion-hint"; + hint.style.cssText = "position:fixed;z-index:10000;pointer-events:none;max-width:40em;padding:6px 10px;border-radius:var(--rs-control-radius,6px);background:var(--rs-bg,#20242a);color:var(--rs-text,#eee);border:1px solid currentColor;font:inherit;white-space:pre-wrap"; + hint.hidden = true; + hint.setAttribute("aria-hidden", "true"); + document.body.append(hint); + const handle = completionHub.registerSurface({ + id: options.id, + snapshot: () => ({ documentId: options.id, revision, text: element.value, caret: element.selectionStart ?? 0, selectionEnd: element.selectionEnd ?? 0, + focused: document.activeElement === element, composing, readOnly: element.readOnly || element.disabled, + sensitive: options.sensitive || element instanceof HTMLInputElement && !["text", "search"].includes(element.type), kind: options.kind ?? "prose" }), + preview: text => { hint.hidden = !text; hint.textContent = text ? `${text}\nTab to accept · Escape to dismiss` : ""; const r = element.getBoundingClientRect(); hint.style.left = `${Math.max(0, Math.min(r.left, innerWidth - 350))}px`; hint.style.top = `${Math.min(r.bottom + 4, innerHeight - 100)}px`; }, + insert: (text, expected) => { + if (element.value !== expected.text || element.selectionStart !== expected.caret || element.selectionEnd !== expected.caret) return false; + // The native edit command keeps input and textarea undo history intact. + element.focus(); + return document.execCommand("insertText", false, text); + }, + }); + const changed = () => { revision++; handle.changed(); }; + const select = () => handle.dismiss(); + const start = () => { composing = true; handle.dismiss(); }; + const end = () => { composing = false; changed(); }; + const key: EventListener = raw => { + const event = raw as KeyboardEvent; + if (event.isComposing || composing) return; + if (event.key === "Tab" && !event.shiftKey && !event.altKey && !event.ctrlKey && handle.accept()) { event.preventDefault(); event.stopPropagation(); } + else if (event.key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); } + else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === " ") { event.preventDefault(); handle.request(); } + else if ((event.ctrlKey || event.metaKey) && event.altKey && event.key === "ArrowRight" && handle.accept(true)) event.preventDefault(); + }; + element.addEventListener("input", changed); element.addEventListener("keydown", key); element.addEventListener("blur", select); + element.addEventListener("pointerdown", select); element.addEventListener("select", select); + element.addEventListener("compositionstart", start); element.addEventListener("compositionend", end); + const dispose = () => { + handle.dispose(); hint.remove(); + element.removeEventListener("input", changed); element.removeEventListener("keydown", key); element.removeEventListener("blur", select); + element.removeEventListener("pointerdown", select); element.removeEventListener("select", select); + element.removeEventListener("compositionstart", start); element.removeEventListener("compositionend", end); + }; + return { ...handle, dispose } satisfies CompletionHandle; +}; diff --git a/src/lib/completion/monaco.ts b/src/lib/completion/monaco.ts new file mode 100644 index 0000000..ab25e57 --- /dev/null +++ b/src/lib/completion/monaco.ts @@ -0,0 +1,51 @@ +import type * as Monaco from "monaco-editor"; +import { completionHub } from "./hub"; + +export function connectMonacoCompletion(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, documentId: string, prose: boolean) { + const model = view.getModel()!; + let composing = false; + const decoration = view.createDecorationsCollection(); + if (!document.getElementById("rs-completion-style")) { + const style = document.createElement("style"); style.id = "rs-completion-style"; + style.textContent = ".rs-completion-ghost{opacity:.65;font-style:italic;pointer-events:none}"; + document.head.append(style); + } + const handle = completionHub.registerSurface({ + id: `source:${documentId}:${crypto.randomUUID()}`, + snapshot: () => { + const selection = view.getSelection(), position = view.getPosition(); + return { documentId, revision: model.getVersionId(), text: model.getValue(), caret: position ? model.getOffsetAt(position) : 0, + selectionEnd: (view.getSelections()?.length === 1 && selection?.isEmpty()) && position ? model.getOffsetAt(position) : -1, + focused: view.hasTextFocus(), composing, readOnly: view.getOption(monaco.editor.EditorOption.readOnly), kind: prose ? "prose" : "code", language: model.getLanguageId() }; + }, + preview: text => { + const p = view.getPosition(); + decoration.set(text && p ? [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), options: { + after: { content: text.replace(/\r?\n/g, " ↵ "), inlineClassName: "rs-completion-ghost", cursorStops: monaco.editor.InjectedTextCursorStops.None }, + showIfCollapsed: true, + } }] : []); + }, + insert: (text, expected) => { + if (model.getVersionId() !== expected.revision || !view.getSelection()?.isEmpty()) return false; + const p = model.getPositionAt(expected.caret); + view.pushUndoStop(); + const done = view.executeEdits("autocomplete", [{ range: new monaco.Range(p.lineNumber, p.column, p.lineNumber, p.column), text }]); + view.setPosition(model.getPositionAt(expected.caret + text.length)); view.pushUndoStop(); return done; + }, + }); + const listeners = [model.onDidChangeContent(() => handle.changed()), view.onDidChangeCursorSelection(() => handle.changed()), + view.onDidFocusEditorText(() => handle.changed()), view.onDidBlurEditorText(() => handle.dismiss()), + view.onDidCompositionStart(() => { composing = true; handle.dismiss(); }), view.onDidCompositionEnd(() => { composing = false; handle.changed(); }), + view.onKeyDown(event => { + if (composing) return; + const key = event.browserEvent.key; + if (key === "Tab" && !event.shiftKey && !event.ctrlKey && !event.altKey) { + if (view.getDomNode()?.querySelector(".suggest-widget.visible")) { handle.dismiss(); return; } + if (handle.accept()) { event.preventDefault(); event.stopPropagation(); } + } else if (key === "Escape" && handle.dismiss()) { event.preventDefault(); event.stopPropagation(); } + else if ((event.ctrlKey || event.metaKey) && event.altKey && key === " ") { event.preventDefault(); event.stopPropagation(); handle.request(); } + else if ((event.ctrlKey || event.metaKey) && event.altKey && key === "ArrowRight" && handle.accept(true)) { event.preventDefault(); event.stopPropagation(); } + }), + ]; + return () => { handle.dispose(); decoration.clear(); listeners.forEach(item => item.dispose()); }; +} diff --git a/src/lib/completion/testHarness.ts b/src/lib/completion/testHarness.ts new file mode 100644 index 0000000..139880d --- /dev/null +++ b/src/lib/completion/testHarness.ts @@ -0,0 +1,33 @@ +import { EditorState } from '@codemirror/state'; +import { EditorView, keymap } from '@codemirror/view'; +import { history, historyKeymap, defaultKeymap } from '@codemirror/commands'; +import { completionExtension } from './codemirror'; +import { connectMonacoCompletion } from './monaco'; +import { completionHub } from './hub'; +import { ExternalSession } from '../plugins/externalSession'; +import { monaco } from '../editor/monacoEnv'; +const writer = new EditorView({ parent: document.querySelector('#writer')!, state: EditorState.create({ doc: 'The ', selection: { anchor: 4 }, extensions: [history(), keymap.of([...historyKeymap, ...defaultKeymap]), completionExtension('fixture')] }) }); +const model = monaco.editor.createModel('The ', 'markdown'); +const source = monaco.editor.create(document.querySelector('#source') as HTMLElement, { model, theme: 'vs-dark', automaticLayout: true }); +const stopSource = connectMonacoCompletion(monaco, source, 'fixture-source', true); +source.setPosition({ lineNumber: 1, column: 5 }); +let stopProvider = completionHub.registerProvider({ id: 'fixture', delayMs: 100, complete: async () => 'quiet harbor.' }); +Object.assign(window, { completionTest: { writer, source, model, completionHub, stopProvider, + async plugin(code: string) { + stopProvider(); + const session = new ExternalSession('test.autocomplete', { + settings: { read: async () => ({ enabled: true, endpoint: 'http://127.0.0.1:8012' }), write: async () => {} }, + workspace: { list: async () => [], read: async () => '', write: async () => {} }, assets: { read: async () => new Uint8Array() }, + completionTransport: async (request, signal, onLine) => { + if (request.route === '/v1/models') { onLine('{"data":[{"id":"fixture-model"}]}'); return; } + await new Promise(resolve => setTimeout(resolve, 25)); + if (!signal.aborted) onLine('data: {"choices":[{"delta":{"content":"quiet harbor."}}]}\n'); + }, + }, () => {}, () => {}); + const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' })); + try { await session.start(await import(/* @vite-ignore */ url)); } finally { URL.revokeObjectURL(url); } + await session.mount('settings', document.querySelector('#plugin') as HTMLElement); + return session; + }, + destroy() { stopProvider(); stopSource(); writer.destroy(); source.dispose(); model.dispose(); }, +} }); diff --git a/src/lib/completion/transport.ts b/src/lib/completion/transport.ts new file mode 100644 index 0000000..19048ce --- /dev/null +++ b/src/lib/completion/transport.ts @@ -0,0 +1,16 @@ +import { Channel, invoke } from "@tauri-apps/api/core"; +import type { CompletionApi } from "./contracts.ts"; +export const completionTransport: NonNullable = async (request, signal, onLine) => { + if (signal.aborted) throw new DOMException("Cancelled", "AbortError"); + const id = crypto.randomUUID(); + let parseError: unknown; + const channel = new Channel(); + channel.onmessage = line => { + if (signal.aborted || parseError) return; + try { onLine(line); } catch (error) { parseError = error; cancel(); } + }; + const cancel = () => { void invoke("completion_cancel", { id }).catch(() => {}); }; + signal.addEventListener("abort", cancel, { once: true }); + try { await invoke("completion_request", { id, request, onLine: channel }); if (parseError) throw parseError; } + finally { signal.removeEventListener("abort", cancel); } +}; diff --git a/src/lib/editor/EditorHost.svelte b/src/lib/editor/EditorHost.svelte index a5715b4..d4fb3cc 100644 --- a/src/lib/editor/EditorHost.svelte +++ b/src/lib/editor/EditorHost.svelte @@ -6,6 +6,7 @@ import { editorSession } from "./sessions"; import { registerSelection } from "./selection"; import { monacoChrome } from "./monacoChrome"; + import { connectMonacoCompletion } from "$lib/completion/monaco"; import { markdownMenu } from "./markdownMenu"; import type { TableContextActions } from "./tableCellActions"; @@ -85,6 +86,7 @@ let releaseSelection: (() => void) | undefined; let menu: ReturnType | undefined; let releaseDrop: (() => void) | undefined; + let releaseCompletion: (() => void) | undefined; const listeners: { dispose(): void }[] = []; void import("./monacoEnv").then(({ monaco }) => { if (cancelled || !el.isConnected) { @@ -144,6 +146,7 @@ listeners.push(model.onDidChangeContent(() => menu?.close(false))); } const documentId = untrack(() => buffer.id); + 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); ready += 1; @@ -160,6 +163,7 @@ const view = editor; if (view && session) session.view = view.saveViewState(); contentListener?.dispose(); + releaseCompletion?.(); releaseSelection?.(); menu?.destroy(); releaseDrop?.(); diff --git a/src/lib/editor/LiveWriter.svelte b/src/lib/editor/LiveWriter.svelte index fe56e91..476e0b7 100644 --- a/src/lib/editor/LiveWriter.svelte +++ b/src/lib/editor/LiveWriter.svelte @@ -24,6 +24,7 @@ import type { TableContextActions } from "./tableCellActions"; import { markdownMenu } from "./markdownMenu"; import { tableNavigation } from "./tableNavigation"; + import { completionExtension } from "$lib/completion/codemirror"; type Props = { buffer: OpenBuffer; @@ -138,6 +139,7 @@ if (model.getValue() !== lastValue) model.setValue(lastValue); model.pushStackElement(); const extensions = [ + completionExtension(current.id), EditorState.lineSeparator.of(model.getEOL()), markdown({ base: markdownLanguage, extensions: [noteFormats] }), // Rich cell serialization can change delimiters away from the caret. diff --git a/src/lib/editor/liveMarkdown.ts b/src/lib/editor/liveMarkdown.ts index 4cc68db..c6f1546 100644 --- a/src/lib/editor/liveMarkdown.ts +++ b/src/lib/editor/liveMarkdown.ts @@ -208,7 +208,10 @@ export function liveMarkdown(urls: Map, actions: TableContextAct return [imageSource, StateField.define({ create: build, update(value, transaction) { - return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state, value.map(transaction.changes)) : value; + return transaction.docChanged || transaction.selection + || syntaxTree(transaction.startState) !== syntaxTree(transaction.state) + || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) + ? build(transaction.state, value.map(transaction.changes)) : value; }, provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({ filter: (_from, _to, decoration) => decoration.spec.atomic === true, diff --git a/src/lib/layout/BookmarksPane.svelte b/src/lib/layout/BookmarksPane.svelte index bcdbd9f..3f7087f 100644 --- a/src/lib/layout/BookmarksPane.svelte +++ b/src/lib/layout/BookmarksPane.svelte @@ -1,5 +1,6 @@ + + +
+
+ []} tabActions={actions} + tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} /> + void newTab()} /> +
+ error = message} /> +
+ {#if message}{/if} +
+ {#each $pluginEditors as view (view.key)} + {@const position = bounds[view.key]} + +
{ if (active !== view.key) select(view.key); }} + onpointerdown={() => { if (active !== view.key) select(view.key); }}> + {#if split && position} + tab.id === view.key)} activePath={active} + onSelect={select} onClose={close} onCloseTabs={close} onMove={move} onPin={pinPluginEditor} + fileActions={() => []} tabActions={actions} tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} /> + {/if} + +
+ {/each} + {#if !tabs.length}

{browser ? "Open a browser tab with the + button." : "Loading browser…"}

{/if} +
+
+ + diff --git a/src/lib/layout/EditorPane.svelte b/src/lib/layout/EditorPane.svelte index d513ace..86a0e50 100644 --- a/src/lib/layout/EditorPane.svelte +++ b/src/lib/layout/EditorPane.svelte @@ -26,11 +26,13 @@ onOpenWorkspace: () => void; onNewFile: () => void; onQuickOpen: () => void; + onOpenBrowser?: () => void; + browserOpening?: boolean; hasWorkspace: boolean; tableActions?: TableContextActions; }; - let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props(); + let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props(); let previewMode = $state<"split" | "preview">("split"); let modeControls = $state(); let titleFocusId = $state(null); @@ -94,6 +96,7 @@

{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}

{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}

+ {#if onOpenBrowser}{/if} {#if hasWorkspace} diff --git a/src/lib/layout/FileTree.svelte b/src/lib/layout/FileTree.svelte index 712b163..3100b71 100644 --- a/src/lib/layout/FileTree.svelte +++ b/src/lib/layout/FileTree.svelte @@ -559,7 +559,20 @@ function menuItems(entry: TreeEntry | null): MenuItem[] { if (!entry) { - return paneMenuItems(""); + return [ + ...paneMenuItems(""), + { kind: "sep" }, + { + kind: "action", + label: "Show in Explorer", + icon: "folder", + run: () => { + void workspaceReveal("").catch((err) => { + error = err instanceof Error ? err.message : String(err); + }); + }, + }, + ]; } const entries = actionEntries(entry, selection.paths, visiblePaths, findEntry); const multiple = entries.length > 1; diff --git a/src/lib/layout/SettingsDialog.svelte b/src/lib/layout/SettingsDialog.svelte index a220e52..e60facc 100644 --- a/src/lib/layout/SettingsDialog.svelte +++ b/src/lib/layout/SettingsDialog.svelte @@ -1,22 +1,28 @@ - { if (event.target === dialog) { event.preventDefault(); onClose(); } }}> + { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>

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

@@ -81,6 +94,7 @@ {/if}
+ {#if windowError}{/if} {#if !selected}

No settings found

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

@@ -105,6 +119,10 @@

{message}

{:else if selected.id === "plugins"} + {:else if selected.id === "browser"} + + {:else if selectedPlugin} + {#key selectedPlugin.id}{/key} {:else}

RuneStone

Version {version}

@@ -121,6 +139,7 @@ diff --git a/src/lib/plugins/PluginAccessMenu.svelte b/src/lib/plugins/PluginAccessMenu.svelte new file mode 100644 index 0000000..dbabfd1 --- /dev/null +++ b/src/lib/plugins/PluginAccessMenu.svelte @@ -0,0 +1,42 @@ + + +{#if tools.length} + +{/if} +{#if position && tools.length} position = null} />{/if} +{#if error}{/if} + + diff --git a/src/lib/plugins/PluginEditor.svelte b/src/lib/plugins/PluginEditor.svelte index f00ec4d..994704b 100644 --- a/src/lib/plugins/PluginEditor.svelte +++ b/src/lib/plugins/PluginEditor.svelte @@ -1,6 +1,6 @@ -
{#if error}{/if}
@@ -30,7 +30,6 @@ diff --git a/src/lib/plugins/PluginEditorTab.svelte b/src/lib/plugins/PluginEditorTab.svelte deleted file mode 100644 index 78ee5c2..0000000 --- a/src/lib/plugins/PluginEditorTab.svelte +++ /dev/null @@ -1,31 +0,0 @@ - - -{#if $pluginEditors.length} -
- {#each $pluginEditors as view (view.key)} -
- - closePluginEditor(view.key)} /> -
- {/each} -
-{/if} - - diff --git a/src/lib/plugins/PluginSettings.svelte b/src/lib/plugins/PluginSettings.svelte new file mode 100644 index 0000000..03b8d32 --- /dev/null +++ b/src/lib/plugins/PluginSettings.svelte @@ -0,0 +1,23 @@ + +{#if error}{/if} +
+ diff --git a/src/lib/plugins/PluginTools.svelte b/src/lib/plugins/PluginTools.svelte index a849fbd..5841ee5 100644 --- a/src/lib/plugins/PluginTools.svelte +++ b/src/lib/plugins/PluginTools.svelte @@ -1,9 +1,7 @@ -{#if $pluginTools.length} -
- menu = !menu} /> - {#if menu} -
- {#each $pluginTools as tool (`${tool.owner}:${tool.kind}:${tool.id}`)} - - {/each} -
- {/if} -
-{/if} {#if error && $pluginView?.placement !== "dialog"}{/if} {#if $pluginView?.placement === "dialog"} { event.preventDefault(); pluginView.set(null); }}> @@ -50,11 +31,6 @@ {/if} diff --git a/src/lib/ui/actionIcons.ts b/src/lib/ui/actionIcons.ts index 2ad74fd..77e19b2 100644 --- a/src/lib/ui/actionIcons.ts +++ b/src/lib/ui/actionIcons.ts @@ -1,5 +1,9 @@ // Stroke icons share the same 24px grid and weight as IconButton. export const actionIcons = { + globe: '', + puzzle: '', + 'split-right': '', + 'split-down': '', kanban: '', bookmark: '', 'file-plus': '', diff --git a/src/lib/workspace/documents.ts b/src/lib/workspace/documents.ts index cc7d258..9b1f514 100644 --- a/src/lib/workspace/documents.ts +++ b/src/lib/workspace/documents.ts @@ -76,6 +76,7 @@ export class Documents { const index = this.buffers.indexOf(previous); const opened = this.buffers.find(b => b.relPath === entry.rel_path); if (index !== -1 && opened) { + opened.tabId = previous.tabId ?? previous.id; this.buffers = this.buffers.filter(b => b !== opened); this.buffers.splice(this.buffers.indexOf(previous), 1, opened); } diff --git a/src/lib/workspace/splitLayout.ts b/src/lib/workspace/splitLayout.ts new file mode 100644 index 0000000..fc64eca --- /dev/null +++ b/src/lib/workspace/splitLayout.ts @@ -0,0 +1,25 @@ +export type SplitLayout = string | { direction: "right" | "down"; first: SplitLayout; second: SplitLayout }; +export type PaneBounds = { left: number; top: number; width: number; height: number }; + +export function containsPane(tree: SplitLayout, key: string): boolean { + return typeof tree === "string" ? tree === key : containsPane(tree.first, key) || containsPane(tree.second, key); +} + +export function splitPane(tree: SplitLayout, key: string, next: string, direction: "right" | "down"): SplitLayout { + if (typeof tree === "string") return tree === key ? { direction, first: tree, second: next } : tree; + return { ...tree, first: splitPane(tree.first, key, next, direction), second: splitPane(tree.second, key, next, direction) }; +} + +export function removePane(tree: SplitLayout, key: string): SplitLayout | null { + if (typeof tree === "string") return tree === key ? null : tree; + const first = removePane(tree.first, key), second = removePane(tree.second, key); + return first === null ? second : second === null ? first : { ...tree, first, second }; +} + +export function paneBounds(tree: SplitLayout, bounds: PaneBounds = { left: 0, top: 0, width: 100, height: 100 }): Record { + if (typeof tree === "string") return { [tree]: bounds }; + const a = { ...bounds }, b = { ...bounds }; + if (tree.direction === "right") { a.width /= 2; b.width /= 2; b.left += a.width; } + else { a.height /= 2; b.height /= 2; b.top += a.height; } + return { ...paneBounds(tree.first, a), ...paneBounds(tree.second, b) }; +} diff --git a/src/lib/workspace/tabActions.ts b/src/lib/workspace/tabActions.ts index faa2033..4e69334 100644 --- a/src/lib/workspace/tabActions.ts +++ b/src/lib/workspace/tabActions.ts @@ -2,7 +2,7 @@ import type { OpenBuffer } from "./types"; export type TabCloseScope = "one" | "others" | "after" | "all"; -export function tabsToClose(tabs: OpenBuffer[], path: string, scope: TabCloseScope): OpenBuffer[] { +export function tabsToClose>(tabs: T[], path: string, scope: TabCloseScope): T[] { const index = tabs.findIndex(tab => tab.relPath === path); if (index < 0) return []; if (scope === "one") return [tabs[index]]; diff --git a/src/lib/workspace/types.ts b/src/lib/workspace/types.ts index 20cdad4..9d4e705 100644 --- a/src/lib/workspace/types.ts +++ b/src/lib/workspace/types.ts @@ -22,6 +22,7 @@ export type WorkspaceEvent = { export type OpenBuffer = { id: string; + tabId?: string; relPath: string; name: string; contents: string; diff --git a/src/lib/workspace/workbenchTabs.ts b/src/lib/workspace/workbenchTabs.ts new file mode 100644 index 0000000..ab03641 --- /dev/null +++ b/src/lib/workspace/workbenchTabs.ts @@ -0,0 +1,27 @@ +import type { IconName } from "../ui/IconButton.svelte"; + +export type WorkbenchTab = { + id: string; + relPath: string; + name: string; + title: string; + dirty?: boolean; + pinned?: boolean; + draggable?: boolean; + icon?: IconName; + iconImage?: string | null; + panelId?: string; +}; + +export function orderWorkbenchTabs(tabs: T[], order: string[]): T[] { + const remaining = new Map(tabs.map(tab => [tab.id, tab])); + const ordered: T[] = []; + for (const id of order) { + const tab = remaining.get(id); + if (tab) { + ordered.push(tab); + remaining.delete(id); + } + } + return [...ordered, ...remaining.values()]; +} diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 87160ce..347f499 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -3,13 +3,17 @@ import { onMount } from "svelte"; import { getCurrentWindow } from "@tauri-apps/api/window"; import Workbench from "$lib/layout/Workbench.svelte"; + import BrowserWindow from "$lib/layout/BrowserWindow.svelte"; + import SettingsWindow from "$lib/layout/SettingsWindow.svelte"; import TerminalSlot from "$lib/plugins/TerminalSlot.svelte"; import { pluginHost } from "$lib/plugins/registry"; const terminalRoot = new URLSearchParams(location.search).get("terminalWindow"); + const browserWindow = new URLSearchParams(location.search).get("browserWindow") === "true"; + const settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true"; let dock: TerminalSlot | undefined = $state(); let error = $state(""); const terminal = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); }); - onMount(startExternalPlugins); + onMount(() => startExternalPlugins(browserWindow ? ["runestone.browser"] : undefined)); function keydown(event: KeyboardEvent) { if (!terminalRoot || event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return; const action = terminal?.shortcut(event); @@ -27,5 +31,7 @@ {/key} {:else}

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

{/if}
+{:else if browserWindow} +{:else if settingsWindow} {:else}{/if}