Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+4
View File
@@ -16,8 +16,12 @@ src-tauri/gen
/plugin-packages/ /plugin-packages/
src-tauri/browser-engine/ src-tauri/browser-engine/
/browser-runtime/dist/
/browser-runtime/output/
output/browser-installer-build.log output/browser-installer-build.log
output/browser-test.conf.json output/browser-test.conf.json
# Local workspace settings and project data # Local workspace settings and project data
/.runestone/ /.runestone/
/output/
+31 -5
View File
@@ -18,7 +18,8 @@ Keep unresolved work In progress. Do not start blocked cards or cards outside th
Apply this policy to RuneStone and its plugins. Each project keeps its own version number. 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. 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. Increase `xx` once for each new completed regular build. The number has no two-digit limit.
For a hotfix build, keep `zz.yy.xx` and increase only its lowercase letter suffix.
Keep the current version during source edits, fixes, improvements, documentation work, and automated checks. 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. 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. Development servers, test runs, and intermediate compilation output do not count as new builds.
@@ -31,10 +32,16 @@ Increase `zz` only for a full release, with user direction. Reset `yy` and `xx`
Passing automated checks alone does not authorize a `yy` or `zz` increase. 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. 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`. A hotfix fixes a single item or a narrowly scoped problem in an existing release.
Where packaging requires numeric versions, use letters in release labels or tags until that package format supports suffixes. Use lowercase letter suffixes as the actual hotfix version, such as `0.2.28a` and `0.2.28b`.
For those packages, increase `xx` for each changed hotfix build and record its numeric version in the release notes. Advance hotfix suffixes in this order: `a`, `b`, `c`, through `z`, then `aa`, `ab`, and later suffixes.
The current plugin contract requires numeric versions in `plugin.json`. Do not bypass its validator or overwrite an existing release ZIP. The next regular build increases `xx` and removes the suffix.
Use the same hotfix version in `package.json`, `plugin.json`, build metadata, ZIP names, release notes, and tags.
For installer toolchains that require numeric or SemVer fields, use the reversible encoding in [the build guide](docs/builds.md#hotfix-installer-versions).
Keep the literal hotfix version in release metadata, visible version strings, and artifact names.
Do not substitute a numeric build increment for a hotfix suffix.
If a package format rejects the suffix, add support or report the blocker before building.
Do not bypass validation or overwrite an existing release ZIP.
See [versioning for plugin authors and agents](docs/plugins.md#versioning-for-plugin-authors-and-agents) for the package guidance. See [versioning for plugin authors and agents](docs/plugins.md#versioning-for-plugin-authors-and-agents) for the package guidance.
@@ -166,3 +173,22 @@ Use quiet active states. Reserve strong borders and accents for controls that ne
Show board and view names once where possible. Keep switching and renaming as separate actions. Show board and view names once where possible. Keep switching and renaming as separate actions.
Use familiar icons and visual previews. Keep labels when they prevent ambiguity. Use familiar icons and visual previews. Keep labels when they prevent ambiguity.
Keep accessible names, keyboard focus, and tooltips on icon controls. Keep accessible names, keyboard focus, and tooltips on icon controls.
Keep optional forms hidden until needed. Let users collapse sections and hide panes to focus on their work.
Before adding a control, check the shared component and examples in `docs/ui-design.md`.
## UI work: record design decisions
Use [Interface design](docs/ui-design.md) as the current design reference for the app and its plugins.
Use the [design decision log](docs/design-decisions.md) for rule changes, recurring problems, and exceptions.
- For an isolated correction, keep the normal card or commit record. Do not add a design entry.
- For a rule change, update the guide and add a rule-change entry in the same change.
Record the reason, scope, shared component or token, and evidence. The number of affected controls does not determine the category.
- For a recurring problem, link the occurrences and record the cause and prevention check.
Mark an unknown cause as unknown. Update an existing entry for the same problem instead of adding duplicate entries.
Clarify the guide only when its rule is missing or unclear.
- For an exception, record the user benefit, exact scope, and review date or trigger.
Link the exception from the relevant guide section. An entry does not authorize a departure from the current rule.
- Before moving UI work to Review, include the evidence required by the guide.
Identify the shared component or token, check local overrides, and record any gaps in checks.
Check design principles as well as styling. Keep unresolved work In progress and reserve Done for the user's acceptance.
+11 -1
View File
@@ -1,3 +1,14 @@
---
runestone_pm:
schema: 1
id: 66c0769c-c13e-417d-826e-4ae112dc6f55
kind: task
status: todo
tags: []
sessions: []
archived: true
placements: {}
---
# RuneStone # RuneStone
A desktop workspace for notes, code, and project work stored in ordinary local files. A desktop workspace for notes, code, and project work stored in ordinary local files.
@@ -31,7 +42,6 @@ The installer needs no developer tools. It downloads WebView2 if that runtime is
Keep workspace folders outside the application folder. Keep workspace folders outside the application folder.
[Installation and updates](docs/installation.md) covers Windows setup and experimental Linux and macOS source setup. [Installation and updates](docs/installation.md) covers Windows setup and experimental Linux and macOS source setup.
[Release history](docs/releases.md) records the local test builds and their acceptance limits.
## Find help ## Find help
+12
View File
@@ -0,0 +1,12 @@
# Third-party notices
EasyList and EasyPrivacy are by [the EasyList authors](https://easylist.to/).
The bundled text files are unchanged snapshots from their published endpoints. Their headers retain authorship and version information.
This project uses those lists under [Creative Commons Attribution-ShareAlike 3.0](https://creativecommons.org/licenses/by-sa/3.0/).
See the [EasyList license page](https://easylist.to/pages/licence.html) and assets/filters/manifest.json for the source and download record.
Ghostery's filter engine uses the Mozilla Public License 2.0. The unmodified dependency retains its license and copyright notices.
Its license text is included in licenses/MPL-2.0.txt. Source is available from https://github.com/ghostery/adblocker.
Electron and Chromium notices accompany the packaged runtime. Other dependencies retain their license files in node_modules.
No project-wide distribution license is selected by this prototype.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
{
"fetchedAt": "2026-10-06T16:29:07.621Z",
"lists": [
[
"easylist.txt",
"https://easylist.to/easylist/easylist.txt"
],
[
"easyprivacy.txt",
"https://easylist.to/easylist/easyprivacy.txt"
]
]
}
+64
View File
@@ -0,0 +1,64 @@
# Browser architecture
The interface lives in `../../src/lib/browser/`. The native bridge lives in `../../src-tauri/src/browser.rs`.
This directory contains the runtime, bundled filter lists, licenses, and tests.
Electron runs in its own process, with a separate dependency lock.
Run `npm ci` in this directory to install the runtime dependencies.
Run `npm run package` and `npm run stage:host` to prepare the resource for a host installer.
No Browser plugin ZIP or sibling checkout is required.
## Page isolation
Each page has a sandboxed renderer without Node integration or a preload bridge.
Website scripts never execute inside the privileged RuneStone webview.
The native bridge accepts a fixed command list. It rejects executable paths, arbitrary JavaScript, and shell commands.
RuneStone authenticates the runtime through a temporary loopback listener and a random environment token.
The runtime removes that token before it creates pages. The listener closes after authentication.
The established connection carries commands, state, and frames. No external debugger or agent server is enabled.
The bridge checks the window session and tab ownership. It limits message sizes and routes events to the owner.
## Frames and input
Chromium paints at up to 60 FPS. JPEG frames reduce encoding and transport costs during motion.
A lossless PNG follows after the page stops changing. At most two frames await host acknowledgment.
Acknowledgments follow image decoding. Expired acknowledgments allow recovery after a view closes or moves.
Hidden tabs stop painting. The encoder skips work while the transport is busy.
The viewport uses the host pixel ratio. Device emulation keeps CSS dimensions while the offscreen window supplies physical pixels.
Pointer coordinates and wheel distances use the same scale. Native window rounding can add one or two image pixels.
The host coalesces pointer motion and wheel bursts. A reversed wheel direction replaces pending motion in the old direction.
Middle-button scrolling uses a dead zone and a speed based on distance.
Escape, another click, focus loss, and drag release stop it.
The host orders button and keyboard events. Text insertion accepts Unicode and composition text.
Clipboard shortcuts use native editing commands. Page menus use the shared RuneStone menu components.
Image and link downloads require a user menu action. Each menu has a token tied to its tab and document.
Downloads use the Chromium session and a native save dialog. Other downloads remain blocked.
## Profiles and tabs
A fresh store contains one User profile. New profiles start blank unless the user requests a copy.
Duplication stops the runtime before it copies the persistent partition. It then restores the tabs.
Cookies, site data, history, and bookmarks survive the copy. Later changes remain separate.
Profile names carry no special authority. Copies do not inherit agent grants.
The application data path remains unchanged. Old profiles and settings remain available.
Each tab belongs to one RuneStone window. A transfer token moves a live tab between windows.
Split panes open independent tabs with the same URL and profile. Find uses Chromium match counts and selection.
## Network and filters
Each profile uses an authenticated local proxy. The proxy resolves public destinations and pins the validated address.
It rejects private addresses. HTTPS retains certificate validation. A proxy failure has no direct network fallback.
QUIC is disabled. WebRTC disables non-proxied UDP. These controls do not constitute a VPN.
A bounded worker loads EasyList, EasyPrivacy, subscriptions, and personal rules through the Ghostery parser.
Missing filters block requests when ad blocking is enabled. Scriptlets and extended cosmetic selectors remain disabled.
Basic cosmetic filtering runs after the main frame loads. Dynamic-frame coverage still needs work.
## Remaining limits
Webpage screen-reader access, Linux execution, update delivery, and full media compatibility need separate acceptance checks.
Per-tab VPN tunnels remain unimplemented. Agent observation uses scoped grants, but external agent control is not connected.
+22
View File
@@ -0,0 +1,22 @@
# Browser status
The interface, runtime, tests, filters, and licenses live in the RuneStone repository.
The former Browser repository is no longer a build dependency.
| Capability | State |
| --- | --- |
| Delivery | Built into RuneStone, with an isolated Chromium process |
| Interface | Editor tabs, Bookmarks, Settings, split panes, and separate windows |
| Profiles | Default User profile, blank profiles, and independent copies |
| Page input | Pointer input, wheel scrolling, middle-button scrolling, text, clipboard shortcuts, and composition text |
| Page menus | Navigation, Find, editing, image copy and save, and link copy, save, and open |
| Rendering | Up to 60 FPS, bounded frame delivery, high-DPI pixels, and lossless still frames |
| Filters | Default lists, custom subscriptions, personal rules, and basic cosmetic filtering |
| Web data | Profile cleanup, cookie removal, and history removal |
| Agent support | Scoped observation. No external model connection or action tools |
| VPN | Not implemented |
| Accessibility | Webpage content still lacks a screen-reader bridge |
| Linux | Runtime execution requires a separate acceptance check |
The tests use temporary profiles. Native host tests require the isolated identity in `test/runestone.conf.json`.
The performance and interaction reports state the viewport, frame rate, and checks that ran.
+375
View File
@@ -0,0 +1,375 @@
Copyright (c) 2017-present Ghostery GmbH. All rights reserved.
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
+1079
View File
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
{
"name": "runestone-browser",
"version": "0.1.7",
"private": true,
"description": "Isolated browser runtime included with RuneStone",
"type": "module",
"main": "src/engine-main.mjs",
"engines": {
"node": ">=24"
},
"scripts": {
"setup": "node node_modules/electron/install.js",
"stage:host": "node scripts/stage-host.mjs",
"test": "node --test test/*.test.mjs",
"test:browser": "node scripts/test-engine.mjs",
"test:packaged": "node scripts/test-engine.mjs --packaged",
"test:protocol": "node scripts/test-protocol.mjs",
"test:native": "node scripts/test-native.mjs",
"test:tab-actions": "node scripts/test-tab-actions.mjs",
"test:idle": "node scripts/test-idle.mjs",
"check": "node scripts/check.mjs",
"filters:update": "node scripts/update-filters.mjs",
"package": "node scripts/package.mjs",
"package:windows": "npm run package -- --platform=win32 --arch=x64",
"package:linux": "npm run package -- --platform=linux --arch=x64",
"test:performance": "node test/performance-smoke.mjs"
},
"dependencies": {
"@ghostery/adblocker": "2.18.2",
"ipaddr.js": "2.3.0"
},
"devDependencies": {
"@electron/packager": "20.3.0",
"@tauri-apps/api": "2.11.1",
"electron": "44.5.1",
"playwright": "1.63.0",
"svelte": "5.57.1"
}
}
+14
View File
@@ -0,0 +1,14 @@
import { readdir } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
async function check(directory) {
for (const item of await readdir(directory, { withFileTypes: true })) {
const file = `${directory}/${item.name}`;
if (item.isDirectory()) await check(file);
else if (/\.(mjs|cjs)$/.test(file)) {
const result = spawnSync(process.execPath, ['--check', file], { stdio: 'inherit' });
if (result.status !== 0) process.exit(result.status || 1);
}
}
}
for (const directory of ['src', 'scripts', 'test']) await check(directory);
console.log('JavaScript syntax checks passed.');
@@ -0,0 +1,12 @@
const sessions = new WeakMap();
export async function nativeRequest(page, command, args = {}) {
const invoke = (name, value) => page.evaluate(({ name, value }) => window.__TAURI_INTERNALS__.invoke(name, value), { name, value });
if (command === 'browser_request') {
let session = sessions.get(page);
if (!session) { session = await invoke('browser_connect', {}); sessions.set(page, session); }
return invoke(command, { ...args, session });
}
if (command === 'browser_stop') sessions.delete(page);
return invoke(command, args);
}
+12
View File
@@ -0,0 +1,12 @@
import { packager } from '@electron/packager';
const options = Object.fromEntries(process.argv.slice(2).map(arg => {
const match = /^--(platform|arch)=(win32|linux|x64|arm64)$/.exec(arg);
if (!match) throw new Error('Use --platform=win32|linux and --arch=x64|arm64.');
return [match[1], match[2]];
}));
const outputs = await packager({
dir: '.', name: 'RuneStone-Browser', out: 'dist', overwrite: true,
platform: options.platform || process.platform, arch: options.arch || process.arch,
ignore: [/^\/(test|scripts|output|plugin|releases|\.github)(\/|$)/, /^\/src\/(ui\/|host\.mjs|main\.mjs|preload\.cjs)/],
});
for (const output of outputs) console.log(output);
+11
View File
@@ -0,0 +1,11 @@
import { cp, mkdir, access } from 'node:fs/promises';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const project = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const host = resolve(process.env.RUNESTONE_ROOT || resolve(project, '..'));
const source = resolve(project, `dist/RuneStone-Browser-${process.platform}-${process.arch}`);
await access(resolve(source, process.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser'));
const destination = resolve(host, 'src-tauri/browser-engine');
await mkdir(destination, { recursive: true });
await cp(source, destination, { recursive: true });
console.log(`Browser runtime staged in ${destination}`);
+39
View File
@@ -0,0 +1,39 @@
import { spawn } from 'node:child_process';
import { mkdtemp, readFile, cp } from 'node:fs/promises';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import electron from 'electron';
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-plugin-browser-'));
const server = http.createServer((req, res) => {
if (req.url === '/picture.png') {
res.writeHead(200, { 'Content-Type': 'image/png' });
return res.end(Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64'));
}
if (req.url === '/slow') return;
if (req.url === '/icon.svg') {
res.writeHead(200, { 'Content-Type': 'image/svg+xml' });
return res.end('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="red"/></svg>');
}
if (req.url === '/favicon.ico') { res.writeHead(404); return res.end(); }
if (req.url === '/no-icon') return res.end('<!doctype html><title>No icon</title>');
if (req.url === '/with-icon') return res.end('<!doctype html><title>Icon fixture</title><link rel="icon" href="/icon.svg">');
res.writeHead(200, { 'Content-Type': req.url.endsWith('.js') ? 'text/javascript' : 'text/html', 'Cache-Control': 'no-store' });
res.end(req.url.endsWith('.js') ? 'window.adExecuted=true;' : '<!doctype html><title>Browser fixture</title><input style="position:absolute;left:20px;top:20px;width:200px;height:30px"><p class="advertisement">Ad</p><p style="margin-top:80px">Runestone needle. Runestone needle. Runestone needle.</p><script src="/blocked-ad.js"></script>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
async function phase(name, plan) {
const child = spawn(electron, ['test/engine-smoke.mjs'], { stdio: 'inherit', windowsHide: true,
env: { ...process.env, RS_TEST_ROOT: directory, RS_TEST_URL: `http://127.0.0.1:${server.address().port}/`, RS_TEST_PHASE: name, RS_TEST_PLAN: JSON.stringify(plan || {}),
...(process.argv.includes('--packaged') ? { RUNESTONE_TEST_PACKAGE: path.resolve(`dist/RuneStone-Browser-${process.platform}-${process.arch}/resources/app.asar`) } : {}) } });
const timer = setTimeout(() => child.kill(), 60_000);
const code = await new Promise((resolve, reject) => { child.once('exit', resolve); child.once('error', reject); }); clearTimeout(timer);
const result = JSON.parse(await readFile(`output/engine-${name}.json`, 'utf8'));
if (code !== 0 || result.exitCode !== 0) throw new Error(`Engine ${name} checks failed.`);
}
try {
await phase('initial');
const plan = JSON.parse(await readFile(path.join(directory, 'clone-plan.json'), 'utf8'));
await cp(path.join(directory, 'Partitions', `runestone-${plan.sourceId}`), path.join(directory, 'Partitions', `runestone-${plan.id}`), { recursive: true });
await phase('restore', plan);
} finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)); }
+88
View File
@@ -0,0 +1,88 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const listener = net.createServer();
await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve));
const port = listener.address().port;
await new Promise(resolve => listener.close(resolve));
const native = spawn(resolve('../src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let browser, page;
const passed = [];
const idle = () => new Promise(resolve => setTimeout(resolve, 2200));
try {
for (let attempt = 0; attempt < 60; attempt++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, 'The isolated test window must start.');
page = browser.contexts()[0].pages()[0];
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
let snapshot = await invoke('plugins_snapshot');
assert.equal(basename(dirname(snapshot.root)), 'com.runestone.browser-test');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const current = () => page.locator('.browser:visible');
const ready = () => page.waitForFunction(() => {
const view = [...document.querySelectorAll('.browser')].find(view => view.getBoundingClientRect().width > 0);
return view?.dataset.browserState === 'ready';
});
await ready();
const original = await current().getAttribute('data-browser-tab');
await idle();
const afterIdle = await invoke('browser_request', { command: 'state', args: {} });
assert.ok(afterIdle.tabs.some(tab => tab.id === original), `An idle connection must keep its original tab: ${JSON.stringify({ original, tabs: afterIdle.tabs, diagnostics: await page.locator('.diagnostics').allTextContents() })}`);
passed.push('the idle connection stays open beyond the authentication timeout');
console.log(`PASS ${passed.at(-1)}`);
for (let index = 0; index < 2; index++) {
await current().getByRole('button', { name: 'New browser tab', exact: true }).click();
await ready();
}
const ids = await page.locator('.browser').evaluateAll(views => views.map(view => view.dataset.browserTab).sort());
assert.equal(ids.length, 3);
for (let index = 0; index < 9; index++) {
await page.locator('.plugin-tab [role="tab"], [role="tab"][data-path^="plugin:"]').nth(index % 3).click();
await ready();
await idle();
const state = await invoke('browser_request', { command: 'state', args: {} });
assert.deepEqual(state.tabs.map(tab => tab.id).sort(), ids, 'Tab switches must not restart the browser.');
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
}
passed.push('nine tab switches and idle periods preserve all three runtime tabs');
console.log(`PASS ${passed.at(-1)}`);
const address = current().getByRole('textbox', { name: 'Address or search', exact: true });
await address.fill('https://example.com/');
await address.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('.browser input')].some(input => input.value === 'https://example.com/' && !input.disabled));
await current().getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
const bookmark = page.locator('.bookmarks .link[title="https://example.com/"]').first();
await bookmark.waitFor();
await idle();
await bookmark.click();
await ready();
await idle();
const finalState = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(finalState.tabs.length, 4);
assert.ok(ids.every(id => finalState.tabs.some(tab => tab.id === id)));
const opened = await current().getAttribute('data-browser-tab');
assert.equal(finalState.tabs.find(tab => tab.id === opened)?.url, 'https://example.com/');
passed.push('a bookmark opens after idle without replacing existing tabs');
console.log(`PASS ${passed.at(-1)}`);
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/browser-idle.png' });
await writeFile('output/browser-idle.json', JSON.stringify({ passed }, null, 2));
} catch (error) {
if (page) console.error(await page.locator('.diagnostics').allTextContents());
throw error;
} finally { await browser?.close().catch(() => {}); native.kill(); }
+119
View File
@@ -0,0 +1,119 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
if (process.platform !== 'win32') throw new Error('This native smoke test uses Windows WebView2.');
const host = resolve(process.env.RUNESTONE_ROOT || '..');
const portServer = net.createServer(); await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve));
const port = portServer.address().port; await new Promise(resolve => portServer.close(resolve));
const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], { windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` } });
let browser, page;
const passed = [];
try {
for (let attempt = 0; attempt < 60; attempt++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
if (!browser) throw new Error('The isolated RuneStone test window did not start.');
const context = browser.contexts()[0];
page = context.pages()[0];
if (!page) page = await context.waitForEvent('page');
page.setDefaultTimeout(30_000);
const errors = []; page.on('pageerror', error => errors.push(error.message));
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
let snapshot = await invoke('plugins_snapshot');
const pluginRoot = resolve(snapshot.root);
assert.equal(basename(pluginRoot), 'plugins');
assert.equal(basename(dirname(pluginRoot)), 'com.runestone.browser-test', 'Never modify a real RuneStone profile.');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
const initial = await invoke('browser_request', { command: 'state', args: {} });
await invoke('browser_request', { command: 'settings', args: { ...initial.settings, homepage: '', adblock: true, linkDestination: 'internal' } });
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/runestone-browser-splash.png' });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const address = page.getByRole('textbox', { name: 'Address or search', exact: true });
await address.waitFor();
await page.locator('.surface img').waitFor();
const state = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(state.profiles[0].name, 'User'); assert.ok(!state.profiles.some(item => item.id === 'agent'));
assert.equal(state.tabs[0].url, 'about:blank');
passed.push('browser opens inside the RuneStone editor with a User profile');
await address.fill('https://example.com/'); await address.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('[role=tab]')].some(tab => /Example|example/i.test(tab.textContent)), { timeout: 30_000 });
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/runestone-browser-internal.png' });
passed.push('a public HTTPS page renders inside the native RuneStone window');
await page.getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
await page.locator('.bookmarks .link').first().waitFor();
passed.push('web bookmarks appear in the existing Bookmarks pane');
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await page.getByRole('button', { name: 'Browser', exact: true }).click();
const settings = page.getByRole('dialog', { name: 'Settings', exact: true });
await settings.getByRole('button', { name: 'New blank profile', exact: true }).waitFor();
const adblockSwitch = settings.getByRole('switch', { name: 'Block ads and trackers', exact: true });
const linkSwitch = settings.getByRole('switch', { name: 'Open web links in RuneStone', exact: true });
await adblockSwitch.uncheck(); await linkSwitch.uncheck();
await settings.getByRole('textbox', { name: 'Homepage', exact: true }).fill('https://example.com/');
const lists = settings.getByRole('textbox', { name: 'Ad blocking lists', exact: true });
assert.match(await lists.inputValue(), /easylist\.txt/);
await lists.fill('https://easylist.to/easylist/easylist.txt');
await settings.getByRole('button', { name: 'Save browser settings', exact: true }).click();
await settings.getByText('Changes saved.', { exact: true }).waitFor();
let saved = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(saved.settings.homepage, 'https://example.com/');
assert.equal(saved.settings.linkDestination, 'external');
assert.equal(saved.settings.adblock, false);
assert.deepEqual(saved.settings.filterLists, ['https://easylist.to/easylist/easylist.txt']);
assert.equal(await adblockSwitch.evaluate(node => getComputedStyle(node).appearance), 'none');
await adblockSwitch.focus(); await page.keyboard.press('Space');
assert.equal(await adblockSwitch.isChecked(), true);
await settings.getByRole('button', { name: 'Save browser settings', exact: true }).click();
await settings.getByText('Changes saved.', { exact: true }).waitFor();
await settings.getByRole('textbox', { name: 'Homepage', exact: true }).scrollIntoViewIfNeeded();
await page.screenshot({ path: 'output/runestone-browser-settings.png' });
await page.evaluate(() => document.documentElement.dataset.theme = 'light');
await page.screenshot({ path: 'output/runestone-browser-settings-light.png' });
await page.evaluate(() => document.documentElement.dataset.theme = 'dark');
await page.keyboard.press('Escape');
await settings.waitFor({ state: 'detached' });
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await page.waitForFunction(() => [...document.querySelectorAll('[role=tab]')].filter(tab => /Example|example/i.test(tab.textContent)).length >= 2);
saved = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(saved.tabs.at(-1).url, 'https://example.com/');
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.waitForFunction(() => document.querySelector('input[aria-label="Homepage"]')?.value === 'https://example.com/');
assert.equal(await settings.getByRole('textbox', { name: 'Homepage', exact: true }).inputValue(), 'https://example.com/');
assert.equal(await linkSwitch.isChecked(), false);
passed.push('splash launch, sliding switches, filter-list edits and homepage persist and work in the native app');
const profileName = settings.getByRole('textbox', { name: 'New profile name', exact: true });
const suffix = Date.now().toString().slice(-6);
const research = `Research ${suffix}`, copy = `User copy ${suffix}`;
await profileName.fill(research); await settings.getByRole('button', { name: 'New blank profile', exact: true }).click();
await page.waitForFunction(name => [...document.querySelectorAll('.settings option')].some(option => option.textContent === name), research);
await settings.getByLabel('Profile', { exact: true }).selectOption('user');
await profileName.fill(copy); await settings.getByRole('button', { name: 'Duplicate profile', exact: true }).click();
await page.waitForFunction(name => [...document.querySelectorAll('.settings option')].some(option => option.textContent === name), copy);
passed.push('blank and duplicate profile actions work in RuneStone Settings');
assert.equal(await address.last().evaluate(node => getComputedStyle(node).borderRadius), await page.locator('.toolbar .icon-btn').last().evaluate(node => getComputedStyle(node).borderRadius));
passed.push('browser controls share RuneStone corner tokens in both themes');
await invoke('browser_stop');
passed.push('browser cleanup revokes the window session');
assert.deepEqual(errors, []);
await writeFile('output/native-plugin-smoke.json', JSON.stringify({ passed, errors }, null, 2));
for (const name of passed) console.log(`PASS ${name}`);
} catch (error) {
if (page) { await mkdir('output', { recursive: true }); await page.screenshot({ path: 'output/native-failure.png' }).catch(() => {}); console.error(await page.locator('body').innerText().catch(() => '')); }
throw error;
} finally {
if (browser) { await browser.close().catch(() => {}); }
native.kill();
}
+35
View File
@@ -0,0 +1,35 @@
import net from 'node:net';
import { spawn } from 'node:child_process';
import { randomBytes } from 'node:crypto';
import { mkdtemp } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import assert from 'node:assert/strict';
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-protocol-'));
const token = randomBytes(32).toString('hex');
let socket;
const server = net.createServer(client => {
socket = client;
let buffer = '';
client.on('data', bytes => {
buffer += bytes;
let end;
while ((end = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
const message = JSON.parse(line);
if (message.token) { assert.equal(message.token, token); console.log('PASS runtime authentication'); }
if (message.event === 'ready') client.write(JSON.stringify({ id: 1, command: 'state', args: {} }) + '\n');
if (message.id === 1) { assert.deepEqual(message.result.profiles, [{ id: 'user', name: 'User' }]); client.write(JSON.stringify({ id: 2, command: 'newTab', args: {} }) + '\n'); }
if (message.id === 2) { assert.ok(message.result.tabId); console.log('PASS packaged runtime commands'); client.write(JSON.stringify({ id: 3, command: 'shutdown', args: {} }) + '\n'); }
if (message.id === 3) console.log('PASS clean shutdown response');
}
});
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
const executable = path.resolve(`dist/RuneStone-Browser-${process.platform}-${process.arch}/${process.platform === 'win32' ? 'RuneStone-Browser.exe' : 'RuneStone-Browser'}`);
const child = spawn(executable, [`--rs-connect=${server.address().port}`, `--rs-browser-root=${root}`], { windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'], env: { ...process.env, RUNESTONE_BROWSER_TOKEN: token } });
child.stderr.on('data', chunk => process.stderr.write(chunk));
const timer = setTimeout(() => { child.kill(); process.exitCode = 1; }, 15_000);
const code = await new Promise(resolve => child.once('exit', resolve)); clearTimeout(timer);
socket?.destroy(); await new Promise(resolve => server.close(resolve));
assert.equal(code, 0);
+115
View File
@@ -0,0 +1,115 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { execFileSync, spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const listener = net.createServer();
await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve));
const port = listener.address().port;
await new Promise(resolve => listener.close(resolve));
const native = spawn(resolve('../src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: 'ignore',
env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let browser, page;
const passed = [];
try {
for (let i = 0; i < 60; i++) {
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, 'Isolated test window must start.');
page = browser.contexts()[0].pages()[0];
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
const invoke = (command, args = {}) => nativeRequest(page, command, args);
const rendered = () => page.waitForFunction(() => {
const image = document.querySelector('.surface img');
return image?.complete && image.naturalWidth > 0;
});
let snapshot = await invoke('plugins_snapshot');
assert.equal(basename(dirname(snapshot.root)), 'com.runestone.browser-test');
const crashBrowser = () => {
const output = execFileSync('powershell.exe', ['-NoProfile', '-Command',
`Get-CimInstance Win32_Process -Filter "ParentProcessId = ${native.pid} AND Name = 'RuneStone-Browser.exe'" | Select-Object -ExpandProperty ProcessId`],
{ windowsHide: true, encoding: 'utf8' });
const ids = output.trim().split(/\s+/).filter(Boolean).map(Number);
assert.equal(ids.length, 1, 'Only the browser child of the isolated test window can stop.');
assert.ok(Number.isSafeInteger(ids[0]) && ids[0] > 0);
process.kill(ids[0]);
};
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
await invoke('browser_request', { command: 'state', args: {} });
crashBrowser();
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await rendered();
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
passed.push('a new tab opens after the browser process stops without manual reconnect');
await page.getByRole('textbox', { name: 'Address or search', exact: true }).fill('https://example.com/');
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
await page.getByRole('tab', { name: 'Example Domain · User', exact: true }).waitFor();
const before = await invoke('browser_request', { command: 'state', args: {} });
await invoke('browser_stop');
const reset = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(reset.tabs.length, 0);
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
if (process.argv.includes('--expect-broken')) {
await page.getByText('Unknown browser tab.', { exact: true }).waitFor();
passed.push('reproduced Unknown browser tab after a runtime restart');
} else {
await page.waitForFunction(oldId => {
const view = document.querySelector('.browser');
return view?.dataset.browserState === 'ready' && view.dataset.browserTab && view.dataset.browserTab !== oldId;
}, before.tabs[0].id);
await rendered();
await page.waitForFunction(() => document.querySelector('input[aria-label="Address or search"]')?.disabled === false);
const restored = await invoke('browser_request', { command: 'state', args: {} });
assert.equal(restored.tabs.length, 1);
assert.notEqual(restored.tabs[0].id, before.tabs[0].id);
assert.equal(await page.getByText('Unknown browser tab.', { exact: true }).isVisible(), false);
passed.push('the open view reconnects after a runtime restart');
// A repeated failure must stop automatic retries and offer an explicit action.
await invoke('browser_stop');
await invoke('browser_request', { command: 'state', args: {} });
await page.getByRole('textbox', { name: 'Address or search', exact: true }).press('Enter');
await page.getByRole('button', { name: 'Reconnect', exact: true }).waitFor();
await page.getByText('Browser error details', { exact: true }).click();
await page.getByText('Unknown browser tab.', { exact: false }).waitFor();
await page.screenshot({ path: 'output/browser-recovery-details.png' });
await page.getByRole('button', { name: 'Reconnect', exact: true }).click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
passed.push('a repeated failure shows the cause, operation and a working Reconnect action');
// Registered plugin views remain in the host menu after their tabs close.
await page.locator('.plugin-tab .icon-btn').click();
await page.locator('.browser').waitFor({ state: 'detached' });
await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).click();
const tools = page.getByRole('group', { name: 'Plugin commands and views', exact: true }).getByRole('button');
assert.equal(await tools.count(), 2);
await tools.last().click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
passed.push('a closed browser view opens with a fresh runtime tab');
await page.getByRole('button', { name: 'Bookmark this page', exact: true }).click();
await page.getByRole('button', { name: 'Bookmarks', exact: true }).click();
const bookmark = page.locator('.bookmarks .link').filter({ hasText: 'Example Domain' }).first();
await bookmark.waitFor();
crashBrowser();
await bookmark.click();
await page.waitForFunction(() => document.querySelector('.browser')?.dataset.browserState === 'ready');
await rendered();
await page.waitForFunction(() => document.querySelector('input[aria-label="Address or search"]')?.value === 'https://example.com/');
assert.equal(await page.getByRole('button', { name: 'Reconnect', exact: true }).count(), 0);
passed.push('a bookmark opens its saved URL after the browser process stops');
}
await mkdir('output', { recursive: true });
await page.screenshot({ path: 'output/browser-recovery.png' });
await writeFile('output/browser-recovery.json', JSON.stringify({ passed }, null, 2));
passed.forEach(message => console.log(`PASS ${message}`));
} catch (error) {
if (page) { console.error(await page.locator('body').innerText()); console.error(await page.locator('.diagnostics').allTextContents()); await page.screenshot({ path: 'output/browser-recovery-failure.png' }); }
throw error;
} finally { await browser?.close().catch(() => {}); native.kill(); }
@@ -0,0 +1,276 @@
import { nativeRequest } from './native-support.mjs';
import { chromium } from 'playwright';
import { spawn } from 'node:child_process';
import { cp, mkdir, writeFile } from 'node:fs/promises';
import { resolve, basename, dirname } from 'node:path';
import net from 'node:net';
import assert from 'node:assert/strict';
const host = resolve(process.env.RUNESTONE_ROOT || '..');
const portServer = net.createServer();
await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve));
const port = portServer.address().port;
await new Promise(resolve => portServer.close(resolve));
const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], {
windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` },
});
let nativeOutput = '';
for (const stream of [native.stdout, native.stderr]) stream.on('data', chunk => nativeOutput = (nativeOutput + chunk).slice(-8000));
let browser, page;
const passed = [], errors = [];
const ipc = nativeRequest;
const state = page => ipc(page, 'browser_request', { command: 'state', args: {} });
const menuItem = (page, name) => page.getByRole('menuitem', { name: name === 'Find…' ? 'Find… Ctrl+F' : name, exact: true });
const tabs = page => page.locator('.header').getByRole('tab');
async function action(page, tab, name) {
await tab.click({ button: 'right' });
await menuItem(page, name).click();
}
async function ready(page, count) {
await page.waitForFunction(count => [...document.querySelectorAll('.browser[data-browser-state="ready"]')].filter(node => node.getBoundingClientRect().width > 0).length === count, count);
}
async function painted(page, count) {
await page.waitForFunction(count => {
const images = [...document.querySelectorAll('.surface img')].filter(img => img.getBoundingClientRect().width > 0);
return images.length === count && images.every(img => {
const bounds = img.getBoundingClientRect();
return img.naturalHeight > 0 && Math.abs(img.naturalWidth / img.naturalHeight - bounds.width / bounds.height) < 0.02;
});
}, count);
}
async function dragToWindow(context, source, sourceTab, destination) {
const targetSession = await context.newCDPSession(destination);
const before = (await state(source)).tabs.map(tab => tab.id);
await source.evaluate(() => {
window.__tabDragData = undefined;
window.addEventListener('dragstart', event => {
window.__tabDragData = {
items: [...event.dataTransfer.types].map(mimeType => ({ mimeType, data: event.dataTransfer.getData(mimeType) })),
dragOperationsMask: 16,
};
}, { once: true });
});
const bounds = await sourceTab.boundingBox();
await source.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2);
await source.mouse.down();
await source.mouse.move(bounds.x + bounds.width / 2 + 30, bounds.y + bounds.height / 2 + 12, { steps: 5 });
await source.waitForFunction(() => window.__tabDragData?.items.length);
const transfer = await source.evaluate(() => window.__tabDragData);
assert.ok(transfer.items.some(item => item.mimeType === 'application/x-runestone-tab' && item.data));
await source.mouse.up();
assert.deepEqual((await state(source)).tabs.map(tab => tab.id), before, 'A drag without a destination keeps the live tabs.');
const drop = await destination.locator('.header [role="tablist"]').boundingBox();
assert.ok(drop.width > 0 && drop.height > 0);
for (const type of ['dragEnter', 'dragOver', 'drop']) {
await targetSession.send('Input.dispatchDragEvent', { type, x: drop.x + 2, y: drop.y + drop.height / 2, data: transfer });
}
await targetSession.detach();
}
try {
for (let attempt = 0; attempt < 60; attempt++) {
if (native.exitCode !== null) throw new Error(`The test app exited (${native.exitCode}). ${nativeOutput}`);
try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; }
catch { await new Promise(resolve => setTimeout(resolve, 500)); }
}
assert.ok(browser, `The isolated native app must start. ${nativeOutput}`);
const context = browser.contexts()[0];
page = context.pages()[0] || await context.waitForEvent('page');
page.setDefaultTimeout(20000);
page.on('pageerror', error => errors.push(error.message));
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke);
let plugins = await ipc(page, 'plugins_snapshot');
const root = resolve(plugins.root);
assert.equal(basename(dirname(root)), 'com.runestone.browser-test');
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
const initial = await state(page);
await ipc(page, 'browser_request', { command: 'settings', args: { ...initial.settings, homepage: '', linkDestination: 'internal' } });
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await tabs(page).filter({ hasText: 'New tab' }).waitFor();
await action(page, tabs(page).first(), 'Pin');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await ready(page, 1);
assert.equal(await tabs(page).count(), 1);
assert.equal(await page.locator('.header .pin').count(), 1);
await action(page, tabs(page).first(), 'Unpin');
passed.push('Open browser replaces the empty tab and keeps its pin');
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
const emptyPath = await tabs(page).last().getAttribute('data-path');
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
const untouchedPath = await tabs(page).last().getAttribute('data-path');
await page.locator(`.header [role="tab"][data-path="${emptyPath}"]`).click();
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await ready(page, 1);
assert.equal(await tabs(page).count(), 3);
assert.equal(await tabs(page).last().getAttribute('data-path'), untouchedPath);
assert.match(await tabs(page).nth(1).getAttribute('data-path'), /^plugin:/);
await action(page, tabs(page).nth(1), 'Close');
await action(page, tabs(page).last(), 'Close');
assert.equal(await tabs(page).count(), 1);
passed.push('splash replacement keeps the tab position and other empty tabs');
await tabs(page).first().click({ button: 'right' });
assert.equal(await menuItem(page, 'Open in default browser').isDisabled(), true);
assert.equal(await menuItem(page, 'Bookmark').isDisabled(), true);
await page.keyboard.press('Escape');
const address = page.getByRole('textbox', { name: 'Address or search', exact: true });
await address.fill('https://example.com/'); await address.press('Enter');
await page.waitForFunction(() => document.querySelector('.header [role="tab"]')?.textContent.includes('Example'));
const firstId = (await state(page)).tabs[0].id;
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await tabs(page).first().click({ button: 'right' });
for (const label of ['Close', 'Pin', 'Move to new window', 'Split right', 'Split down', 'Find…', 'Open in default browser', 'Bookmark']) {
assert.equal(await menuItem(page, label).isEnabled(), true, label);
assert.equal(await menuItem(page, label).locator('svg').count(), 1, label);
}
await mkdir('output', { recursive: true });
await page.screenshot({ path: `output/browser-tab-menu-${theme}.png` });
await page.keyboard.press('Escape');
}
passed.push('all eight tab actions use the shared menu in both themes');
await action(page, tabs(page).first(), 'Pin');
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await ready(page, 1);
await page.getByRole('button', { name: 'New browser tab', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 3);
await ready(page, 1);
await action(page, tabs(page).last(), 'Close others');
await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2);
assert.equal(await tabs(page).count(), 2);
await action(page, tabs(page).first(), 'Bookmark');
assert.ok((await state(page)).bookmarks.some(bookmark => bookmark.url === 'https://example.com/'));
await action(page, tabs(page).last(), 'Close');
await ready(page, 1);
passed.push('pins survive bulk close and inactive-tab actions target the clicked page');
await page.locator('.surface:visible').focus();
await page.keyboard.press('Control+f');
const find = page.getByRole('textbox', { name: 'Find in page', exact: true });
await find.fill('Learn more');
await page.getByText('1 of 1', { exact: true }).waitFor();
await find.press('Enter');
await find.press('Shift+Enter');
await find.fill('no such phrase exists');
await page.getByText('No matches', { exact: true }).waitFor();
await find.press('Escape');
await find.waitFor({ state: 'detached' });
await address.focus(); await page.keyboard.press('Control+f');
await find.waitFor(); await page.getByText('No matches', { exact: true }).waitFor(); await find.press('Escape');
await action(page, tabs(page).first(), 'Find…');
await find.fill('Learn more');
await page.getByText('1 of 1', { exact: true }).waitFor();
await find.press('Escape');
passed.push('Ctrl+F works from the page and address bar, with counts, navigation, and Escape');
await action(page, tabs(page).first(), 'Split right');
await ready(page, 2);
assert.equal((await state(page)).tabs[0].id, firstId);
const surfaces = page.locator('.surface:visible');
const a = await surfaces.nth(0).boundingBox(), b = await surfaces.nth(1).boundingBox();
assert.ok(b.x > a.x + a.width - 5);
await action(page, tabs(page).last(), 'Split down');
await ready(page, 3);
const c = await surfaces.nth(2).boundingBox(), upper = await surfaces.nth(1).boundingBox();
assert.ok(c.y > upper.y + upper.height - 5);
assert.equal((await state(page)).tabs.length, 3);
await painted(page, 3);
await page.screenshot({ path: 'output/browser-split-panes.png' });
await action(page, tabs(page).last(), 'Close');
await ready(page, 2);
passed.push('nested splits preserve the source tab and closing a pane fills its space');
const movingId = (await state(page)).tabs.find(tab => tab.id !== firstId).id;
await action(page, tabs(page).last(), 'Pin');
const opened = context.waitForEvent('page');
await action(page, tabs(page).last(), 'Move to new window');
const target = await opened;
target.setDefaultTimeout(20000);
target.on('pageerror', error => errors.push(error.message));
await ready(target, 1);
await target.evaluate(async () => {
window.__browserStates = [];
const handler = window.__TAURI_INTERNALS__.transformCallback(event => {
window.__browserStates.push({ revision: event.payload.state?.revision, tabs: event.payload.state?.tabs });
window.__browserStates = window.__browserStates.slice(-5);
});
await window.__TAURI_INTERNALS__.invoke('plugin:event|listen', { event: 'browser-state', target: { kind: 'WebviewWindow', label: window.__TAURI_INTERNALS__.metadata.currentWindow.label }, handler });
});
await ready(page, 1);
assert.equal(await target.getByRole('application', { name: 'RuneStone browser', exact: true }).count(), 1);
assert.equal(await target.getByRole('application', { name: 'RuneStone workbench', exact: true }).count(), 0);
assert.equal(await target.getByRole('button', { name: 'Files', exact: true }).count(), 0);
assert.equal(await target.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).count(), 0);
assert.equal((await state(target)).tabs[0].id, movingId);
assert.equal((await state(page)).tabs.length, 1);
assert.equal((await state(target)).tabs[0].url, 'https://example.com/');
assert.equal(await target.locator('.header .pin').count(), 1);
await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: movingId } }), /another window/);
await target.locator('.surface:visible').focus(); await target.keyboard.press('Control+f');
await target.getByRole('textbox', { name: 'Find in page', exact: true }).fill('Learn more');
await target.getByText('1 of 1', { exact: true }).waitFor();
await target.screenshot({ path: 'output/browser-moved-window.png' });
assert.equal(await tabs(target).first().getAttribute('draggable'), 'true');
const beforeDrop = (await state(target)).tabs[0];
await assert.rejects(ipc(page, 'browser_request', { command: 'adoptTab', args: { tabId: movingId, transferToken: 'invalid-token' } }), /valid transfer/);
const updates = await target.evaluate(() => window.__browserStates);
assert.ok(updates.length > 0 && updates.every(update => update.tabs.every(tab => tab.id === movingId)));
const closed = target.waitForEvent('close');
await dragToWindow(context, target, tabs(target).first(), page);
await closed;
await ready(page, 1);
await page.waitForFunction(() => document.querySelectorAll('.browser[data-browser-state="ready"]').length === 2);
const returned = (await state(page)).tabs.find(tab => tab.id === movingId);
assert.equal(returned.url, beforeDrop.url);
assert.equal(returned.profileId, beforeDrop.profileId);
assert.equal(returned.canBack, beforeDrop.canBack);
assert.equal(returned.canForward, beforeDrop.canForward);
assert.notEqual(returned.transferToken, beforeDrop.transferToken);
assert.equal(await page.locator('.header .tab').first().locator('.pin').count(), 1);
assert.equal(await page.locator('.browser:visible').getAttribute('data-browser-tab'), movingId);
assert.equal((await state(page)).tabs.length, 2);
await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: 'missing-tab' } }), /Unknown browser tab/);
await painted(page, 1);
await page.screenshot({ path: 'output/browser-returned-tab.png' });
passed.push('the browser-only window returns its live tab by drag and closes when empty');
await action(page, tabs(page).first(), 'Close');
assert.equal((await state(page)).tabs[0].id, firstId);
const another = context.waitForEvent('page');
await action(page, tabs(page).first(), 'Move to new window');
const secondWindow = await another;
secondWindow.setDefaultTimeout(20000);
secondWindow.on('pageerror', error => errors.push(error.message));
await ready(secondWindow, 1);
assert.equal(await tabs(page).count(), 0);
await secondWindow.locator('.surface:visible').focus();
await secondWindow.keyboard.press('Control+t');
await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2);
await ready(secondWindow, 1);
await dragToWindow(context, secondWindow, tabs(secondWindow).first(), page);
await ready(page, 1);
await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 1);
assert.equal((await state(page)).tabs[0].id, firstId);
assert.equal((await state(secondWindow)).tabs.length, 1);
const secondClosed = secondWindow.waitForEvent('close');
await secondWindow.keyboard.press('Control+w');
await secondClosed;
assert.equal((await state(page)).tabs[0].id, firstId);
passed.push('an empty RuneStone tab bar accepts a tab, and the source window keeps its remaining tab');
await action(page, tabs(page).first(), 'Close');
await page.waitForFunction(() => !document.querySelector('.browser'));
assert.equal((await state(page)).tabs.length, 0);
assert.deepEqual(errors, []);
await writeFile('output/browser-tab-actions.json', JSON.stringify({ passed, errors }, null, 2));
for (const label of passed) console.log(`PASS ${label}`);
} catch (error) {
for (const current of browser?.contexts()[0]?.pages() || []) {
if (current !== page) {
console.error(await current.locator('body').innerText().catch(() => ''));
console.error(JSON.stringify((await state(current).catch(() => ({ tabs: [] }))).tabs));
console.error(JSON.stringify(await current.evaluate(() => window.__browserStates).catch(() => [])));
await current.screenshot({ path: 'output/browser-window-failure.png' }).catch(() => {});
}
}
if (page) { await mkdir('output', { recursive: true }); await page.screenshot({ path: 'output/browser-tab-actions-failure.png' }).catch(() => {}); console.error(await page.locator('body').innerText().catch(() => '')); }
throw error;
} finally {
if (page) await ipc(page, 'browser_stop').catch(() => {});
if (browser) await browser.close().catch(() => {});
native.kill();
}
@@ -0,0 +1,14 @@
import { mkdir, writeFile } from 'node:fs/promises';
import { fetchList } from '../src/downloads.mjs';
const directory = new URL('../assets/filters/', import.meta.url);
await mkdir(directory, { recursive: true });
const lists = [
['easylist.txt', 'https://easylist.to/easylist/easylist.txt'],
['easyprivacy.txt', 'https://easylist.to/easylist/easyprivacy.txt'],
];
for (const [file, url] of lists) {
const text = await fetchList(url);
await writeFile(new URL(file, directory), text);
console.log(`${file}: ${Buffer.byteLength(text)} bytes`);
}
await writeFile(new URL('manifest.json', directory), JSON.stringify({ fetchedAt: new Date().toISOString(), lists }, null, 2));
+30
View File
@@ -0,0 +1,30 @@
import { randomUUID } from 'node:crypto';
// Grants are issued only by trusted host UI code. Pages never receive tokens.
export class AgentController {
#grants = new Map();
constructor(getTab, clock = Date.now) { this.getTab = getTab; this.clock = clock; }
grant(tabId, profileId) {
const tab = this.getTab(tabId);
if (tab.profileId !== profileId) throw new Error('Profile mismatch.');
const token = randomUUID();
this.#grants.set(token, { tabId, profileId, epoch: tab.epoch, expires: this.clock() + 300_000 });
return token;
}
revokeAll() { this.#grants.clear(); }
authorized(token, tabId) {
const grant = this.#grants.get(token);
if (!grant || grant.tabId !== tabId || grant.expires <= this.clock()) throw new Error('Agent access is not authorized.');
const tab = this.getTab(tabId);
if (tab.profileId !== grant.profileId || tab.epoch !== grant.epoch) throw new Error('The document changed. Request a new grant.');
return tab;
}
async snapshot(token, tabId) {
const tab = this.authorized(token, tabId);
const text = await tab.view.webContents.executeJavaScriptInIsolatedWorld(900, [{
code: `(() => ({ title: document.title.slice(0, 200), text: (document.body?.innerText || '').slice(0, 24000) }))()`,
}]);
this.authorized(token, tabId);
return { tabId, profileId: tab.profileId, document: tab.epoch, url: tab.view.webContents.getURL(), untrusted: true, ...text };
}
}
+43
View File
@@ -0,0 +1,43 @@
import https from 'node:https';
import { resolvePublic, webUrl } from './policy.mjs';
export async function fetchList(address, redirects = 0, signal = AbortSignal.timeout(10_000)) {
const url = new URL(webUrl(address, { blank: false }));
if (url.protocol !== 'https:' || (url.port && url.port !== '443') || redirects > 3) throw new Error('Use a public HTTPS filter list.');
const target = await new Promise((resolve, reject) => {
const abort = () => reject(new Error('Filter download timed out.'));
signal.addEventListener('abort', abort, { once: true });
if (signal.aborted) abort();
resolvePublic(url.hostname).then(resolve, reject).finally(() => signal.removeEventListener('abort', abort));
});
return new Promise((resolve, reject) => {
const request = https.get(url, {
signal,
lookup: (_host, options, callback) => options.all ? callback(null, [target]) : callback(null, target.address, target.family),
headers: { 'Accept': 'text/plain', 'Accept-Encoding': 'identity' },
}, response => {
if ([301, 302, 303, 307, 308].includes(response.statusCode)) {
response.resume();
try { fetchList(new URL(response.headers.location, url).href, redirects + 1, signal).then(resolve, reject); }
catch (error) { reject(error); }
return;
}
if (response.statusCode !== 200) { response.resume(); reject(new Error('Filter download failed.')); return; }
let size = 0;
const chunks = [];
response.on('data', chunk => {
size += chunk.length;
if (size > 5_000_000) request.destroy(new Error('The filter list exceeds 5 MB.'));
else chunks.push(chunk);
});
response.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
if (!text.trim() || /^\s*</.test(text)) reject(new Error('The download is not a filter list.'));
else resolve(text);
});
response.on('error', reject);
});
request.setTimeout(10_000, () => request.destroy(new Error('Filter download timed out.')));
request.on('error', reject);
});
}
+63
View File
@@ -0,0 +1,63 @@
import { app } from 'electron';
import path from 'node:path';
import net from 'node:net';
import { createEngine } from './engine.mjs';
for (const flag of ['no-sandbox', 'disable-web-security', 'ignore-certificate-errors', 'remote-debugging-port', 'remote-debugging-pipe']) {
if (app.commandLine.hasSwitch(flag)) throw new Error('Unsafe browser launch option.');
}
app.enableSandbox();
app.commandLine.appendSwitch('disable-quic');
app.commandLine.appendSwitch('disable-background-networking');
app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE 127.0.0.1');
app.commandLine.appendSwitch('force-webrtc-ip-handling-policy', 'disable_non_proxied_udp');
app.on('window-all-closed', () => {});
app.on('certificate-error', (event, _wc, _url, _error, _cert, done) => { event.preventDefault(); done(false); });
app.on('select-client-certificate', (event, _wc, _url, _certs, done) => { event.preventDefault(); done(); });
const root = app.commandLine.getSwitchValue('rs-browser-root');
const port = Number(app.commandLine.getSwitchValue('rs-connect'));
const token = process.env.RUNESTONE_BROWSER_TOKEN || '';
delete process.env.RUNESTONE_BROWSER_TOKEN;
if (!path.isAbsolute(root) || !Number.isInteger(port) || port < 1024 || port > 65535 || token.length < 32) app.exit(1);
else {
app.setPath('userData', root);
app.whenReady().then(async () => {
let writable = true;
const socket = net.createConnection({ host: '127.0.0.1', port });
socket.setEncoding('utf8'); socket.setNoDelay(true);
socket.on('error', () => app.exit(1));
const connected = new Promise(resolve => socket.once('connect', resolve));
const emit = value => {
if (socket.destroyed || (value.event === 'frame' && !writable)) return;
writable = socket.write(JSON.stringify(value) + '\n');
};
socket.on('drain', () => { writable = true; });
await connected;
socket.write(JSON.stringify({ token }) + '\n');
const engine = await createEngine({ directory: root, emit, canEmitFrame: () => writable && !socket.destroyed });
let buffer = '', queued = 0, queue = Promise.resolve();
socket.on('close', () => { void engine.shutdown().finally(() => app.exit(0)); });
socket.on('data', chunk => {
buffer += chunk;
if (buffer.length > 6_000_000) { socket.destroy(); return; }
let end;
while ((end = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, end); buffer = buffer.slice(end + 1);
if (++queued > 128) { socket.destroy(); return; }
queue = queue.then(async () => {
let message;
try {
message = JSON.parse(line);
if (!Number.isSafeInteger(message.id) || message.id < 1) throw new Error('Invalid request.');
if (message.command === 'shutdown') {
await engine.shutdown();
socket.write(JSON.stringify({ id: message.id, result: null }) + '\n', () => app.exit(0)); return;
}
emit({ id: message.id, result: await engine.command(message.command, message.args) });
} catch (error) { emit({ id: message?.id, error: error.message }); }
finally { queued--; }
});
}
});
emit({ event: 'ready' });
}).catch(error => { console.error(error); app.exit(1); });
}
+319
View File
@@ -0,0 +1,319 @@
import { app, BrowserWindow, session, shell, clipboard } from 'electron';
import { randomUUID } from 'node:crypto';
import { Store } from './store.mjs';
import { Filters } from './filters.mjs';
import { createGateway } from './gateway.mjs';
import { AgentController } from './agent.mjs';
import { loadFavicon } from './favicon.mjs';
import { listCookies, removeCookie } from './web-data.mjs';
import { addressInput, webUrl, shortText, REMOTE_PREFERENCES } from './policy.mjs';
import { FrameDelivery } from './frame-delivery.mjs';
export async function createEngine({ directory, emit = () => {}, canEmitFrame = () => true, allowedTestHosts = new Set(), openExternal = url => shell.openExternal(url) }) {
const store = new Store(directory);
const sessions = new Map(), tabs = new Map();
let filters = new Filters();
await filters.load(store.data.settings.personalRules, store.data.settings.filterLists, { directory });
let stopped = false;
const runtimeId = randomUUID();
let revision = 0;
const tab = id => { const found = tabs.get(id); if (!found) throw new Error('Unknown browser tab.'); return found; };
const agent = new AgentController(tab);
const snapshot = () => ({
runtimeId, revision: ++revision,
profiles: structuredClone(store.data.profiles), settings: structuredClone(store.data.settings),
bookmarks: structuredClone(store.data.bookmarks),
tabs: [...tabs.values()].map(item => ({ id: item.id, profileId: item.profileId, title: item.title, favicon: item.favicon,
url: item.view.webContents.getURL(), loading: item.view.webContents.isLoading(), blocked: item.blocked, find: item.find,
canBack: item.view.webContents.navigationHistory.canGoBack(), canForward: item.view.webContents.navigationHistory.canGoForward() })),
});
let timer;
const changed = () => {
if (stopped || timer) return;
timer = setTimeout(() => { timer = undefined; if (!stopped) emit({ event: 'state', state: snapshot() }); }, 80);
};
const login = (event, _contents, _details, auth, callback) => {
event.preventDefault();
const entry = [...sessions.values()].find(item => item.gateway.port === auth.port);
if (entry && auth.isProxy && auth.host === '127.0.0.1') callback(entry.gateway.username, entry.gateway.password);
else callback();
};
app.on('login', login);
const enabled = url => {
try { return store.data.settings.adblock && !store.data.exceptions.includes(new URL(url).origin); }
catch { return store.data.settings.adblock; }
};
async function profile(id) {
store.profile(id);
if (sessions.has(id)) return sessions.get(id).session;
const ses = session.fromPartition(`persist:runestone-${id}`);
const gateway = await createGateway({ allowedTestHosts });
sessions.set(id, { session: ses, gateway });
await ses.setProxy({ mode: 'fixed_servers', proxyRules: `http://127.0.0.1:${gateway.port}`, proxyBypassRules: '<-loopback>' });
ses.setPermissionRequestHandler((_wc, _permission, done) => done(false));
ses.setPermissionCheckHandler(() => false);
ses.setDevicePermissionHandler(() => false);
ses.setDisplayMediaRequestHandler((_request, done) => done({}));
ses.on('will-download', (event, download, contents) => {
const current = [...tabs.values()].find(item => item.view.webContents === contents);
const url = download.getURLChain()[0];
if (!current?.downloads.delete(url)) { event.preventDefault(); return; }
download.setSaveDialogOptions({ title: 'Save download', defaultPath: download.getFilename() });
download.once('done', (_event, state) => {
if (state === 'interrupted') emit({ event: 'error', tabId: current.id, message: 'The download failed. Try again.' });
});
});
ses.webRequest.onBeforeRequest(async (details, done) => {
try {
if (details.url === 'about:blank') return done({ cancel: false });
webUrl(details.url.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:'), { blank: false });
const current = [...tabs.values()].find(item => item.view.webContents.id === details.webContentsId);
const sourceUrl = details.frame?.url || details.initiator || current?.view.webContents.getURL() || details.url;
const cancel = enabled(sourceUrl) && await filters.match({ url: details.url, sourceUrl, type: details.resourceType });
if (cancel && current) { current.blocked++; changed(); }
done({ cancel });
} catch { done({ cancel: true }); }
});
return ses;
}
async function cosmetics(item) {
const wc = item.view.webContents;
if (wc.isDestroyed() || !enabled(wc.getURL()) || !/^https?:/.test(wc.getURL())) return;
const epoch = item.epoch;
try {
const selectors = await wc.executeJavaScriptInIsolatedWorld(901, [{ code: `(() => { const nodes = [...document.querySelectorAll('[class], [id]')].slice(0, 3000); return { classes: [...new Set(nodes.flatMap(n => [...n.classList]))].slice(0, 3000), ids: nodes.map(n => n.id).filter(Boolean) }; })()` }]);
const css = await filters.cosmetics({ url: wc.getURL(), ...selectors });
if (css && item.epoch === epoch) await wc.insertCSS(css);
} catch { /* Navigation can destroy the isolated world. */ }
}
async function createTab(profileId = store.data.profiles[0].id, id = randomUUID(), url = store.data.settings.homepage || 'about:blank') {
url = webUrl(url);
if (tabs.size >= 24) throw new Error('The browser tab limit is 24.');
const ses = await profile(profileId);
const win = new BrowserWindow({ width: 1000, height: 700, show: false, frame: false,
webPreferences: { ...REMOTE_PREFERENCES, session: ses, offscreen: { deviceScaleFactor: 1 }, backgroundThrottling: false } });
win.setMenu(null);
const item = { id, profileId, epoch: 0, view: win, title: 'Browser', favicon: null, iconRequest: null, blocked: 0, find: null, findRequest: 0,
delivery: new FrameDelivery(), context: null, downloads: new Set(), settle: null, retryFrame: null, latestImage: null, scale: 1 };
tabs.set(item.id, item);
const wc = win.webContents;
wc.setFrameRate(60); wc.setWebRTCIPHandlingPolicy('disable_non_proxied_udp');
wc.setWindowOpenHandler(details => {
try { emit({ event: 'open-link', tabId: id, url: webUrl(details.url, { blank: false }) }); } catch { /* Reject unsupported addresses. */ }
return { action: 'deny' };
});
wc.on('context-menu', (_event, params) => {
const token = randomUUID();
const safe = value => { try { return webUrl(value, { blank: false }); } catch { return ''; } };
item.context = { token, epoch: item.epoch, x: params.x / item.scale, y: params.y / item.scale, linkURL: safe(params.linkURL), srcURL: safe(params.srcURL),
hasImageContents: params.hasImageContents, isEditable: params.isEditable, selectionText: params.selectionText.slice(0, 100000), editFlags: params.editFlags };
emit({ event: 'context-menu', tabId: id, ...item.context });
});
wc.on('will-attach-webview', event => event.preventDefault());
const navigation = (event, url) => { try { webUrl(url); } catch { event.preventDefault(); } };
wc.on('will-navigate', navigation); wc.on('will-redirect', navigation);
wc.on('will-frame-navigate', event => { if (!['about:blank', 'about:srcdoc'].includes(event.url)) navigation(event, event.url); });
wc.on('did-start-navigation', (_event, _url, inPlace, main) => { if (main && !inPlace) { item.iconRequest?.abort(); item.favicon = null; item.epoch++; item.blocked = 0; item.find = null; item.findRequest = 0; agent.revokeAll(); } changed(); });
wc.on('found-in-page', (_event, result) => {
if (item.find && result.requestId === item.findRequest) {
item.find = { ...item.find, matches: result.matches, activeMatch: result.activeMatchOrdinal, pending: !result.finalUpdate };
changed();
}
});
wc.on('did-navigate', (_event, url) => { store.visit(profileId, url, item.title); changed(); });
wc.on('did-navigate-in-page', (_event, _url, main) => { if (main) { item.epoch++; agent.revokeAll(); } changed(); });
wc.on('page-title-updated', (_event, title) => { item.title = title.slice(0, 200); changed(); });
wc.on('page-favicon-updated', (_event, urls) => {
item.iconRequest?.abort();
const request = new AbortController();
item.iconRequest = request;
void loadFavicon(urls, (url, options) => ses.fetch(url, options), request.signal).then(icon => {
if (request.signal.aborted || stopped || wc.isDestroyed()) return;
item.favicon = icon; changed();
});
});
wc.on('destroyed', () => { item.iconRequest?.abort(); clearTimeout(item.settle); clearTimeout(item.retryFrame); });
wc.on('did-stop-loading', () => { changed(); void cosmetics(item); });
wc.on('did-fail-load', (_event, code, _description, _url, main) => { if (main && code !== -3) emit({ event: 'error', tabId: item.id, message: `Page load failed (${code}).` }); });
wc.on('paint', (_event, _dirty, image) => {
item.latestImage = image;
clearTimeout(item.settle);
clearTimeout(item.retryFrame);
const frame = (lossless = false) => {
clearTimeout(item.retryFrame);
if (stopped || wc.isDestroyed() || !wc.isPainting()) return;
if (!canEmitFrame() || !item.delivery.canSend()) {
// Retain the latest static frame until the host can decode it.
item.retryFrame = setTimeout(() => frame(lossless), 32); return;
}
const data = lossless ? item.latestImage.toPNG() : item.latestImage.toJPEG(90);
if (data.length && data.length <= 4_000_000) emit({ event: 'frame', tabId: item.id, frameId: item.delivery.sent(),
mime: lossless ? 'image/png' : 'image/jpeg', data: data.toString('base64'), ...item.latestImage.getSize() });
};
frame();
// Send a lossless final frame for sharp text when the page stops changing.
item.settle = setTimeout(() => frame(true), 140);
});
// Navigation reports completion through events and must not hold the command queue.
void wc.loadURL(url).catch(() => {}); changed(); return item.id;
}
function closeTab(id) {
const current = tab(id); tabs.delete(id); agent.revokeAll(); current.view.destroy(); changed();
}
async function command(name, args = {}) {
if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('Invalid browser arguments.');
switch (name) {
case 'state': return snapshot();
case 'frameAck': tab(args.tabId).delivery.acknowledge(args.frameId); return null;
case 'newTab': return { tabId: await createTab(args.profileId, undefined, args.url) };
case 'closeTab': closeTab(args.tabId); break;
case 'navigate': {
const current = tab(args.tabId), url = addressInput(args.input, store.data.settings.search);
void current.view.webContents.loadURL(url).catch(() => {}); break;
}
case 'back': { const history = tab(args.tabId).view.webContents.navigationHistory; if (history.canGoBack()) history.goBack(); break; }
case 'forward': { const history = tab(args.tabId).view.webContents.navigationHistory; if (history.canGoForward()) history.goForward(); break; }
case 'reload': tab(args.tabId).view.webContents.reload(); break;
case 'stop': tab(args.tabId).view.webContents.stop(); break;
case 'find': {
const current = tab(args.tabId), wc = current.view.webContents;
if (typeof args.text !== 'string' || args.text.length > 1000) throw new Error('Find text must contain at most 1000 characters.');
if (!args.text) { wc.stopFindInPage('clearSelection'); current.find = null; current.findRequest = 0; break; }
const fresh = current.find?.text !== args.text || args.next !== true;
current.find = { text: args.text, matches: current.find?.matches ?? 0, activeMatch: 0, pending: true };
current.findRequest = wc.findInPage(args.text, { forward: args.forward !== false, findNext: fresh });
break;
}
case 'stopFind': {
const current = tab(args.tabId);
current.find = null; current.findRequest = 0;
current.view.webContents.stopFindInPage('clearSelection'); break;
}
case 'openExternal': await openExternal(webUrl(tab(args.tabId).view.webContents.getURL(), { blank: false })); break;
case 'resize': {
const current = tab(args.tabId);
if (!Number.isInteger(args.width) || !Number.isInteger(args.height) || args.width < 100 || args.height < 100 || args.width > 5120 || args.height > 3200) throw new Error('Invalid browser size.');
const scale = Number(args.scale ?? 1);
if (!Number.isFinite(scale) || scale < 1 || scale > 3) throw new Error('Invalid browser scale.');
current.scale = scale;
current.view.setContentSize(Math.round(args.width * scale), Math.round(args.height * scale));
current.view.webContents.enableDeviceEmulation({ screenPosition: 'desktop', screenSize: { width: args.width, height: args.height },
deviceScaleFactor: scale, viewPosition: { x: 0, y: 0 }, viewSize: { width: args.width, height: args.height }, scale });
current.delivery.clear(); current.view.webContents.invalidate(); return null;
}
case 'visible': { const item = tab(args.tabId), wc = item.view.webContents; item.delivery.clear(); if (args.visible === true) { wc.startPainting(); wc.invalidate(); } else { wc.stopPainting(); clearTimeout(item.settle); clearTimeout(item.retryFrame); } return null; }
case 'insertText': {
if (typeof args.text !== 'string' || args.text.length > 100000) throw new Error('Invalid browser text.');
await tab(args.tabId).view.webContents.insertText(args.text); return null;
}
case 'edit': {
const wc = tab(args.tabId).view.webContents;
if (!['undo', 'redo', 'cut', 'copy', 'paste', 'pasteAndMatchStyle', 'selectAll', 'delete'].includes(args.action)) throw new Error('Invalid edit action.');
wc[args.action](); return null;
}
case 'contextAction': {
const current = tab(args.tabId), context = current.context, wc = current.view.webContents;
if (!context || context.token !== args.token || context.epoch !== current.epoch) throw new Error('This page menu is no longer available.');
switch (args.action) {
case 'copyLink': if (context.linkURL) clipboard.writeText(context.linkURL); break;
case 'copyImageAddress': if (context.srcURL) clipboard.writeText(context.srcURL); break;
case 'copyImage': if (context.hasImageContents) wc.copyImageAt(Math.round(context.x * current.scale), Math.round(context.y * current.scale)); break;
case 'openExternal': if (context.linkURL) await openExternal(context.linkURL); break;
case 'saveImage': case 'saveLink': {
const url = args.action === 'saveImage' ? context.srcURL : context.linkURL;
if (!url) throw new Error('This item has no downloadable address.');
current.downloads.add(url); wc.downloadURL(url); break;
}
default: throw new Error('Invalid page menu action.');
}
return null;
}
case 'input': {
const current = tab(args.tabId), wc = current.view.webContents;
const input = args.input;
if (!input || !['mouseDown', 'mouseUp', 'mouseMove', 'mouseWheel', 'keyDown', 'keyUp', 'char'].includes(input.type)) throw new Error('Invalid browser input.');
const modifiers = Array.isArray(input.modifiers) ? input.modifiers.filter(value => ['shift', 'control', 'alt', 'meta'].includes(value)) : [];
let event;
if (input.type.startsWith('mouse')) {
if (![input.x, input.y].every(value => Number.isInteger(value) && value >= 0 && value <= 5120)) throw new Error('Invalid pointer position.');
event = { type: input.type, x: Math.round(input.x * current.scale), y: Math.round(input.y * current.scale), modifiers };
if (input.type === 'mouseWheel') Object.assign(event, { deltaX: Math.max(-2000, Math.min(2000, Number(input.deltaX) || 0)) * current.scale, deltaY: Math.max(-2000, Math.min(2000, Number(input.deltaY) || 0)) * current.scale, canScroll: true, hasPreciseScrollingDeltas: true });
else Object.assign(event, { button: ['left', 'middle', 'right'].includes(input.button) ? input.button : 'left', clickCount: input.clickCount === 2 ? 2 : 1 });
} else {
if (typeof input.keyCode !== 'string' || input.keyCode.length > 32) throw new Error('Invalid key.');
event = { type: input.type, keyCode: input.keyCode, modifiers };
}
// Pointer motion and wheel events must not repeatedly activate the native window.
if (input.type === 'mouseDown' || input.type === 'keyDown' || input.type === 'char') wc.focus();
wc.sendInputEvent(event); return null;
}
case 'createProfile': store.createProfile(args.name); break;
case 'renameProfile': store.profile(args.profileId).name = shortText(args.name, 60); store.save(); break;
case 'prepareDuplicate': {
store.profile(args.profileId); shortText(args.name, 60);
if (store.data.profiles.length >= 20) throw new Error('The profile limit is 20.');
const cookies = [];
for (const [profileId, entry] of sessions) cookies.push({ profileId, cookies: await entry.session.cookies.get({}) });
return { sourceId: args.profileId, id: randomUUID(), name: args.name.trim(), cookies, tabs: snapshot().tabs.map(item => ({ id: item.id, profileId: item.profileId, url: item.url })) };
}
case 'commitDuplicate': {
store.duplicateMetadata(args.sourceId, args.id, args.name);
for (const entry of args.cookies || []) {
const destinations = entry.profileId === args.sourceId ? [entry.profileId, args.id] : [entry.profileId];
for (const profileId of destinations) {
const ses = await profile(profileId);
for (const cookie of entry.cookies) {
await ses.cookies.set({ url: `${cookie.secure ? 'https' : 'http'}://${cookie.domain.replace(/^\./, '')}${cookie.path}`, name: cookie.name, value: cookie.value,
path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite,
...(!cookie.hostOnly ? { domain: cookie.domain } : {}), ...(cookie.expirationDate ? { expirationDate: cookie.expirationDate } : {}) });
}
}
}
for (const saved of args.tabs || []) await createTab(saved.profileId, saved.id, saved.url);
break;
}
case 'bookmark': { const current = tab(args.tabId); store.bookmark(current.profileId, current.view.webContents.getURL(), current.title); break; }
case 'removeBookmark': store.data.bookmarks = store.data.bookmarks.filter(item => item.id !== args.id); store.save(); break;
case 'settings': {
const previous = structuredClone(store.data.settings);
store.configure(args, { persist: false });
const next = new Filters();
try {
await next.load(store.data.settings.personalRules, store.data.settings.filterLists, { directory, download: true });
store.save();
} catch (error) { await next.close(); store.configure(previous, { persist: false }); throw error; }
await filters.close(); filters = next;
for (const item of tabs.values()) item.view.webContents.reload(); break;
}
case 'webData': {
const ses = await profile(args.profileId);
return { profileId: args.profileId, cookies: await listCookies(ses), history: structuredClone(store.data.history.filter(item => item.profileId === args.profileId)) };
}
case 'removeCookie': await removeCookie(await profile(args.profileId), args.id); break;
case 'removeHistory': store.removeHistory(args.profileId, args.id); break;
case 'clearData': {
const ses = await profile(args.profileId);
if (!['all', 'cache', 'cookies', 'history'].includes(args.kind)) throw new Error('Invalid data type.');
for (const item of [...tabs.values()]) if (item.profileId === args.profileId) closeTab(item.id);
if (args.kind !== 'history') await ses.clearData(args.kind === 'all' ? {} : { dataTypes: [args.kind] });
if (args.kind === 'all' || args.kind === 'cookies') await ses.clearAuthCache();
if (args.kind === 'all' || args.kind === 'history') store.data.history = store.data.history.filter(item => item.profileId !== args.profileId);
store.save(); break;
}
case 'agentSnapshot': {
const current = tab(args.tabId), token = agent.grant(current.id, current.profileId);
try { return await agent.snapshot(token, current.id); } finally { agent.revokeAll(); }
}
default: throw new Error('Unknown browser command.');
}
changed(); return snapshot();
}
async function shutdown() {
if (stopped) return;
stopped = true; clearTimeout(timer); agent.revokeAll(); app.removeListener('login', login);
for (const item of tabs.values()) item.view.destroy(); tabs.clear();
for (const item of sessions.values()) { item.session.flushStorageData(); await item.session.cookies.flushStore(); await item.session.closeAllConnections(); await item.gateway.close(); }
await filters.close();
}
return { command, snapshot, shutdown, tabs, store };
}
+38
View File
@@ -0,0 +1,38 @@
import { webUrl } from './policy.mjs';
const limit = 64 * 1024;
const imageType = /^image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon|svg\+xml)$/;
export async function loadFavicon(urls, fetchImage, signal) {
for (const url of [...new Set(urls)].slice(0, 8)) {
if (signal.aborted) return null;
try {
if (typeof url !== 'string' || url.length > 90_000) continue;
if (url.startsWith('data:image/')) {
const comma = url.indexOf(',');
const metadata = url.slice(5, comma).split(';');
if (comma < 0 || !imageType.test(metadata[0])) continue;
const bytes = Buffer.from(decodeURIComponent(url.slice(comma + 1)), metadata.includes('base64') ? 'base64' : 'utf8');
if (bytes.length && bytes.length <= limit) return `data:${metadata[0]};base64,${bytes.toString('base64')}`;
continue;
}
webUrl(url, { blank: false });
const response = await fetchImage(url, { signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) });
try {
const type = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
if (!response.ok || !imageType.test(type || '') || Number(response.headers.get('content-length')) > limit) continue;
const chunks = [];
let size = 0;
for await (const chunk of response.body) {
size += chunk.length;
if (size > limit) throw new Error('Icon exceeds the size limit.');
chunks.push(chunk);
}
if (size) return `data:${type};base64,${Buffer.concat(chunks).toString('base64')}`;
} finally {
if (!response.body?.locked) await response.body?.cancel().catch(() => {});
}
} catch { /* Try the next icon when a request fails. */ }
}
return null;
}
+33
View File
@@ -0,0 +1,33 @@
import { parentPort } from 'node:worker_threads';
import { FiltersEngine, Request } from '@ghostery/adblocker';
let engine;
parentPort.on('message', ({ id, type, text, details }) => {
try {
let result;
if (type === 'load') {
if (text.length > 30_000_000) throw new Error('The combined filters exceed the limit.');
const lines = text.split(/\r?\n/);
const supported = lines.filter(line => !/##\+js\(|#@#\+js\(|#\$#|#\?#|:style\(|\$.*(?:csp|replace|urltransform)=/i.test(line) && line.length < 8192);
engine = FiltersEngine.parse(supported.join('\n'), {
loadCSPFilters: false, loadExtendedSelectors: false, enableHtmlFiltering: false,
loadPreprocessors: false,
});
result = { excludedRules: lines.length - supported.length };
} else if (type === 'match') {
if (!engine) throw new Error('Filters are unavailable.');
result = engine.match(Request.fromRawDetails(details)).match;
} else if (type === 'cosmetics') {
const request = Request.fromRawDetails({ url: details.url, type: 'main_frame' });
const filters = engine.getCosmeticsFilters({
url: details.url, hostname: request.hostname, domain: request.domain,
classes: details.classes, ids: details.ids,
getBaseRules: true, getRulesFromDOM: true, getRulesFromHostname: true,
getInjectionRules: false, getExtendedRules: false,
});
result = filters.styles || '';
// Never turn filter-list text into scripts or network-bearing CSS.
if (/url\s*\(|@import|expression\s*\(/i.test(result)) result = '';
} else throw new Error('Unknown filter operation.');
parentPort.postMessage({ id, result });
} catch (error) { parentPort.postMessage({ id, error: error.message }); }
});
+38
View File
@@ -0,0 +1,38 @@
import { Worker } from 'node:worker_threads';
import { DEFAULT_LISTS, loadLists } from './subscriptions.mjs';
export class Filters {
constructor() {
this.worker = new Worker(new URL('./filter-worker.mjs', import.meta.url), { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 384 } });
this.next = 1; this.pending = new Map(); this.closed = false;
this.worker.on('message', ({ id, result, error }) => {
const pending = this.pending.get(id);
if (!pending) return;
clearTimeout(pending.timer); this.pending.delete(id);
if (error) pending.reject(new Error(error)); else pending.resolve(result);
});
const fail = () => {
this.closed = true;
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(new Error('The filter worker stopped.')); }
this.pending.clear();
};
this.worker.on('error', fail); this.worker.on('exit', fail);
}
call(type, payload = {}, timeout = 3000) {
if (this.closed || this.pending.size >= 512) return Promise.reject(new Error('Filters are unavailable.'));
return new Promise((resolve, reject) => {
const id = this.next++;
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error('The filter operation timed out.')); }, timeout);
this.pending.set(id, { resolve, reject, timer });
this.worker.postMessage({ id, type, ...payload });
});
}
async load(extra = '', addresses = DEFAULT_LISTS, options = {}) {
const files = await loadLists(addresses, options);
this.status = await this.call('load', { text: [...files, extra].join('\n') }, 15_000);
return this.status;
}
match(details) { return this.call('match', { details }); }
cosmetics(details) { return this.call('cosmetics', { details }); }
close() { return this.worker.terminate(); }
}
+12
View File
@@ -0,0 +1,12 @@
/** Bound frames in flight so image decoding cannot delay browser input. */
export class FrameDelivery {
sequence = 0;
pending = new Map();
canSend(time = performance.now()) {
for (const [id, started] of this.pending) if (time - started > 250) this.pending.delete(id);
return this.pending.size < 2;
}
sent(time = performance.now()) { const id = ++this.sequence; this.pending.set(id, time); return id; }
acknowledge(id) { this.pending.delete(id); }
clear() { this.pending.clear(); }
}
+93
View File
@@ -0,0 +1,93 @@
import http from 'node:http';
import net from 'node:net';
import { randomBytes, timingSafeEqual } from 'node:crypto';
import { resolvePublic, webUrl } from './policy.mjs';
// A destination is resolved once and the socket connects to that exact address.
// Never pass the original hostname to a second resolver after the policy check.
export async function createGateway({ resolver, allowedTestHosts = new Set() } = {}) {
const username = 'runestone';
const password = randomBytes(32).toString('hex');
const expected = Buffer.from(`Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`);
const sockets = new Set();
let stopped = false;
let resolving = 0;
const authenticate = (req, socket) => {
const actual = Buffer.from(req.headers['proxy-authorization'] || '');
if (actual.length === expected.length && timingSafeEqual(actual, expected)) return true;
socket.end('HTTP/1.1 407 Proxy Authentication Required\r\nProxy-Authenticate: Basic realm="RuneStone"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n');
return false;
};
const destination = async (host, port) => {
if (stopped) throw new Error('Network gate is stopped.');
if (![80, 443].includes(port) && !allowedTestHosts.has(host)) throw new Error('Destination port is blocked.');
if (resolving >= 64) throw new Error('The DNS request limit was reached.');
resolving++;
let timer;
try {
return await Promise.race([
resolvePublic(host, resolver, allowedTestHosts),
new Promise((_resolve, reject) => { timer = setTimeout(() => reject(new Error('DNS lookup timed out.')), 10_000); }),
]);
} finally { clearTimeout(timer); resolving--; }
};
const track = (socket) => {
sockets.add(socket);
socket.on('error', () => {});
socket.once('close', () => sockets.delete(socket));
socket.setTimeout(60_000, () => socket.destroy());
};
const server = http.createServer({ maxHeaderSize: 16_384, requestTimeout: 30_000, headersTimeout: 15_000 }, async (req, res) => {
if (!authenticate(req, req.socket)) return;
try {
const url = new URL(webUrl(req.url, { blank: false }));
if (url.protocol !== 'http:') throw new Error('HTTPS requires CONNECT.');
const port = Number(url.port || 80);
const target = await destination(url.hostname, port);
if (stopped || req.destroyed) return res.destroy();
const headers = { ...req.headers, host: url.host, connection: 'close' };
for (const name of ['proxy-authorization', 'proxy-connection', 'upgrade', ...(req.headers.connection || '').toLowerCase().split(',').map(x => x.trim())]) delete headers[name];
const upstream = http.request({ hostname: target.address, family: target.family, port, path: url.pathname + url.search, method: req.method, headers, agent: false }, (response) => {
res.writeHead(response.statusCode, response.headers);
response.pipe(res);
});
upstream.on('socket', track);
upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });
res.once('close', () => upstream.destroy());
req.pipe(upstream);
} catch { res.writeHead(403); res.end('Destination blocked.'); }
});
server.on('connect', async (req, client, head) => {
if (!authenticate(req, client)) return;
try {
if (!/^(?:\[[\da-fA-F:]+\]|[^:/\s@?#]+):\d+$/.test(req.url)) throw new Error('Invalid tunnel destination.');
const url = new URL(`https://${req.url}`);
const port = Number(url.port || 443);
const target = await destination(url.hostname, port);
if (stopped || client.destroyed) return client.destroy();
const upstream = net.connect({ host: target.address, family: target.family, port });
track(upstream);
upstream.once('connect', () => {
client.write('HTTP/1.1 200 Connection Established\r\n\r\n');
if (head.length) upstream.write(head);
client.pipe(upstream); upstream.pipe(client);
});
upstream.once('error', () => client.destroy());
client.once('close', () => upstream.destroy());
} catch { client.end('HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n'); }
});
server.on('upgrade', (_req, socket) => socket.destroy());
server.on('connection', (socket) => {
if (stopped || sockets.size >= 256) return socket.destroy();
track(socket);
});
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
return {
port: server.address().port, username, password,
close() {
stopped = true;
for (const socket of sockets) socket.destroy();
return new Promise(resolve => server.close(resolve));
},
};
}
+63
View File
@@ -0,0 +1,63 @@
import ipaddr from 'ipaddr.js';
import { lookup } from 'node:dns/promises';
export const SEARCH_PROVIDERS = Object.freeze({
duckduckgo: 'https://duckduckgo.com/?q=',
google: 'https://www.google.com/search?q=',
bing: 'https://www.bing.com/search?q=',
});
export const MAX_INPUT = 8192;
export function webUrl(value, { blank = true } = {}) {
if (typeof value !== 'string' || value.length > MAX_INPUT || /[\u0000-\u001f\u007f]/u.test(value)) {
throw new Error('Invalid address.');
}
if (blank && value === 'about:blank') return value;
const url = new URL(value);
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) {
throw new Error('Use an HTTP or HTTPS address without embedded credentials.');
}
return url.href;
}
export function addressInput(value, provider = 'duckduckgo') {
if (typeof value !== 'string' || value.length > MAX_INPUT) throw new Error('Invalid address.');
const input = value.trim();
if (!input) return 'about:blank';
if (input === 'about:blank' || /^[a-z][a-z\d+.-]*:/i.test(input)) return webUrl(input);
if (!/\s/u.test(input) && (input.includes('.') || input === 'localhost')) return webUrl(`https://${input}`);
if (!Object.hasOwn(SEARCH_PROVIDERS, provider)) throw new Error('Unknown search provider.');
return SEARCH_PROVIDERS[provider] + encodeURIComponent(input);
}
export function publicAddress(address) {
try {
const parsed = ipaddr.process(address.replace(/^\[|\]$/g, ''));
return parsed.range() === 'unicast';
} catch { return false; }
}
export async function resolvePublic(hostname, resolver = lookup, allowedTestHosts = new Set()) {
const host = hostname.replace(/^\[|\]$/g, '');
if (!host || host.includes('%')) throw new Error('Invalid host.');
const answers = ipaddr.isValid(host)
? [{ address: host, family: ipaddr.parse(host).kind() === 'ipv6' ? 6 : 4 }]
: await resolver(host, { all: true, verbatim: true });
if (!answers.length || (!allowedTestHosts.has(host) && answers.some(({ address }) => !publicAddress(address)))) {
throw new Error('Local and private network access is blocked.');
}
return answers.find(answer => answer.family === 4) || answers[0];
}
export function shortText(value, limit = 120) {
if (typeof value !== 'string' || !value.trim() || value.length > limit) throw new Error('Invalid text.');
return value.trim().replace(/[\u0000-\u001f\u007f]/gu, '');
}
export const REMOTE_PREFERENCES = Object.freeze({
sandbox: true, contextIsolation: true, nodeIntegration: false,
nodeIntegrationInWorker: false, nodeIntegrationInSubFrames: false,
webSecurity: true, allowRunningInsecureContent: false,
webviewTag: false, devTools: false, safeDialogs: true,
navigateOnDragDrop: false, spellcheck: false,
});
+77
View File
@@ -0,0 +1,77 @@
import { mkdirSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { shortText, webUrl, SEARCH_PROVIDERS } from './policy.mjs';
import { DEFAULT_LISTS, normalizeLists } from './subscriptions.mjs';
export class Store {
constructor(directory) {
mkdirSync(directory, { recursive: true, mode: 0o700 });
this.file = path.join(directory, 'browser.json');
this.data = {
version: 1, settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [...DEFAULT_LISTS] },
profiles: [{ id: 'user', name: 'User' }],
bookmarks: [], history: [], exceptions: [],
};
try {
const saved = JSON.parse(readFileSync(this.file, 'utf8'));
if (saved.version !== 1 || !Array.isArray(saved.profiles) || !saved.profiles.every(p => /^[a-z0-9-]{1,64}$/.test(p.id))) throw new Error('Unsupported profile store.');
this.data = { ...saved, settings: { ...this.data.settings, ...saved.settings } };
// Preserve existing data. Legacy profiles become ordinary, removable profiles.
const personal = this.data.profiles.find(profile => profile.id === 'personal');
if (personal?.name === 'Personal') personal.name = 'User';
} catch (error) { if (error.code !== 'ENOENT') throw error; }
for (const item of this.data.history) if (!item.id) item.id = randomUUID();
}
save() {
writeFileSync(this.file + '.tmp', JSON.stringify(this.data, null, 2), { mode: 0o600 });
renameSync(this.file + '.tmp', this.file);
}
profile(id) {
const profile = this.data.profiles.find(p => p.id === id);
if (!profile) throw new Error('Unknown profile.');
return profile;
}
createProfile(name) {
if (this.data.profiles.length >= 20) throw new Error('The profile limit is 20.');
const profile = { id: randomUUID(), name: shortText(name, 60) };
this.data.profiles.push(profile); this.save(); return profile;
}
duplicateMetadata(sourceId, id, name) {
this.profile(sourceId);
if (!/^[a-f0-9-]{36}$/.test(id) || this.data.profiles.some(profile => profile.id === id)) throw new Error('Invalid destination profile.');
if (this.data.profiles.length >= 20) throw new Error('The profile limit is 20.');
const profile = { id, name: shortText(name, 60) };
this.data.profiles.push(profile);
this.data.bookmarks.push(...this.data.bookmarks.filter(item => item.profileId === sourceId).map(item => ({ ...item, id: randomUUID(), profileId: id })));
this.data.history.push(...this.data.history.filter(item => item.profileId === sourceId).map(item => ({ ...item, id: randomUUID(), profileId: id })));
this.save(); return profile;
}
configure(input, { persist = true } = {}) {
if (!Object.hasOwn(SEARCH_PROVIDERS, input.search) || typeof input.adblock !== 'boolean' ||
!['internal', 'external'].includes(input.linkDestination) || typeof input.personalRules !== 'string' || input.personalRules.length > 100_000) throw new Error('Invalid browser settings.');
const homepage = input.homepage ?? this.data.settings.homepage;
if (typeof homepage !== 'string') throw new Error('Invalid homepage address.');
const filterLists = normalizeLists(input.filterLists ?? this.data.settings.filterLists);
this.data.settings = { search: input.search, adblock: input.adblock, linkDestination: input.linkDestination, personalRules: input.personalRules,
homepage: homepage.trim() ? webUrl(homepage.trim()) : '', filterLists };
if (persist) this.save();
}
visit(profileId, url, title) {
this.profile(profileId);
if (!/^https?:/.test(url)) return;
this.data.history.unshift({ id: randomUUID(), profileId, url: webUrl(url), title: String(title).slice(0, 200), at: Date.now() });
this.data.history = this.data.history.slice(0, 2000); this.save();
}
bookmark(profileId, url, title) {
this.profile(profileId);
this.data.bookmarks.push({ id: randomUUID(), profileId, url: webUrl(url, { blank: false }), title: shortText(title || url, 500) });
this.save();
}
removeHistory(profileId, id) {
this.profile(profileId);
if (typeof id !== 'string' || !this.data.history.some(item => item.profileId === profileId && item.id === id)) throw new Error('This history entry no longer exists. Refresh the list.');
this.data.history = this.data.history.filter(item => item.profileId !== profileId || item.id !== id);
this.save();
}
}
+35
View File
@@ -0,0 +1,35 @@
import { createHash } from 'node:crypto';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { webUrl } from './policy.mjs';
import { fetchList } from './downloads.mjs';
export const DEFAULT_LISTS = Object.freeze([
'https://easylist.to/easylist/easylist.txt',
'https://easylist.to/easylist/easyprivacy.txt',
]);
export function normalizeLists(value) {
if (!Array.isArray(value) || value.length > 8) throw new Error('Use at most eight filter list URLs.');
return [...new Set(value.map(address => {
const url = new URL(webUrl(address, { blank: false }));
if (url.protocol !== 'https:' || (url.port && url.port !== '443')) throw new Error('Use an HTTPS filter list URL.');
return url.href;
}))];
}
export async function loadLists(addresses, { directory, download = false, fetch = fetchList } = {}) {
return Promise.all(normalizeLists(addresses).map(async address => {
const bundled = DEFAULT_LISTS.indexOf(address);
if (bundled !== -1) return readFile(new URL(`../assets/filters/${bundled === 0 ? 'easylist' : 'easyprivacy'}.txt`, import.meta.url), 'utf8');
const file = directory && path.join(directory, 'filter-lists', createHash('sha256').update(address).digest('hex') + '.txt');
if (!file) throw new Error('Filter storage is unavailable.');
try { return await readFile(file, 'utf8'); }
catch (error) { if (error.code !== 'ENOENT') throw error; }
if (!download) throw new Error('A filter list is missing. Save the browser settings to download it again.');
const text = await fetch(address);
await mkdir(path.dirname(file), { recursive: true });
await writeFile(file, text, { mode: 0o600 });
return text;
}));
}
+17
View File
@@ -0,0 +1,17 @@
export function cookieId(cookie) {
return JSON.stringify([cookie.name, cookie.domain, cookie.path, !!cookie.hostOnly, !!cookie.secure]);
}
export async function listCookies(session) {
return (await session.cookies.get({})).map(cookie => ({ id: cookieId(cookie), name: cookie.name,
domain: cookie.domain, path: cookie.path, secure: cookie.secure, httpOnly: cookie.httpOnly }));
}
export async function removeCookie(session, id) {
if (typeof id !== 'string' || id.length > 8192) throw new Error('Invalid cookie selection.');
const cookie = (await session.cookies.get({})).find(item => cookieId(item) === id);
if (!cookie) throw new Error('This cookie no longer exists. Refresh the list.');
// Expire the exact domain/path tuple. cookies.remove(url, name) can match other paths.
await session.cookies.set({ url: `${cookie.secure ? 'https' : 'http'}://${cookie.domain.replace(/^\./, '')}${cookie.path}`,
name: cookie.name, value: '', ...(cookie.hostOnly ? {} : { domain: cookie.domain }), path: cookie.path,
secure: cookie.secure, httpOnly: cookie.httpOnly, sameSite: cookie.sameSite, expirationDate: 1 });
await session.cookies.flushStore();
}
+18
View File
@@ -0,0 +1,18 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { AgentController } from '../src/agent.mjs';
test('agent grants bind profile, tab, document and expiry', () => {
let now = 100;
const tabs = new Map([['a', { profileId: 'agent', epoch: 1 }], ['p', { profileId: 'personal', epoch: 1 }]]);
const agent = new AgentController(id => tabs.get(id), () => now);
assert.throws(() => agent.grant('p', 'agent'));
const token = agent.grant('a', 'agent');
assert.throws(() => agent.authorized(token, 'p'));
assert.equal(agent.authorized(token, 'a'), tabs.get('a'));
tabs.get('a').epoch++;
assert.throws(() => agent.authorized(token, 'a'));
const next = agent.grant('a', 'agent'); now += 300_001;
assert.throws(() => agent.authorized(next, 'a'));
const last = agent.grant('a', 'agent'); agent.revokeAll();
assert.throws(() => agent.authorized(last, 'a'));
});
+187
View File
@@ -0,0 +1,187 @@
import { app, BrowserWindow } from 'electron';
import assert from 'node:assert/strict';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const { createEngine } = await import(process.env.RUNESTONE_TEST_PACKAGE ? pathToFileURL(path.join(process.env.RUNESTONE_TEST_PACKAGE, 'src/engine.mjs')).href : '../src/engine.mjs');
app.enableSandbox();
app.on('window-all-closed', () => {});
app.commandLine.appendSwitch('disable-quic');
app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE 127.0.0.1');
app.setPath('userData', process.env.RS_TEST_ROOT);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const until = async predicate => { for (let attempt = 0; attempt < 100; attempt++) { if (await predicate()) return; await wait(50); } throw new Error('Browser condition timed out.'); };
app.whenReady().then(async () => {
let engine, exitCode = 0;
const passed = [];
try {
const frames = [], external = [], events = [];
engine = await createEngine({ directory: process.env.RS_TEST_ROOT, allowedTestHosts: new Set(['127.0.0.1']), openExternal: async url => { external.push(url); }, emit: value => { if (value.event === 'frame') { frames.push(value); void engine?.command('frameAck', { tabId: value.tabId, frameId: value.frameId }); } else events.push(value); } });
if (process.env.RS_TEST_PHASE === 'restore') {
const plan = JSON.parse(process.env.RS_TEST_PLAN);
await engine.command('commitDuplicate', plan);
const made = await engine.command('newTab', { profileId: plan.id });
await engine.command('navigate', { tabId: made.tabId, input: process.env.RS_TEST_URL });
const wc = engine.tabs.get(made.tabId).view.webContents;
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.match(await wc.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(await wc.executeJavaScript("localStorage.getItem('identity')"), 'source');
await wc.executeJavaScript("localStorage.setItem('identity', 'copy'); document.cookie='login=copy; path=/'; true");
const original = engine.tabs.get(plan.tabs[0].id).view.webContents;
await until(async () => await original.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await original.executeJavaScript("localStorage.getItem('identity')"), 'source');
assert.match(await original.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === plan.id).length, 1);
passed.push('duplicate preserves cookies, local storage and bookmarks without sharing later changes');
} else {
assert.deepEqual(engine.snapshot().profiles, [{ id: 'user', name: 'User' }]);
const first = (await engine.command('newTab')).tabId;
const wc = engine.tabs.get(first).view.webContents;
await until(() => wc.getURL() === 'about:blank');
assert.equal(wc.getURL(), 'about:blank');
await assert.rejects(engine.command('openExternal', { tabId: first }));
assert.deepEqual(external, []);
assert.ok(BrowserWindow.getAllWindows().every(win => !win.isVisible()));
passed.push('one default User profile and no standalone browser window');
assert.equal(engine.snapshot().tabs.find(tab => tab.id === first).favicon, null);
const iconTab = (await engine.command('newTab', { url: process.env.RS_TEST_URL + 'with-icon' })).tabId;
const iconContents = engine.tabs.get(iconTab).view.webContents;
const favicon = () => engine.snapshot().tabs.find(tab => tab.id === iconTab)?.favicon;
await until(() => favicon()?.startsWith('data:image/svg+xml;base64,'));
const originalIcon = favicon();
await iconContents.executeJavaScript(`document.querySelector('link').href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a6XcAAAAASUVORK5CYII='; true`);
await until(() => favicon()?.startsWith('data:image/png;base64,'));
assert.notEqual(favicon(), originalIcon);
await engine.command('navigate', { tabId: iconTab, input: process.env.RS_TEST_URL + 'no-icon' });
await until(() => iconContents.getURL().endsWith('/no-icon') && !iconContents.isLoading());
assert.equal(favicon(), null);
await engine.command('back', { tabId: iconTab });
await until(() => favicon() === originalIcon);
await engine.command('closeTab', { tabId: iconTab });
passed.push('site icons load, update dynamically, clear on navigation, and return with history');
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL + 'slow' });
const slow = await Promise.race([
engine.command('newTab'),
wait(2000).then(() => { throw new Error('Slow homepage blocked the new-tab response.'); }),
]);
const slowContents = engine.tabs.get(slow.tabId).view.webContents;
await until(() => slowContents.isLoading());
assert.ok((await engine.command('state')).tabs.some(tab => tab.id === slow.tabId));
await engine.command('stop', { tabId: slow.tabId });
await engine.command('closeTab', { tabId: slow.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL });
const home = await engine.command('newTab');
const homeContents = engine.tabs.get(home.tabId).view.webContents;
await until(() => homeContents.getURL() === process.env.RS_TEST_URL);
await engine.command('closeTab', { tabId: home.tabId });
const explicit = await engine.command('newTab', { url: 'about:blank' });
await until(() => engine.tabs.get(explicit.tabId).view.webContents.getURL() === 'about:blank');
await engine.command('closeTab', { tabId: explicit.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: '' });
passed.push('homepage loads in new tabs, explicit links override it, and slow pages do not block commands');
await engine.command('settings', { ...engine.snapshot().settings, personalRules: '/blocked-ad.js\n127.0.0.1##.advertisement' });
await engine.command('navigate', { tabId: first, input: process.env.RS_TEST_URL });
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.deepEqual(await wc.executeJavaScript('[typeof require,typeof process,typeof browserHost,typeof window.__TAURI_INTERNALS__]'), ['undefined','undefined','undefined','undefined']);
passed.push('remote content has no Node, native bridge or terminal access');
await until(() => frames.some(frame => frame.tabId === first));
assert.ok(frames.some(frame => frame.width > 100 && frame.height > 100 && frame.data.length > 100 && ['image/png', 'image/jpeg'].includes(frame.mime)));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'char', keyCode: 'x' } });
await until(async () => await wc.executeJavaScript("document.querySelector('input').value") === 'x');
passed.push('offscreen frames and forwarded pointer and keyboard input work');
await engine.command('insertText', { tabId: first, text: '日本語 🙂' });
await until(async () => (await wc.executeJavaScript("document.querySelector('input').value")).endsWith('日本語 🙂'));
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="save-image" src="${process.env.RS_TEST_URL}picture.png" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#save-image").complete'));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.some(event => event.event === 'context-menu' && event.hasImageContents));
const context = events.findLast(event => event.event === 'context-menu');
const downloadPath = path.join(process.env.RS_TEST_ROOT, 'saved-image.png');
const saved = new Promise((resolve, reject) => wc.session.once('will-download', (_event, download) => {
download.setSavePath(downloadPath);
download.once('done', (_event, state) => state === 'completed' ? resolve() : reject(new Error(`Image download: ${state}`)));
}));
await engine.command('contextAction', { tabId: first, token: context.token, action: 'saveImage' });
await saved;
assert.equal((await readFile(downloadPath)).subarray(1, 4).toString(), 'PNG');
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active');
const finding = () => engine.snapshot().tabs.find(tab => tab.id === first).find;
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await until(() => finding()?.matches === 3 && !finding()?.pending);
assert.equal(finding().activeMatch, 1);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true });
await until(() => finding()?.activeMatch === 2 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true, forward: false });
await until(() => finding()?.activeMatch === 1 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'missing phrase' });
await until(() => finding()?.text === 'missing phrase' && !finding()?.pending);
assert.equal(finding().matches, 0);
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await engine.command('stopFind', { tabId: first });
await wait(100);
assert.equal(finding(), null);
await engine.command('find', { tabId: first, text: '' });
assert.equal(finding(), null);
await assert.rejects(engine.command('find', { tabId: first, text: 'x'.repeat(1001) }));
await engine.command('openExternal', { tabId: first });
assert.deepEqual(external, [process.env.RS_TEST_URL]);
passed.push('Find counts matches, moves both ways, clears results, and external opening uses the current web URL');
await wc.executeJavaScript("document.cookie='login=kept; path=/'; localStorage.setItem('identity','source'); true");
await engine.command('bookmark', { tabId: first });
const created = await engine.command('createProfile', { name: 'Research' });
const second = (await engine.command('newTab', { profileId: created.profiles.at(-1).id })).tabId;
await engine.command('navigate', { tabId: second, input: process.env.RS_TEST_URL });
const other = engine.tabs.get(second).view.webContents;
await until(async () => await other.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await other.executeJavaScript('document.cookie'), '');
assert.equal(await other.executeJavaScript("localStorage.getItem('identity')"), null);
const observation = await engine.command('agentSnapshot', { tabId: first });
assert.equal(observation.untrusted, true); assert.equal(observation.profileId, 'user');
passed.push('blank profiles are isolated and agent observation has no special profile name');
await wc.executeJavaScript("document.cookie='selected=root; path=/'; document.cookie='selected=nested; path=/nested'; document.cookie='keep=unchanged; path=/'; true");
await other.executeJavaScript("document.cookie='selected=other-profile; path=/'; true");
let webData = await engine.command('webData', { profileId: 'user' });
assert.ok(webData.cookies.every(cookie => !Object.hasOwn(cookie, 'value')));
const nestedCookie = webData.cookies.find(cookie => cookie.name === 'selected' && cookie.path === '/nested');
assert.ok(nestedCookie);
const openTabs = engine.snapshot().tabs.map(tab => tab.id);
await engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id });
webData = await engine.command('webData', { profileId: 'user' });
assert.ok(!webData.cookies.some(cookie => cookie.id === nestedCookie.id));
assert.ok(webData.cookies.some(cookie => cookie.name === 'selected' && cookie.path === '/'));
assert.ok(webData.cookies.some(cookie => cookie.name === 'keep'));
assert.match(await other.executeJavaScript('document.cookie'), /selected=other-profile/);
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
await assert.rejects(engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id }), /no longer exists/);
await assert.rejects(engine.command('webData', { profileId: 'missing' }), /Unknown profile/);
const visit = webData.history[0];
assert.ok(visit.id);
const otherProfile = created.profiles.at(-1).id;
await assert.rejects(engine.command('removeHistory', { profileId: otherProfile, id: visit.id }), /no longer exists/);
await engine.command('removeHistory', { profileId: 'user', id: visit.id });
const afterRemoval = await engine.command('webData', { profileId: 'user' });
assert.equal(afterRemoval.history.length, webData.history.length - 1);
assert.ok(!afterRemoval.history.some(item => item.id === visit.id));
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === 'user').length, 1);
passed.push('individual cookie and history removal preserves other paths, entries, profiles, bookmarks and tabs');
const plan = await engine.command('prepareDuplicate', { profileId: 'user', name: 'User copy' });
await writeFile(process.env.RS_TEST_ROOT + '/clone-plan.json', JSON.stringify(plan));
}
} catch (error) { console.error(error); exitCode = 1; }
finally {
if (engine) await engine.shutdown();
for (const name of passed) console.log(`PASS ${name}`);
await mkdir('output', { recursive: true });
await writeFile(`output/engine-${process.env.RS_TEST_PHASE || 'initial'}.json`, JSON.stringify({ exitCode, passed, platform: process.platform }, null, 2));
app.exit(exitCode);
}
});
+28
View File
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadFavicon } from '../src/favicon.mjs';
test('icons reject unsafe URLs and non-image responses, then use the next image', async () => {
const requested = [];
const icon = await loadFavicon(['file:///secret.png', 'javascript:alert(1)', 'https://example.com/bad', 'https://example.com/icon'], async url => {
requested.push(url);
return new Response('image', { headers: { 'content-type': url.endsWith('bad') ? 'text/html' : 'image/x-icon' } });
}, new AbortController().signal);
assert.deepEqual(requested, ['https://example.com/bad', 'https://example.com/icon']);
assert.equal(icon, 'data:image/x-icon;base64,aW1hZ2U=');
});
test('icons bound streamed data even without a content-length header', async () => {
const icon = await loadFavicon(['https://example.com/icon'], async () => new Response(new Uint8Array(65537), { headers: { 'content-type': 'image/png' } }), new AbortController().signal);
assert.equal(icon, null);
});
test('cancelled icon work does not make more requests', async () => {
const controller = new AbortController();
let calls = 0;
const icon = await loadFavicon(['https://example.com/one', 'https://example.com/two'], async () => {
calls++; controller.abort(); throw new Error('Aborted');
}, controller.signal);
assert.equal(icon, null);
assert.equal(calls, 1);
});
+14
View File
@@ -0,0 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Filters } from '../src/filters.mjs';
test('bundled filters block ads, apply exceptions and produce CSS without scripts', async () => {
const filters = new Filters();
try {
await filters.load('||ads.fixture.test^\n@@||ads.fixture.test/allowed.js\nfixture.test##.fixture-ad\nfixture.test##+js(alert, injected)');
assert.equal(await filters.match({ url: 'https://ads.fixture.test/ads.js', sourceUrl: 'https://fixture.test', type: 'script' }), true);
assert.equal(await filters.match({ url: 'https://ads.fixture.test/allowed.js', sourceUrl: 'https://fixture.test', type: 'script' }), false);
assert.equal(await filters.match({ url: 'https://google-analytics.com/analytics.js', sourceUrl: 'https://fixture.test', type: 'script' }), true);
const css = await filters.cosmetics({ url: 'https://fixture.test', classes: ['fixture-ad'], ids: [] });
assert.match(css, /fixture-ad/); assert.doesNotMatch(css, /alert|injected/);
} finally { await filters.close(); }
});
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { createGateway } from '../src/gateway.mjs';
function request(gateway, url, authenticated = true) {
return new Promise((resolve, reject) => {
const req = http.get({ host: '127.0.0.1', port: gateway.port, path: url, headers: authenticated ? { 'Proxy-Authorization': `Basic ${Buffer.from(`${gateway.username}:${gateway.password}`).toString('base64')}` } : {} }, res => {
const chunks = []; res.on('data', chunk => chunks.push(chunk)); res.on('end', () => resolve({ status: res.statusCode, body: Buffer.concat(chunks).toString() }));
}); req.on('error', reject);
});
}
test('gateway denies unauthenticated requests, loopback and invalid schemes', async () => {
const gateway = await createGateway();
try {
assert.equal((await request(gateway, 'http://127.0.0.1/', false)).status, 407);
assert.equal((await request(gateway, 'http://127.0.0.1/')).status, 403);
assert.equal((await request(gateway, 'file:///etc/passwd')).status, 403);
assert.equal((await request(gateway, 'http://1.1.1.1:1234/')).status, 403);
} finally { await gateway.close(); }
});
test('gateway connects to the validated address and strips proxy credentials', async () => {
const server = http.createServer((req, res) => { assert.equal(req.headers['proxy-authorization'], undefined); res.end(req.headers.host); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
let lookups = 0;
const gateway = await createGateway({ allowedTestHosts: new Set(['fixture.test']), resolver: async () => { lookups++; return [{ address: '127.0.0.1', family: 4 }]; } });
try {
const result = await request(gateway, `http://fixture.test:${server.address().port}/`);
assert.equal(result.status, 200); assert.match(result.body, /^fixture.test:/); assert.equal(lookups, 1);
await gateway.close();
await assert.rejects(request(gateway, 'http://fixture.test/'));
} finally { await new Promise(resolve => server.close(resolve)); }
});
+35
View File
@@ -0,0 +1,35 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { WheelQueue } from '../../src/lib/browser/inputQueue.ts';
import { AutoScroll } from '../../src/lib/browser/autoScroll.ts';
import { FrameDelivery } from '../src/frame-delivery.mjs';
test('wheel bursts keep one pending call and discard stale direction', async () => {
const calls = [], releases = [];
const queue = new WheelQueue(input => { calls.push(input); return new Promise(resolve => releases.push(resolve)); });
const wheel = deltaY => ({ type: 'mouseWheel', x: 10, y: 10, deltaX: 0, deltaY });
queue.push(wheel(-100));
for (let index = 0; index < 500; index++) queue.push(wheel(-100));
queue.push(wheel(120));
assert.equal(calls.length, 1);
releases.shift()(); await Promise.resolve();
assert.equal(calls.length, 2);
assert.equal(calls[1].deltaY, 120);
queue.push(wheel(100)); queue.clear(); releases.shift()(); await Promise.resolve();
assert.equal(calls.length, 2);
queue.close(); queue.push(wheel(100)); assert.equal(calls.length, 2);
});
test('middle scrolling retains useful speed and has a quiet center', () => {
const scroll = new AutoScroll(); scroll.start({ x: 100, y: 100 }); scroll.delta(1000);
scroll.move({ x: 105, y: 105 }); assert.deepEqual(scroll.delta(1016), { x: 0, y: 0 });
scroll.move({ x: 100, y: 200 }); assert.ok(scroll.delta(1032).y >= 25);
scroll.release(); assert.equal(scroll.anchor, null);
});
test('frame delivery bounds the backlog and recovers after an abandoned view', () => {
const frames = new FrameDelivery(); const first = frames.sent(0); frames.sent(1);
assert.equal(frames.canSend(2), false); frames.acknowledge(first);
assert.equal(frames.canSend(3), true); frames.sent(3);
assert.equal(frames.canSend(4), false); assert.equal(frames.canSend(254), true);
});
@@ -0,0 +1,24 @@
// This IPC adapter exists only for the browser UI smoke test.
import { app } from 'electron';
import { createEngine } from '../src/engine.mjs';
app.enableSandbox();
app.setPath('userData', process.env.RS_INTERACTION_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let framePending = false;
const engine = await createEngine({ directory: process.env.RS_INTERACTION_ROOT, canEmitFrame: () => !framePending, emit: value => {
if (value.event === 'frame') framePending = true;
process.send?.({ event: value }, () => { if (value.event === 'frame') framePending = false; });
} });
process.on('message', async ({ id, command, args }) => {
try {
let result;
if (command === 'testEvaluate') result = await engine.tabs.get(args.tabId).view.webContents.executeJavaScript(args.code);
else if (command === 'shutdown') { await engine.shutdown(); process.send?.({ id, result: null }); app.exit(0); return; }
else result = await engine.command(command, args);
process.send?.({ id, result });
} catch (error) { process.send?.({ id, error: String(error) }); }
});
process.on('disconnect', () => { void engine.shutdown().finally(() => app.exit(0)); });
process.send?.({ ready: true });
});
@@ -0,0 +1,85 @@
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
if (!process.versions.electron) {
const { spawn } = await import('node:child_process');
const { default: electron } = await import('electron');
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-performance-'));
const child = spawn(electron, [import.meta.filename, ...process.argv.slice(2)], {
windowsHide: true, stdio: 'inherit', env: { ...process.env, RS_PERFORMANCE_ROOT: root },
});
const timeout = setTimeout(() => child.kill(), 45_000);
process.exitCode = await new Promise((resolve, reject) => { child.once('exit', code => resolve(code ?? 1)); child.once('error', reject); });
clearTimeout(timeout);
} else {
const { app } = await import('electron');
const { createEngine } = await import('../src/engine.mjs');
app.enableSandbox();
app.setPath('userData', process.env.RS_PERFORMANCE_ROOT);
app.on('window-all-closed', () => {});
app.whenReady().then(async () => {
let engine, code = 0;
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const frames = [];
let writable = true;
try {
engine = await createEngine({ directory: process.env.RS_PERFORMANCE_ROOT, canEmitFrame: () => writable, emit: value => {
if (value.event === 'frame') { frames.push({ time: performance.now(), bytes: value.data.length, tabId: value.tabId, data: value.data, mime: value.mime }); void engine?.command('frameAck', { tabId: value.tabId, frameId: value.frameId }); }
} });
const { tabId } = await engine.command('newTab');
const wc = engine.tabs.get(tabId).view.webContents;
if (wc.isLoading()) await new Promise(resolve => wc.once('did-stop-loading', resolve));
await engine.command('resize', { tabId, width: 1280, height: 800 });
await engine.command('visible', { tabId, visible: true });
await wc.executeJavaScript(`document.body.innerHTML = '<div style="height:6000px;background:linear-gradient(white,steelblue)"><canvas width="1280" height="720"></canvas></div>';
const c = document.querySelector('canvas').getContext('2d'); let tick = 0;
function paint() { c.fillStyle = '#fafafa'; c.fillRect(0,0,1280,720);
for (let i=0;i<80;i++) { c.fillStyle = 'hsl('+i*7+' 60% 50%)'; c.fillRect((i*71+tick*3)%1280,(i*39)%720,30,30); }
tick++; if (!window.stopAnimation) requestAnimationFrame(paint); } paint(); true;`);
await wait(750);
frames.length = 0;
const started = performance.now();
await wait(3000);
const elapsed = performance.now() - started;
const fps = frames.length * 1000 / elapsed;
const gaps = frames.slice(1).map((frame, index) => frame.time - frames[index].time).sort((a,b) => a-b);
const result = { configuredFps: wc.getFrameRate(), frames: frames.length, elapsedMs: Math.round(elapsed), fps: Number(fps.toFixed(1)), p95FrameGapMs: Math.round(gaps[Math.floor(gaps.length * .95)]), meanEncodedBytes: Math.round(frames.reduce((n,f) => n+f.bytes,0)/frames.length), viewport: '1280x800', platform: process.platform };
if (!process.argv.includes('--baseline')) { assert.equal(wc.getFrameRate(), 60); assert.ok(fps >= 24, `Native frame delivery must exceed 24 FPS: ${JSON.stringify(result)}`); }
await engine.command('input', { tabId, input: { type: 'mouseMove', x: 400, y: 400 } });
for (let n=0;n<20;n++) { await engine.command('input', { tabId, input: { type: 'mouseWheel', x: 400, y: 400, deltaY: -30, deltaX: 0 } }); await wait(16); }
await wait(150);
assert.ok(await wc.executeJavaScript('scrollY') > 100, 'Forwarded wheel input must scroll the native page.');
await engine.command('visible', { tabId, visible: false });
await wait(150); frames.length = 0; await wait(300);
assert.equal(frames.length, 0, 'Hidden tabs must stop sending frames.');
await engine.command('visible', { tabId, visible: true });
await wait(200); assert.ok(frames.length > 0, 'Visible tabs must resume frames.');
writable = false; frames.length = 0; await wait(200);
assert.equal(frames.length, 0, 'A busy transport must skip frames before encoding.');
writable = true; await wait(200);
assert.ok(frames.length > 0, 'Frames resume when the transport can accept them.');
const { nativeImage } = await import('electron');
frames.length = 0;
await engine.command('resize', { tabId, width: 1280, height: 800, scale: 2 });
await wait(500);
const highDpi = frames.at(-1);
const pixels = nativeImage.createFromDataURL(`data:${highDpi.mime};base64,${highDpi.data}`).getSize();
assert.ok(pixels.width >= 2560 && pixels.width <= 2562 && pixels.height >= 1600 && pixels.height <= 1602,
`High DPI must render physical pixels, allowing native window rounding: ${JSON.stringify(pixels)}`);
assert.equal(await wc.executeJavaScript('innerWidth'), 1280, 'High DPI keeps CSS page dimensions.');
result.highDpiPixels = pixels;
writable = false;
await wc.executeJavaScript('window.stopAnimation = true; document.body.style.background = "red"; true;');
await wait(400); frames.length = 0;
writable = true; await wait(300);
assert.ok(frames.some(frame => frame.mime === 'image/png'), 'The final lossless static frame must resume after transport backpressure ends.');
await mkdir('output', { recursive: true });
await writeFile(`output/performance-${process.argv.includes('--baseline') ? 'before' : 'after'}.json`, JSON.stringify(result, null, 2));
console.log(JSON.stringify(result));
console.log('PASS native scrolling, hidden frame pause, visible frame resume');
} catch (error) { console.error(error); code = 1; }
finally { await engine?.shutdown(); app.exit(code); }
});
}
+22
View File
@@ -0,0 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { addressInput, webUrl, publicAddress, resolvePublic } from '../src/policy.mjs';
test('addresses reject active schemes, credentials, controls and malformed URLs', () => {
for (const url of ['javascript:alert(1)', 'file:///etc/passwd', 'data:text/html,hi', 'runestone-ui://shell', 'https://user:[email protected]', 'https://example.com\n']) assert.throws(() => webUrl(url));
assert.equal(addressInput('a & b'), 'https://duckduckgo.com/?q=a%20%26%20b');
assert.equal(addressInput('example.com'), 'https://example.com/');
assert.equal(addressInput(''), 'about:blank');
assert.equal(addressInput('test query', 'bing'), 'https://www.bing.com/search?q=test%20query');
});
test('private, mapped, multicast and reserved addresses are blocked', () => {
for (const address of ['127.0.0.1', '10.0.0.1', '169.254.169.254', '192.168.1.2', '172.31.0.1', '100.64.1.1', '0.0.0.0', '224.0.0.1', '::1', '::', 'fc00::1', 'fe80::1', '::ffff:127.0.0.1', '2001:db8::1']) assert.equal(publicAddress(address), false, address);
assert.equal(publicAddress('1.1.1.1'), true);
assert.equal(publicAddress('2606:4700:4700::1111'), true);
});
test('DNS policy rejects mixed public/private answers and pins a validated result', async () => {
await assert.rejects(resolvePublic('example.test', async () => [{ address: '1.1.1.1', family: 4 }, { address: '127.0.0.1', family: 4 }]));
let calls = 0;
const address = await resolvePublic('example.test', async () => { calls++; return [{ address: '1.1.1.1', family: 4 }]; });
assert.equal(calls, 1); assert.equal(address.address, '1.1.1.1');
});
+8
View File
@@ -0,0 +1,8 @@
{
"identifier": "com.runestone.browser-test",
"productName": "RuneStone Browser Test",
"app": {
"windows": [{ "label": "main", "title": "RuneStone browser test (isolated)", "visible": false, "width": 1400, "height": 900, "decorations": false, "dragDropEnabled": false }]
},
"bundle": { "resources": { "browser-engine/": "browser-engine/" } }
}
@@ -0,0 +1,19 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { SnapshotOrder } from '../../src/lib/browser/snapshotOrder.ts';
test('late command replies cannot overwrite final Find results', () => {
const order = new SnapshotOrder();
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 1 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 3 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 2 }), false);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 3 }), false);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 4 }), true);
});
test('a new runtime resets the revision and rejects replies from the retired runtime', () => {
const order = new SnapshotOrder();
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 100 }), true);
assert.equal(order.accept({ runtimeId: 'engine-b', revision: 1 }), true);
assert.equal(order.accept({ runtimeId: 'engine-a', revision: 101 }), false);
});
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/store.mjs';
test('profiles and bookmarks persist without accepting caller-provided paths', () => {
const directory = mkdtempSync(path.join(os.tmpdir(), 'runestone-store-'));
try {
const store = new Store(directory);
assert.equal(store.data.settings.adblock, true);
assert.equal(store.data.settings.search, 'duckduckgo');
assert.deepEqual(store.data.profiles, [{ id: 'user', name: 'User' }]);
const profile = store.createProfile('../name-is-only-a-label');
assert.match(profile.id, /^[a-f0-9-]{36}$/);
store.bookmark(profile.id, 'https://example.com/', '<script>test</script>');
const restored = new Store(directory);
assert.equal(restored.data.bookmarks[0].profileId, profile.id);
assert.throws(() => store.profile('../../other'));
assert.throws(() => store.bookmark('user', 'javascript:alert(1)', 'unsafe'));
} finally { rmSync(directory, { recursive: true, force: true }); }
});
test('browser settings migrate, persist and reject invalid homepages and lists atomically', () => {
const directory = mkdtempSync(path.join(os.tmpdir(), 'runestone-settings-'));
try {
const legacy = new Store(directory);
delete legacy.data.settings.homepage; delete legacy.data.settings.filterLists;
writeFileSync(legacy.file, JSON.stringify(legacy.data));
const store = new Store(directory);
assert.equal(store.data.settings.homepage, '');
assert.equal(store.data.settings.filterLists.length, 2);
store.configure({ ...store.data.settings, homepage: ' https://example.com/home ', filterLists: ['https://example.com/list.txt'], linkDestination: 'external', adblock: false });
const saved = structuredClone(store.data.settings);
assert.deepEqual(new Store(directory).data.settings, saved);
for (const homepage of ['javascript:alert(1)', 'file:///C:/secret', 'https://user:[email protected]', 'search words']) {
assert.throws(() => store.configure({ ...saved, homepage }));
assert.deepEqual(store.data.settings, saved);
}
for (const filterLists of [['http://example.com/list'], ['https://example.com:444/list'], Array(9).fill('https://example.com/list'), 'not-an-array']) {
assert.throws(() => store.configure({ ...saved, filterLists }));
assert.deepEqual(new Store(directory).data.settings, saved);
}
store.configure({ ...saved, homepage: '', filterLists: [] });
assert.equal(new Store(directory).data.settings.homepage, '');
assert.deepEqual(new Store(directory).data.settings.filterLists, []);
} finally { rmSync(directory, { recursive: true, force: true }); }
});
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { Filters } from '../src/filters.mjs';
import { loadLists } from '../src/subscriptions.mjs';
import { fetchList } from '../src/downloads.mjs';
test('custom lists download once, work offline and stop blocking when removed', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'runestone-lists-'));
const filters = new Filters();
try {
let downloads = 0;
const addresses = ['https://filters.example.com/custom.txt'];
const options = { directory, download: true, fetch: async () => { downloads++; return '||custom-ad.fixture.test^'; } };
await filters.load('', addresses, options);
const request = { url: 'https://custom-ad.fixture.test/a.js', sourceUrl: 'https://fixture.test/', type: 'script' };
assert.equal(await filters.match(request), true);
await filters.load('', addresses, { directory });
assert.equal(await filters.match(request), true);
assert.equal(downloads, 1);
await filters.load('', []);
assert.equal(await filters.match(request), false);
await assert.rejects(loadLists(['https://filters.example.com/missing.txt'], { directory }), /missing/);
await assert.rejects(fetchList('https://127.0.0.1/list.txt'), /private network/);
await assert.rejects(fetchList('file:///secret.txt'), /HTTP/);
} finally { await filters.close(); await rm(directory, { recursive: true, force: true }); }
});
+204
View File
@@ -0,0 +1,204 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { TabSession } from '../../src/lib/browser/tabSession.ts';
function runtime() {
const tabs = new Map(), calls = [];
let sequence = 0;
const snapshot = () => ({ profiles: [{ id: 'user' }], tabs: [...tabs.values()], bookmarks: [], settings: {} });
const request = async (command, args = {}) => {
calls.push({ command, args });
if (command === 'state') return snapshot();
if (command === 'newTab') {
const id = `runtime-${++sequence}`;
tabs.set(id, { id, profileId: args.profileId, url: args.url || 'about:blank' });
return { tabId: id };
}
if (!tabs.has(args.tabId)) throw new Error('Unknown browser tab.');
if (command === 'closeTab') tabs.delete(args.tabId);
return snapshot();
};
return { tabs, calls, request, snapshot };
}
test('a moved tab keeps its runtime identity and survives source cleanup', async () => {
const engine = runtime();
const source = new TabSession(engine.request, { url: 'https://example.com/' }, () => {});
await source.connect();
const tabId = source.value.tabId;
source.detach();
await source.close();
const target = new TabSession(engine.request, { tabId }, () => {});
await target.connect();
assert.equal(target.value.tabId, tabId);
assert.equal(target.value.url, 'https://example.com/');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
await target.close();
assert.equal(engine.tabs.size, 0);
});
for (const reason of [
'The browser stopped responding. Open a new browser tab to restart it.',
'An existing connection was forcibly closed by the remote host. (os error 10054)',
'An established connection was aborted by the software in your host machine. (os error 10053)',
]) for (const failureAt of [1, 2, 3]) {
test(`opening recovers at request ${failureAt}: ${reason}`, async () => {
const engine = runtime(), phases = []; let requests = 0;
const session = new TabSession(async (command, args) => {
if (++requests === failureAt) {
engine.tabs.clear();
throw new Error(reason);
}
return engine.request(command, args);
}, { profileId: 'research', url: 'https://example.com/bookmark' }, value => phases.push(value.phase));
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(engine.tabs.size, 1);
assert.equal(engine.tabs.get(session.value.tabId).profileId, 'research');
assert.equal(engine.tabs.get(session.value.tabId).url, 'https://example.com/bookmark');
assert.ok(!phases.includes('disconnected'));
});
}
test('a failed state response reuses a tab that still exists', async () => {
const engine = runtime(); let requests = 0;
const session = new TabSession((command, args) => {
if (++requests === 3) throw new Error('The browser stopped responding.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-1');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
});
test('repeated opening failures stop after one retry and allow manual reconnect', async () => {
const engine = runtime(); let requests = 0, fail = true;
const session = new TabSession((command, args) => {
requests++;
if (fail) throw new Error('The browser stopped responding.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
assert.equal(requests, 2);
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'state');
assert.match(session.value.detail.reason, /stopped responding/);
await session.send('resize');
assert.equal(requests, 2);
fail = false;
await session.connect();
assert.equal(session.value.phase, 'ready');
});
test('an invalid profile does not retry tab creation', async () => {
const engine = runtime(); let creates = 0;
const session = new TabSession((command, args) => {
if (command === 'newTab') { creates++; throw new Error('Unknown browser profile.'); }
return engine.request(command, args);
}, { profileId: 'missing' }, () => {});
await session.connect();
assert.equal(creates, 1);
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'newTab');
});
test('closing while the first request fails prevents the retry', async () => {
let rejectRequest, requests = 0;
const session = new TabSession(() => {
requests++;
return new Promise((_resolve, reject) => { rejectRequest = reject; });
}, {}, () => {});
const opening = session.connect();
assert.equal(session.connect(), opening);
await session.close();
rejectRequest(new Error('The browser stopped responding.'));
await opening;
assert.equal(requests, 1);
assert.equal(session.value.phase, 'closed');
});
test('a restart during the first open creates a valid replacement tab', async () => {
const engine = runtime(); let restart = true;
const session = new TabSession(async (...args) => {
const value = await engine.request(...args);
if (args[0] === 'newTab' && restart) { restart = false; engine.tabs.clear(); }
return value;
}, { profileId: 'user', url: 'https://example.com/' }, () => {});
await session.connect();
assert.equal(session.value.phase, 'ready');
assert.equal(engine.tabs.size, 1);
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(engine.tabs.get('runtime-2').url, 'https://example.com/');
});
test('connection loss restores the same profile and URL without repeating input', async () => {
const engine = runtime();
const session = new TabSession(engine.request, { profileId: 'research', url: 'https://example.com/' }, () => {});
await session.connect(); engine.tabs.clear();
await session.send('input', { input: { type: 'char', keyCode: 'x' } });
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(engine.calls.filter(call => call.command === 'input').length, 1);
assert.equal(engine.tabs.get('runtime-2').profileId, 'research');
assert.equal(session.value.detail.operation, 'input');
assert.match(session.value.detail.reason, /Unknown browser tab/);
});
test('failed recovery stops background requests and keeps a specific retry error', async () => {
const engine = runtime(); let fail = false;
const session = new TabSession((command, args) => {
if (fail && command === 'newTab') throw new Error('The browser runtime is missing.');
return engine.request(command, args);
}, {}, () => {});
await session.connect(); engine.tabs.clear(); fail = true;
await session.send('resize', { width: 900, height: 600 });
assert.equal(session.value.phase, 'disconnected');
assert.equal(session.value.detail.operation, 'newTab');
assert.match(session.value.detail.reason, /runtime is missing/);
const requests = engine.calls.length;
await session.send('input'); await session.send('visible');
assert.equal(engine.calls.length, requests);
fail = false; await session.connect();
assert.equal(session.value.phase, 'ready');
});
test('late errors from the old tab cannot break the replacement', async () => {
const engine = runtime(); let rejectOld;
const session = new TabSession((command, args) => command === 'input'
? new Promise((_resolve, reject) => rejectOld = reject) : engine.request(command, args), {}, () => {});
await session.connect();
const pending = session.send('input'); engine.tabs.clear();
await session.send('resize');
rejectOld(new Error('Old tab timed out.')); await pending;
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-2');
assert.equal(session.value.detail.operation, 'resize');
});
test('closing during creation removes the late tab and leaves no running view', async () => {
const engine = runtime(); let finish;
const session = new TabSession((command, args) => command === 'newTab'
? new Promise(resolve => finish = () => resolve(engine.request(command, args))) : engine.request(command, args), {}, () => {});
const starting = session.connect();
await new Promise(resolve => setImmediate(resolve));
await session.close(); finish(); await starting;
assert.equal(session.value.phase, 'closed');
assert.equal(engine.tabs.size, 0);
});
test('an invalid address keeps the tab usable and does not restart it', async () => {
const engine = runtime();
const session = new TabSession((command, args) => {
if (command === 'navigate' && args.input.startsWith('javascript:')) throw new Error('Use an HTTP or HTTPS address without embedded credentials.');
return engine.request(command, args);
}, {}, () => {});
await session.connect();
await session.send('navigate', { input: 'javascript:alert(1)' });
assert.equal(session.value.phase, 'ready');
assert.equal(session.value.tabId, 'runtime-1');
assert.match(session.value.detail.reason, /HTTP or HTTPS/);
await session.send('navigate', { input: 'https://example.com/' });
assert.equal(session.value.message, '');
assert.equal(engine.calls.filter(call => call.command === 'newTab').length, 1);
});
+30 -5
View File
@@ -1,6 +1,6 @@
# Build and package RuneStone # Build and package RuneStone
[Development](development.md) · [Release history](releases.md) · [Installation](installation.md) [Development](development.md) · [Installation](installation.md)
This guide is for maintainers. Users install a supplied package through the installation guide. This guide is for maintainers. Users install a supplied package through the installation guide.
@@ -41,17 +41,42 @@ It does not register document types or start RuneStone when Windows starts.
See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options. See [Tauri's Windows installer documentation](https://v2.tauri.app/distribute/windows-installer/) for the packaging options.
## Hotfix installer versions
Hotfix installer versions use the same letter sequence as plugin versions: `a`, `b`, `c`, through `z`, then `aa`, `ab`.
Use `pnpm build:installer --version 0.1.23a` to produce that release.
The build command checks matching versions, preserves existing installers, and restores previous version fields if the build fails.
`package.json`, Cargo release metadata, installer metadata, the app version display, and release filenames retain the literal release version.
Cargo and Tauri require SemVer. The adapter encodes `0.1.23a` as `0.1.23+1` in their version fields.
Windows requires four numeric parts. The adapter encodes the same version as `0.1.23.1` in the numeric version resource.
The executable's FileVersion and ProductVersion strings retain `0.1.23a`.
These internal encodings represent the same release. They do not create a separate build or increase the numeric release version.
The shared NSIS comparison orders the numeric release first, then the hotfix suffix.
For example: `0.1.23 < 0.1.23a < 0.1.23b < 0.1.23z < 0.1.23aa < 0.1.24`.
The installer blocks downgrades before uninstall or update actions, including silent and passive installs.
Unknown version formats also block replacement. Reinstall and upgrade retain the existing installation by default.
Windows stores the SemVer encoding in its compatibility version field for older installers.
It stores the literal release version in `RuneStoneReleaseVersion` for the updated installer.
The app and installer version strings and release filenames use `0.1.23a`. Windows Apps can show the equivalent internal value `0.1.23+1`.
This keeps older numeric installers from treating a hotfix as an unknown or older release.
The Windows numeric resource limits each part and the hotfix index to 65535.
The adapter rejects versions outside those limits before it changes version fields.
The NSIS template derives from Tauri CLI 2.11.4. Check its changes when updating Tauri.
## Prepare a release ## Prepare a release
Each project uses its own `zz.yy.xx` version. Routine source edits and checks retain the current version. Each project uses its own `zz.yy.xx` version. Routine source edits and checks retain the current version.
Increase `xx` once when producing a new completed installer or plugin ZIP. Failed attempts do not consume a version. Increase `xx` once for each completed regular build. For a hotfix, increase the letter suffix. Failed attempts do not consume a version.
Keep version fields consistent, and restore them if no build completes. Keep version fields consistent, and restore them if no build completes.
Increase `yy` or `zz` only for a user-directed release, then reset the lower fields as defined in [the version policy](../AGENTS.md#versioning). Increase `yy` or `zz` only for a user-directed release, then reset the lower fields as defined in [the version policy](../AGENTS.md#versioning).
Publishing an existing artifact does not change its version. Publishing an existing artifact does not change its version.
1. Set the same version in `package.json`, `src-tauri/Cargo.toml`, and `src-tauri/tauri.conf.json`. 1. Select the release version under the shared version policy.
2. Update `src-tauri/Cargo.lock` with Cargo if the package version changed. 2. Run the checks above.
3. Run the checks and build command above. 3. Run `pnpm build:installer --version <version>`. The adapter sets matching release and toolchain versions.
4. Test the installer on a clean Windows account with the checks below. 4. Test the installer on a clean Windows account with the checks below.
5. Attach the setup file and release notes to the repository release or your chosen download page. 5. Attach the setup file and release notes to the repository release or your chosen download page.
+206
View File
@@ -0,0 +1,206 @@
# Design decision log
[Interface design](ui-design.md) · [Agent instructions](../AGENTS.md)
The design guide holds current rules. This log records intentional rule changes, recurring problems, and scoped exceptions for RuneStone and its plugins.
An isolated correction belongs in its normal card or commit record. It does not need an entry here.
## Use this log
Copy the matching template into Entries. Give each entry a unique sequential ID, such as UI-001, and a date.
Replace every placeholder. Use relative links to guide sections, source files, and saved evidence where possible.
Record missing evidence as pending. Do not claim acceptance or completed checks without evidence.
For a rule change or exception, record the decision source, such as the user's direction or an accepted review.
A proposed entry does not authorize a departure from the current guide.
Update the guide in the same change as an accepted rule change. Summarize an active exception beside its affected rule and link its entry.
Record the scope as the app, named plugins, or specific controls. Avoid silently extending a local decision to every plugin.
For recurring problems, link separate occurrences or a regression after a prior correction. Record unknown causes as unknown.
Update an existing problem entry when it recurs. Mark it resolved only after the prevention action and relevant check pass.
Keep earlier decisions when a later entry replaces them. Mark them superseded and link the replacement in both directions.
When an exception ends, mark it retired and remove its active exception note from the guide.
Entry status describes the record. It does not move a Kanban card to Done or replace user acceptance.
## Templates
### Rule change
```markdown
### UI-NNN — Short decision title
- Type: Rule change
- Date: YYYY-MM-DD
- Status: Proposed / Accepted / Superseded
- Decision source: User direction or review link
- Previous rule: Prior behavior and guide section
- New rule: Chosen behavior and current guide section
- Reason: User benefit and relevant design principle
- Scope: App, named plugins, and affected controls
- Shared implementation: Component or token paths
- Exceptions: None, or linked exception entries
- Evidence: Reference images, check results, and review link, or pending items
- Replaces / replaced by: None, or linked entries
```
### Recurring problem
```markdown
### UI-NNN — Short problem title
- Type: Recurring problem
- Date: YYYY-MM-DD
- Status: Open / Resolved
- Existing rule: Link to the rule that still applies
- Scope: App, named plugins, and affected controls
- Occurrences: Links to repeated violations or a regression and its prior correction
- Cause: Evidence for the cause, or unknown with the next investigation step
- Correction: How the current violation returns to the existing rule
- Prevention: Shared component change, override removal, check, or needed rule clarification
- Check: How to detect recurrence and the actual result, or pending
- Evidence: Reference images and card, commit, or review links
- Resolution / recurrence: Date and result, or pending. Reopen this entry if the problem returns.
```
### Exception
```markdown
### UI-NNN — Short exception title
- Type: Exception
- Date: YYYY-MM-DD
- Status: Proposed / Accepted / Retired / Superseded
- Decision source: User direction or review link
- Current rule: Guide section and its exception note
- Departure: Exact difference from the rule
- User benefit: Why the standard pattern does not meet this need
- Scope: Specific app or plugin controls and states where the exception applies
- Shared implementation: Component or token paths and why a local difference is necessary
- Review: Responsible person or role, plus a date or concrete trigger
- Exit condition: When the standard pattern can replace the exception
- Evidence: Reference images, accessibility and interaction checks, or pending items
- Replaces / replaced by: None, or linked entries
```
## Entries
### UI-003 — Quiet menu choices
- Type: Rule change
- Date: 2026-10-12
- Status: Accepted
- Decision source: User-selected cards d10adda6 and 48687378.
- Previous rule: Menus used accent outlines and checkmarks for radio choices. Every row reserved an icon column.
- New rule: Use neutral outlines, quiet radio highlights, and text columns for menus without icons.
- Reason: Reduce competing accents and make the current choice clear.
- Scope: Host menus and Project Management menus through the host API.
- Shared implementation: actionMenu.ts, menu.css, and --rs-menu-border.
- Exceptions: None.
- Evidence: Shared menu checks and appearance checks passed. Screenshots are in output/appearance-pass3 and output/pm-october12.
- Replaces: The outline and radio presentation from UI-002. UI-006 replaces this entry's panel outline. Its quiet radio choices remain.
### UI-004 — Detached tab work area
- Type: Rule change
- Date: 2026-10-12
- Status: Accepted
- Decision source: User-selected card 5a8bc531.
- Previous rule: Detached tabs hid side panes and allowed users to reopen them.
- New rule: Detached tabs do not mount side panes, their switches, or the plugin ribbon.
- Reason: Keep the new window focused on the transferred tab.
- Scope: Windows opened through tab transfer.
- Shared implementation: Workbench.svelte and its detached grid layout.
- Exceptions: None.
- Evidence: Browser transfer checks passed in both themes and narrow windows. Native window acceptance remains pending.
- Replaces: None.
### UI-005 — Heading spacing
- Type: Rule change
- Date: 2026-10-12
- Status: Accepted
- Decision source: User-selected card 17207fbc.
- Previous rule: Document headings used separator lines.
- New rule: Use spacing between headings and sections without separator lines.
- Reason: Keep attention on the document text.
- Scope: Writer and Reader headings.
- Shared implementation: src/app.css heading rules.
- Exceptions: None.
- Evidence: Editor browser checks passed in both themes. Screenshots are in output/editor-october12.
- Replaces: None.
### UI-002 — Share the requested dropdown design
- Type: Rule change
- Date: 2026-10-11
- Status: Accepted
- Decision source: RuneStone cards 71b17a71-13cb-4d8c-a9cb-8822b433a889 and 52b6f235-6c3e-44c0-9ab6-dcbfd371c0ce, selected by the user for implementation.
- Previous rule: Menus used 26-pixel rows, 12-pixel text, and the ordinary panel border. Submenu parents had no default action.
- New rule: Share the reference dropdown geometry across menus. A submenu parent can also run a default action.
- Reason: Make dropdown choices easier to read. Let users create a blank note directly from New note.
- Scope: Host action menus and plugin menus that use the host API, including theme, appearance, board, and list menus.
- Shared implementation: [actionMenu.ts](../src/lib/ui/actionMenu.ts), [menu.css](../src/lib/ui/menu.css), and the `--rs-menu-*` tokens in [tokens.css](../src/lib/theme/tokens.css).
- Exceptions: None. Existing older-host plugin fallbacks remain available.
- Evidence: The [card reference](../output/pass3-ref-0ce1efe3-7e2a-40a8-99bb-64215aa9d977.png). Shared menu checks passed in both themes. Further screenshots accompany the card review.
- Replaces / replaced by: The outline and radio presentation changed in [UI-003](#ui-003--quiet-menu-choices). Other rules remain.
### UI-001 — Separate design decisions from routine corrections
- Type: Rule change
- Date: 2026-10-11
- Status: Accepted
- Decision source: The user's request to implement this policy in the guide, agent instructions, and decision log.
- Previous rule: The guide required UI review evidence but did not distinguish corrections, rule changes, recurring problems, and exceptions.
- New rule: Use the [record categories](ui-design.md#current-rules-and-decision-history) and templates above. Keep current design rules in the guide.
- Reason: Preserve useful design history without a log entry for every isolated correction.
- Scope: Documentation and review workflow for the app and its plugins.
- Shared implementation: [Agent instructions](../AGENTS.md#ui-work-record-design-decisions) and [review evidence](ui-design.md#evidence-for-review). No component or token change.
- Exceptions: None.
- Evidence: The user's explicit instruction in this chat. This entry changes documentation policy and has no visual reference image.
- Replaces / replaced by: None.
### UI-006 — Borderless shared menus
- Type: Rule change
- Date: 2026-10-12
- Status: Accepted
- Decision source: User-selected card 8aa18bb1 requests removal of menu borders across Project Management.
- Previous rule: Shared menus used a neutral panel outline.
- New rule: Shared menus use a transparent outline while retaining their shadow, inset rows, and keyboard focus.
- Reason: Keep attention on the work and give plugin menus one shared design.
- Scope: Host action menus and Project Management menus through the host API. Older-host fallback menus also omit panel borders.
- Shared implementation: --rs-menu-border in tokens.css, menu.css, and PM style.css.
- Exceptions: None.
- Evidence: Menu and PM check reports and screenshots accompany the card review.
- Replaces: The panel outline from UI-003. Its quiet radio choices remain.
### UI-007 — Repeated menu drift
- Type: Recurring problem
- Date: 2026-10-12
- Status: Resolved
- Existing rule: Shared action menus in the interface guide.
- Scope: Browser settings and Project Management card, priority, background, and list-status controls.
- Occurrences: Cards 41461dfe and 1d823866 follow earlier menu corrections in UI-002 and UI-003. Card b8cc5ef1 repeats the issue in background and list-status choices.
- Cause: Browser settings used native selects. PM card and priority controls used local popup renderers. Background and list-status choices missed the shared-choice conversion.
- Correction: Use the shared menu API for these controls. Match the host background labels and retain the numeric overlay field.
- Prevention: Check each background choice and the list-status choice with the real host menu API, in both themes and narrow layouts.
- Check: The current host and PM check reports record the results.
- Evidence: output/round4-pm-report.json, output/round4-editor-menu-report.json, and output/round4-overlay-report.json.
- Resolution: The combined checks passed on 2026-10-12. Reopen this entry if the problem returns.
### UI-008 — Keep native editing menus focused
- Type: Rule change
- Date: 2026-10-12
- Status: Accepted
- Decision source: User-selected card 48671ea0.
- Previous rule: Editable native menus exposed all default WebView2 tools.
- New rule: Retain recognized editing commands and omit unsupported system tools.
- Reason: Keep note menus focused on work within RuneStone.
- Scope: Editable WebView2 targets in the host.
- Shared implementation: src-tauri/src/spelling.rs filters command names before either menu path.
- Exceptions: Separators retain their layout role. Non-editable native menus retain their unrelated actions.
- Evidence: Native payloads and two full smoke runs in output/todo-menus.
- Replaces: None.
+15
View File
@@ -186,3 +186,18 @@ 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. In the Windows development window, press Ctrl+Shift+I to open the web inspector.
Use its console for frontend errors. Use its console for frontend errors.
See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector). See [Tauri's inspector instructions](https://v2.tauri.app/develop/#opening-the-web-inspector).
## Built-in browser runtime
The browser interface lives in `src/lib/browser`. Its Electron runtime, tests, assets, and third-party notices live in `browser-runtime`.
The host no longer needs a sibling Browser checkout. Keep the old checkout until its local work and history no longer need preservation.
1. Run `npm ci --prefix browser-runtime` to install the pinned runtime dependencies.
2. Run `pnpm browser:check` and `pnpm browser:test` for source checks.
3. Run `pnpm browser:test:engine` for native Electron checks.
4. Run `npm --prefix browser-runtime run package` to prepare the runtime.
5. Run `pnpm browser:stage` before a host installer build.
Runtime compilation and staging do not produce a new RuneStone installer version.
The installer includes the staged runtime from `src-tauri/browser-engine`. Follow the project version policy when creating that installer.
Use `scripts/browserInteraction.smoke.mjs` to check the host interface against a real runtime.
Keep its results separate from the native Tauri window checks.
+1 -2
View File
@@ -1,6 +1,6 @@
# Installation and updates # Installation and updates
[RuneStone](../README.md) · [User guide](user-guide.md) · [Release history](releases.md) [RuneStone](../README.md) · [User guide](user-guide.md)
| Platform | Current route | | Platform | Current route |
| --- | --- | | --- | --- |
@@ -32,7 +32,6 @@ If WebView2 is missing, setup downloads the runtime. Keep your internet connecti
Run the installer directly. An existing installation defaults to reinstall, including the same version. Run the installer directly. An existing installation defaults to reinstall, including the same version.
You do not need to uninstall first. Setup preserves workspace files and settings and blocks version downgrades. You do not need to uninstall first. Setup preserves workspace files and settings and blocks version downgrades.
The [release notes](releases.md) record which installer checks still need desktop acceptance.
## Try the source on Linux ## Try the source on Linux
+1 -1
View File
@@ -1,6 +1,6 @@
# Linux readiness # Linux readiness
[Developer guide](development.md) · [Release guide](releases.md) [Developer guide](development.md)
Linux support is experimental. No native Linux build or desktop test is recorded yet. Linux support is experimental. No native Linux build or desktop test is recorded yet.
Voice typing is outside the Linux acceptance criteria. Voice typing is outside the Linux acceptance criteria.
+4 -3
View File
@@ -5,16 +5,17 @@ Use names without spaces for source folders and package metadata.
| Plugin name | Source folder after manual rename | Current source folder | npm package name | Stable plugin ID | | Plugin name | Source folder after manual rename | Current source folder | npm package name | Stable plugin ID |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| Browser | `RuneStone_Browser` | `RuneStone_WebViewer` | `runestone-browser` | `runestone.browser` | | Browser (built in) | `RuneStone/browser-runtime` | Not applicable | `runestone-browser` | `runestone.browser` (legacy) |
| Local Autocomplete | `RuneStone_LocalAutocomplete` | `RuneStone_LocalModel` | `runestone-local-autocomplete` | `runestone.local-autocomplete` | | Local Autocomplete | `RuneStone_LocalAutocomplete` | `RuneStone_LocalModel` | `runestone-local-autocomplete` | `runestone.local-autocomplete` |
| Project Management | `RuneStone_ProjectManagement` | `RuneStone_PM` | `runestone-project-management` | `runestone.pm` | | Project Management | `RuneStone_ProjectManagement` | `RuneStone_PM` | `runestone-project-management` | `runestone.pm` |
## Manual source folder changes ## Manual source folder changes
The team must rename the three source folders because local tools and saved project paths can depend on them. The remaining plugin folder changes need care because local tools and saved project paths can depend on them.
Browser source now lives inside RuneStone and does not need a separate folder rename.
These changes remain pending. The current folders and repository URLs still use their earlier names. These changes remain pending. The current folders and repository URLs still use their earlier names.
1. Close development servers and tools that use the three source folders. 1. Close development servers and tools that use the affected plugin folders.
2. Rename each current source folder to its matching name in the table. 2. Rename each current source folder to its matching name in the table.
3. Update saved editor projects, shortcuts, task paths, and local scripts that contain the old absolute paths. 3. Update saved editor projects, shortcuts, task paths, and local scripts that contain the old absolute paths.
4. Update cross-project documentation links after the folders move. 4. Update cross-project documentation links after the folders move.
+20 -10
View File
@@ -152,7 +152,8 @@ Closing the plugin tab or disabling the package disposes the view.
The default placement is `"dialog"`, so existing packages keep their current behavior. The default placement is `"dialog"`, so existing packages keep their current behavior.
Older hosts ignore the placement field. Plugins that require editor placement need RuneStone 0.1.5 or later. Older hosts ignore the placement field. Plugins that require editor placement need RuneStone 0.1.5 or later.
All packages use one API and the same installation, enable, disable, and removal lifecycle. All packages use one API and the same installation, enable, disable, and removal lifecycle.
Versions use three numeric parts. Schema and API versions must match the supported version exactly. Versions use three numeric parts with an optional lowercase hotfix suffix, such as `0.2.28a`.
Schema and API versions must match the supported version exactly.
The `runestone.*` prefix follows the same rules as other package IDs. It does not prove the publisher's identity. The `runestone.*` prefix follows the same rules as other package IDs. It does not prove the publisher's identity.
Package names use ASCII letters, digits, dots, underscores, and hyphens, with forward slashes between directories. Package names use ASCII letters, digits, dots, underscores, and hyphens, with forward slashes between directories.
@@ -172,7 +173,7 @@ Use `zz.yy.xx` and keep routine implementation work in the current `zz.yy` serie
| Part | When to increase it | | Part | When to increase it |
| --- | --- | | --- | --- |
| `xx` | Each new completed plugin ZIP build. The number has no two-digit limit. | | `xx` | Each new completed regular plugin ZIP build. Hotfixes increase the letter suffix. |
| `yy` | A deliberate release ready for build testing, with user direction. Reset `xx` to zero. | | `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. | | `zz` | A full release, with user direction. Reset `yy` and `xx` to zero. |
@@ -181,11 +182,16 @@ Set the next version when producing the ZIP. Intermediate compilation output doe
If no build completes, restore the previous version fields. Failed attempts and retries do not consume version numbers. 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. 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. 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`. A hotfix fixes one item or a narrowly scoped problem in an existing release.
The current plugin packager and installer require numeric versions in `plugin.json`. Use letters in the actual package version: `0.2.28` → `0.2.28a` → `0.2.28b`.
Until that contract supports suffixes, use letters only in release labels or tags. Keep the numeric base for hotfix builds.
Increase `xx` for each changed hotfix ZIP and record its numeric package version in the release notes. Advance hotfix suffixes in this order: `a`, `b`, `c`, through `z`, then `aa`, `ab`, and later suffixes.
Keep the package and manifest versions equal. Do not bypass the host validator or overwrite an existing release ZIP. The next regular build increases `xx` and removes the suffix: `0.2.28b` → `0.2.29`.
Keep the package version, manifest version, build metadata, ZIP name, release notes, and tag consistent.
For example, package version `0.2.28a` produces `runestone.pm-0.2.28a.zip` and uses tag `v0.2.28a`.
The shared packager and updated native installer accept these suffixes. Older hosts with numeric-only validation reject suffixed packages.
Do not substitute a numeric increment for a hotfix. Add suffix support or report a format blocker before building.
Do not bypass validation or overwrite an existing release ZIP.
## Build and release a plugin ## Build and release a plugin
@@ -269,7 +275,8 @@ Keep the package contract above. No repository manifest or special branch layout
Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases. Use `v<version>` for ordinary release tags. Use a clearly named trial tag for temporary prereleases.
Keep the manifest version and package version equal. Keep published release files unchanged. Keep the manifest version and package version equal. Keep published release files unchanged.
Increase the version when building a new ZIP, before publication. 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. Prerelease builds follow the same version policy. Each new regular ZIP gets the next numeric build version.
Each hotfix ZIP gets the next letter suffix. Use an explicit trial tag for prereleases.
The ZIP must contain `plugin.json` at its root, the compiled entry module, and all required assets and dependencies. 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. Do not attach a source ZIP as the plugin package. Gitea's automatic source archives do not count as release attachments.
@@ -366,6 +373,9 @@ export function activate(api) {
| `assets.read(path)` | Read package bytes as a `Uint8Array` | | `assets.read(path)` | Read package bytes as a `Uint8Array` |
Command and view IDs must be unique within their respective plugin collections. Command and view IDs must be unique within their respective plugin collections.
Plugin commands can supply an optional `icon` from the view icon set.
Use the same icon for the command and its view. Older hosts can ignore this field.
Sidebar views belong in the left navigation. Views with a direct navigation button do not repeat in the plugin launch menu.
Plugin configuration appears in Settings under the plugin name. Plugin configuration appears in Settings under the plugin name.
Register a view with `settings: true` to add its configuration page. 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. The host mounts that view inside Settings and removes it from the launch menu.
@@ -457,8 +467,8 @@ Users can open browser tabs, manage profiles in Settings, and use web bookmarks
The existing browser data directory stays the same. Profiles, bookmarks, cookies, and settings remain available. The existing browser data directory stays the same. Profiles, bookmarks, cookies, and settings remain available.
An old Browser package can be removed from Settings. The host does not load it alongside the built-in browser. An old Browser package can be removed from Settings. The host does not load it alongside the built-in browser.
The interface source lives in `src/lib/browser/`. The runtime source remains in `../RuneStone_Browser/`. The interface source lives in `src/lib/browser/`. The runtime source lives in `browser-runtime/`.
Stage the runtime with that checkout's `npm run stage:host` before creating an installer. Run `pnpm browser:stage` after packaging that runtime and before creating an installer.
The main Tauri configuration includes `src-tauri/browser-engine/` as an installer resource. The main Tauri configuration includes `src-tauri/browser-engine/` as an installer resource.
Browser startup obtains a session token for its window. Native requests check that token, and cleanup revokes it. Browser startup obtains a session token for its window. Native requests check that token, and cleanup revokes it.
-32
View File
@@ -1,32 +0,0 @@
# Test build: RuneStone 0.1.13 and Project Management 0.2.18
These builds include the 14 Kanban cards prepared for user review on October 8, 2026.
See the [work record](archive/kanban-review-2026-10-08.md) for assignments and checks.
## Changes
- The tab bar uses available space and keeps one New tab after the last tab closes.
- Settings and plugin rows use shared dimensions and compact spacing.
- Repeated formatted paste no longer duplicates content or freezes the editor.
- Card descriptions edit inside the card and display saved Markdown formatting.
- Priorities use a nearby picker with colors and icons.
- Cards can move between boards while preserving their content and metadata.
- Image controls overlay the viewer. Outside clicks and Escape close it.
- Board menu actions have icons. The title edit indicator appears on hover or keyboard focus.
## Local installation
Run `RuneStone_0.1.13_x64-setup.exe` to reinstall or update RuneStone.
The installer includes the existing browser runtime and retains the downgrade restriction.
In Settings → Plug-ins, uninstall the previous Project Management package.
Restart RuneStone, then choose Install plugin ZIP and select `runestone.pm-0.2.18.zip`.
Workspace cards and retained plugin settings survive removal of the old package.
## Checks
Project Management passed its type check, 101 unit tests, and 103 browser tests after packaging.
Host native tests passed 63 tests, with three ignored. The source checks passed all 191 host unit tests and focused browser checks.
Native installer use and the changed desktop behavior remain for user acceptance.
All 14 cards remain in Review.
Both artifacts passed integrity checks. The plugin file hashes match its build record.
-35
View File
@@ -1,35 +0,0 @@
# Test build: RuneStone 0.1.14, Project Management 0.2.19, and Git 0.1.1
These builds cover 16 selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Browser tabs, profiles, and bookmarks now belong to RuneStone. The installer includes the existing Chromium runtime.
- The left ribbon, shared menus, and table cell spacing use compact dimensions and clear icons.
- Project Management improves card spacing, title focus, outside clicks, image dismissal, and detail icons.
- Large boards retain their view and scroll position. Board selection retains the current tab position.
- Label deletion clears saved references. Card archive actions retain workspace files.
- Git adds a sidebar for status, file diffs, staging, unstaging, commits, and line history.
## Local installation
Run `RuneStone_0.1.14_x64-setup.exe` to reinstall or update RuneStone. Setup retains the downgrade restriction and preserves workspace files and settings.
Install `runestone.pm-0.2.19.zip` and `runestone.git-0.1.1.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing Project Management installation, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace cards survive package removal.
Browser needs no separate ZIP. An old Browser package can be removed through Settings. Browser profiles and bookmarks retain their existing storage.
## Checks and limits
The host passed its source check, 193 unit tests, and 71 native tests. Three native tests remain ignored.
Focused browser checks passed for the built-in browser, plugin access, menus, layouts, and selections in both themes and narrow windows.
Project Management passed its type check, 98 unit tests, and 111 browser tests after packaging. Git passed its source check and four unit tests.
Git also passed seven native host tests and its standalone and real-host browser checks before packaging.
The ZIP manifests and all extracted files match the compiled files.
Browser tests use native mocks. Native browser use, installer behavior, and desktop acceptance still need user review.
Git requires installed Git and a workspace at the repository root. Linked worktrees, remote actions, branch changes, and repository creation remain unsupported.
Git retains commit hooks. Diff tabs refresh when the user selects the file again.
-37
View File
@@ -1,37 +0,0 @@
# Test build: RuneStone 0.1.15, Project Management 0.2.20, and Terminal 0.1.2
These builds cover eight selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Tables retain separate plain paragraphs without extra blank lines. Cell dimensions stay stable during edits and navigation.
- IDE and Terminal text use a lighter font weight.
- Shared menus use compact 14-pixel icons and 26-pixel rows.
- Git and other plugin sidebar views appear beside Files, Search, and Bookmarks in the top header.
- Project Management retains horizontal scroll when hidden tabs refresh or create a board. Each list has an inline Add a card control.
- The UI design reference records shared dimensions, icons, corners, selections, and menus.
## Local installation
Run `RuneStone_0.1.15_x64-setup.exe` to reinstall or update RuneStone. Setup preserves workspace files and settings, and blocks version downgrades.
Install `runestone.pm-0.2.20.zip` and `runestone.terminal-0.1.2.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
Git 0.1.1 remains the current package. The host supplies its new navigation position.
The installer includes the built-in browser and its Chromium runtime.
## Checks and limits
The host passed its source check, 195 unit tests, and 71 native tests. Three native tests remain ignored.
Browser checks passed for shared menus, table navigation, plugin tab order, workbench layout, and the actual Git navigation view.
Table checks cover both themes, two window widths, save, undo, and cell dimensions.
Project Management passed its type check, 98 unit tests, and all 116 browser tests after packaging.
Its final compiled module passed host checks for scroll retention in both legacy and managed board tabs.
Terminal passed its source check, six unit tests, and browser checks, including its rendered font weight in the light theme.
Both ZIPs contain a root manifest. Every archived file matches its compiled source hash.
Browser tests use native mocks. Native installer behavior and desktop acceptance still need user review.
The build creates local artifacts. It does not install, publish, or commit them.
-70
View File
@@ -1,70 +0,0 @@
# Test build: RuneStone 0.1.16, Project Management 0.2.21, and Git 0.1.2
These local builds cover eight selected cards on October 8, 2026. The cards remain in Review for user acceptance.
## Changes
- Plain editable text permits the native spelling menu. Selected text and tables retain their action menus.
- New file accepts the complete filename. Rename includes the extension.
- Code editors share a 13px font size and 21px line height.
- GPT, Claude, Sakura, and RuneStone support light and dark modes. Terminal uses green text on black.
- Browser settings list and filter cookies and history for each profile. Users can remove individual entries.
- Project Management uses the empty list space for its card composer. Focus changes hide the composer and retain its draft.
- Git adds push, pull, and separate collapsible Changes and Graph sections.
See the [source changes and limits](archive/kanban-changes-2026-10-08.md) for more details.
## Local installation
Run `RuneStone_0.1.16_x64-setup.exe` to reinstall or update RuneStone.
Setup defaults to reinstall for an existing version and blocks downgrades. Workspace files and user settings remain outside the installation folder.
Install `runestone.pm-0.2.21.zip` and `runestone.git-0.1.2.zip` through Settings → Plug-ins → Install plugin ZIP.
For an existing plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
The installer includes the rebuilt Browser runtime. Browser needs no separate plugin ZIP.
## Build files
| Build | Local path | Bytes |
| --- | --- | --- |
| RuneStone 0.1.16 | `src-tauri/target/release/bundle/nsis/RuneStone_0.1.16_x64-setup.exe` | 125007691 |
| Project Management 0.2.21 | `../RuneStone_ProjectManagement/plugin-packages/runestone.pm-0.2.21.zip` | 160626 |
| Git 0.1.2 | `../RuneStone_Git/releases/runestone.git-0.1.2.zip` | 6563 |
## SHA256 checksums
```text
a8b0b2532aec27d2862cf3d3924383c67c66b15493456f43158aace0fcf79c5f RuneStone_0.1.16_x64-setup.exe
0003494fc6c671121e11adb3334b2e973f755fd324abc0860c05af19caaa00e5 runestone.pm-0.2.21.zip
8748d264fe9daa563a7e426372d7c965ad27a019ce35842c343a9dfdc7e15b2c runestone.git-0.1.2.zip
```
The installer folder also contains `RuneStone_0.1.16_release-checksums.sha256` with these three checksums.
## Checks and limits
The host passed its source check, 195 unit tests, and 75 native tests. Three native tests remain ignored.
The installer build completed. Both the application and setup executable report version 0.1.16.
The generated installer includes all 73 Browser resources and retains the default reinstall choice and downgrade restriction.
Browser checks cover filenames, extension changes, shared menus, fonts, appearance, and cookie and history controls.
The final appearance check passed all palettes, both modes, three-window sync, reload, and narrow settings.
Terminal-to-Sakura changes restore the original syntax colors. Existing and new editors pass the same check.
Project Management passed its type check, 98 unit tests, and all 119 browser tests after packaging.
The browser suite includes both compiled-plugin checks.
Git passed source checks, four plugin unit tests, 11 native fixture tests, and sidebar browser checks.
Both ZIPs contain a root manifest. Every archived file matches its compiled source SHA256 hash.
The packaged Browser runtime passed native Electron checks, including individual cookie and history removal.
All 73 staged runtime files match the packaged source SHA256 hashes.
Runtime packaging is intermediate installer output and does not change the Browser version.
Native spelling suggestions and actual correction still need desktop acceptance.
Actual installation, reinstall, settings retention, and downgrade protection still need desktop acceptance.
The Git graph shows at most 100 commits. Push and pull require a configured upstream and existing Git authentication.
Pull permits only fast-forward updates.
These builds create local artifacts. They do not install, publish, or commit them.
-74
View File
@@ -1,74 +0,0 @@
# Test build: RuneStone 0.1.17 and Git 0.1.4
These local builds cover three selected cards on October 8, 2026.
The cards remain in Review for user acceptance.
## Changes
- WebView2 supplies spelling suggestions to the shared menu. Native commands apply corrections.
- Claude uses Anthropic colors and local Lora and Poppins font stacks, with Georgia and Arial fallbacks.
- Sakura uses the card palette and light mode. Saved dark Sakura selections migrate to light Sakura.
- GPT and Terminal themes are removed. Saved selections migrate to RuneStone with their previous light or dark mode.
- Git history draws commit nodes and parent links, with branches, tags, messages, authors, and dates.
See the [source changes and checks](archive/kanban-followup-2026-10-08.md) for more details.
## Local installation
Run `RuneStone_0.1.17_x64-setup.exe` to reinstall or update RuneStone.
Setup defaults to reinstall for an existing version and blocks downgrades.
Workspace files and user settings remain outside the installation folder.
Install `runestone.git-0.1.4.zip` through Settings → Plug-ins → Install plugin ZIP.
This Git package requires RuneStone 0.1.17 or later.
For an existing Git plugin, remove its old package and restart RuneStone before installing the new ZIP.
Retained plugin settings and workspace files survive package removal.
Browser remains part of the installer. All 73 staged runtime files match the previous packaged source hashes.
The Browser runtime and other plugins need no new release build for these changes.
## Build files
| Build | Local path | Bytes |
| --- | --- | --- |
| RuneStone 0.1.17 | `src-tauri/target/release/bundle/nsis/RuneStone_0.1.17_x64-setup.exe` | 125009581 |
| Git 0.1.4 | `../RuneStone_Git/releases/runestone.git-0.1.4.zip` | 8004 |
## SHA256 checksums
```text
378b95b6d7f1d4f0413449e67264780d6d84e46e53b8304e6c63296917ec716c RuneStone_0.1.17_x64-setup.exe
eca6eeb9304f344f667c0d31666db54b207efb86c0b7a109c1ce6f563c61c859 runestone.git-0.1.4.zip
```
The installer folder also contains `RuneStone_0.1.17_release-checksums.sha256` with these checksums.
## Checks and limits
The host passed its source check with no errors or warnings and 198 unit tests.
Native tests passed 78 tests, with three ignored.
The frontend production build passed before packaging and during the installer build.
The locked NSIS build completed with the normal `com.runestone.app` identifier and window configuration.
The application and installer report version 0.1.17.
The generated installer includes all 73 Browser resources and retains the default reinstall choice and downgrade restriction.
Git passed its source check, five unit tests, compilation, and sidebar, UI, and host browser checks.
The final ZIP contains a root manifest, a readable entry module, styles, and installation guidance.
Every archived plugin file matches its compiled source SHA256 hash.
All 73 archived Browser resources match their staged source hashes.
The installer passes the 7-Zip archive integrity check.
The archived application differs from the release executable only in the three-byte Tauri NSIS bundle marker.
Git 0.1.3 remains a superseded local artifact. Version 0.1.4 adds the required host version and current feature guidance to its README.
Neither build replaces an earlier release file.
Appearance checks passed all five supported theme and mode combinations, migration, three-window sync, Monaco colors, and 360px settings.
The shared menu check passed after the final icon mapping changes.
Native Undo through the shared menu restored Writer text in an isolated WebView2 profile.
That profile supplied no spelling suggestions. Correction and undo with an actual spelling suggestion still need desktop acceptance.
Actual installation, reinstall, settings retention, and downgrade protection also need desktop acceptance.
The Git graph shows at most 100 commits. Dashed links mark parents outside that history.
Push and pull require a configured upstream and existing Git authentication.
Pull permits only fast-forward updates.
These builds create local artifacts. They do not install, publish, or commit them.
-21
View File
@@ -1,21 +0,0 @@
# Release history
[RuneStone](../README.md) · [Installation](installation.md) · [Build and package](builds.md)
These entries record completed local test builds. They are not public download links.
Source changes after a build do not change its recorded contents.
Each entry includes artifact paths, checks, and any remaining desktop acceptance work.
| RuneStone | Related plugin builds | Notes |
| --- | --- | --- |
| 0.1.17 | Git 0.1.4 | [Menu, themes, and Git graph](release-0.1.17.md) |
| 0.1.16 | Project Management 0.2.21, Git 0.1.2 | [Follow-up test build](release-0.1.16.md) |
| 0.1.15 | Project Management 0.2.20, Terminal 0.1.2 | [Test build](release-0.1.15.md) |
| 0.1.14 | Project Management 0.2.19, Git 0.1.1 | [Test build](release-0.1.14.md) |
| 0.1.13 | Project Management 0.2.18 | [Kanban test build](release-0.1.13.md) |
Earlier local installers include Windows save hotfix 0.1.11a, with numeric installer version 0.1.12.
Their release notes are not complete in this checkout.
See the [archive](archive/README.md) for dated implementation records and proposals.
Maintainers use the [build guide](builds.md) to package installers and run installation checks.
+95 -4
View File
@@ -8,6 +8,7 @@ This reference describes the interface and its shared dimensions. Agent instruct
## Design principles ## Design principles
Keep attention on the user's work. Use quiet backgrounds for the active view and reserve strong accents for alerts or actions that need attention. Keep attention on the user's work. Use quiet backgrounds for the active view and reserve strong accents for alerts or actions that need attention.
Show only what the current task needs. Let users collapse optional sections and hide panes when they need more space.
Tabs can join visually with their content area. A selected view does not need a bright border or a repeated heading. Tabs can join visually with their content area. A selected view does not need a bright border or a repeated heading.
Show each board name once in the main controls. Keep switching and renaming as separate actions with clear targets. Show each board name once in the main controls. Keep switching and renaming as separate actions with clear targets.
@@ -33,6 +34,9 @@ Document and plugin tabs share the tab bar. The new-tab button follows the tabs.
Tabs retain their order and pin state when a plugin replaces its current view. Tabs retain their order and pin state when a plugin replaces its current view.
The last closed tab leaves an empty New tab. Sidebar widths and visibility persist across window sessions. The last closed tab leaves an empty New tab. Sidebar widths and visibility persist across window sessions.
Opening a different editor does not restore a hidden outline. Opening a different editor does not restore a hidden outline.
Detached tabs contain the tab work area and window controls. They do not mount side panes, a plugin ribbon, or pane switches.
Their layout does not change the main window layout. See [UI-004](design-decisions.md#ui-004--detached-tab-work-area).
The built-in browser opens from its own toolbar action. Project Management opens from Plug-in views.
## Icons and controls ## Icons and controls
@@ -57,24 +61,43 @@ Feature code does not override menu rows. Menu width can expand when content nee
| --- | --- | --- | | --- | --- | --- |
| `--rs-menu-width` | 248px | Standard menu width | | `--rs-menu-width` | 248px | Standard menu width |
| `--rs-menu-padding` | 5px | Inset around rows | | `--rs-menu-padding` | 5px | Inset around rows |
| `--rs-menu-row-height` | 26px | Minimum row height | | `--rs-menu-row-height` | 30px | Minimum row height |
| `--rs-menu-row-padding` | 3px 8px | Vertical and horizontal row padding | | `--rs-menu-row-padding` | 4px 10px | Vertical and horizontal row padding |
| `--rs-menu-font-size` | 12px | Shared text size | | `--rs-menu-font-size` | 13px | Shared text size |
| `--rs-menu-border` | `transparent` | Borderless panel |
| `--rs-menu-icon-size` | 14px | Action icon size | | `--rs-menu-icon-size` | 14px | Action icon size |
| `--rs-menu-icon-gap` | 8px | Space between icon and label | | `--rs-menu-icon-gap` | 8px | Space between icon and label |
All rows reserve an icon column. Shortcut text and submenu arrows occupy trailing columns. Menus with only text choices omit the icon column. Mixed action menus reserve the icon column for every row.
Shortcut text and submenu arrows occupy trailing columns.
Enabled rows share hover and keyboard focus colors. Disabled rows stay readable and cannot run. Enabled rows share hover and keyboard focus colors. Disabled rows stay readable and cannot run.
Menus support arrow keys, Home, End, Enter, Space, and Escape. Menus support arrow keys, Home, End, Enter, Space, and Escape.
Right opens a submenu. Left returns to its parent. Keyboard dismissal restores focus. Right opens a submenu. Left returns to its parent. Keyboard dismissal restores focus.
Menus stay inside the viewport and scroll when their contents exceed its height. Menus stay inside the viewport and scroll when their contents exceed its height.
Menus use 30-pixel rows, 13-pixel text, and a borderless panel with a shadow.
Keep hover and keyboard focus fills quiet, with an inset from the panel edge.
Theme, appearance, board, and list menus share these values. See [decision UI-002](design-decisions.md#ui-002--share-the-requested-dropdown-design).
See [UI-006](design-decisions.md#ui-006--borderless-shared-menus) for the borderless panel rule.
Radio choices show the current option with a quiet fill and no checkmark.
The current enabled radio choice receives focus when its menu opens. See [UI-003](design-decisions.md#ui-003--quiet-menu-choices).
A menu row can have a default action and a submenu.
Clicking the label, Enter, or Space runs the default action. Hover, the submenu arrow, or Right opens the submenu.
New note creates a blank note. Its submenu contains templates and Manage templates.
Searchable pickers and form dialogs can use richer layouts. Native select controls retain platform behavior. Searchable pickers and form dialogs can use richer layouts. Native select controls retain platform behavior.
Native editing menus retain recognized editing, spelling, and emoji commands.
They omit system sharing, writing direction, dictation, and unsupported unnamed tools.
The host filters the native collection before shared display or native fallback. See [UI-008](design-decisions.md#ui-008--keep-native-editing-menus-focused).
## Settings ## Settings
Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls. Settings navigation pairs icons with labels. Each settings page uses readable text and ordinary controls.
Related plugin metadata and actions occupy compact rows. Controls wrap at narrow widths, and the content area scrolls. Related plugin metadata and actions occupy compact rows. Controls wrap at narrow widths, and the content area scrolls.
Long navigation lists must leave room for the selected page. Long navigation lists must leave room for the selected page.
New tabs and Project Management keep separate background images and settings in every theme. Images can be up to 50 MiB.
Image bytes stay in IndexedDB. Settings retain a small image reference.
Both support image size, nine alignment positions, and an overlay that lightens or darkens the image.
Set the overlay with the slider or type a percentage from -100 to 100.
An image stays within its view area while content scrolls. A board can retain its own image.
| Shared token | Default | | Shared token | Default |
| --- | --- | | --- | --- |
@@ -92,6 +115,8 @@ The IDE and Terminal share `--rs-font-mono` and `--rs-code-font-weight`.
The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas. The monospace stack starts with Cascadia Mono, then Cascadia Code, JetBrains Mono, Fira Code, and Consolas.
The default code weight is 300. Actual appearance depends on installed fonts and their available weights. The default code weight is 300. Actual appearance depends on installed fonts and their available weights.
Terminal font-size preferences remain independent. Terminal font-size preferences remain independent.
Document headings use spacing between sections. They do not use separator lines.
Heading fold controls use the shared chevron and support keyboard focus. See [UI-005](design-decisions.md#ui-005--heading-spacing).
Tables use shared cell padding and line height. Entering a cell does not change its row height. Tables use shared cell padding and line height. Entering a cell does not change its row height.
A plain paragraph after a table remains a paragraph when the separator line is removed. A plain paragraph after a table remains a paragraph when the separator line is removed.
@@ -108,3 +133,69 @@ The menu check covers file, folder, pane, tab, editor, table, and submenu exampl
Use `SMOKE_URL` to select the server URL. Use `PLAYWRIGHT_MODULE` and `CHROME_PATH` when the environment needs explicit paths. Use `SMOKE_URL` to select the server URL. Use `PLAYWRIGHT_MODULE` and `CHROME_PATH` when the environment needs explicit paths.
Browser tests with desktop mocks do not replace native installer and window acceptance checks. Browser tests with desktop mocks do not replace native installer and window acceptance checks.
## Keep controls quiet
Keep empty forms hidden until the user chooses an add action. Keep section names, counts, and expand controls visible.
Remember that a collapsed section still contains work. Do not remove its data or hide errors that need attention.
Compact toolbars use icon buttons by default. Each button needs an accessible name and a tooltip on hover and keyboard focus.
Keep visible text for ambiguous choices and action menus. Do not add a caption to one familiar toolbar action while its peers use icons.
Board switching, renaming, and adding work remain separate controls. Put plug-in views in the toolbar, away from the new-tab button.
## Shared choices and highlights
Use the shared action menu for short option lists, including board and theme choices. Mark the current option with a radio state.
Use a searchable picker for long lists. Native selectors remain an older-host fallback for plugins.
Menu rows use the same inset, hover fill, focus fill, and corner radius. A menu choice and a file selection serve different purposes.
File selections retain the shared selection fill and outer outline. Hover uses the quiet active background across both surfaces.
Do not copy feature-specific colors into a shared control.
The Claude palette follows the [Anthropic brand guide](https://github.com/anthropics/skills/blob/main/skills/brand-guidelines/SKILL.md).
Keep its warm light and dark surfaces, orange accent, Lora body font, and Poppins headings with their documented fallbacks.
Shared dimensions and interaction rules apply to every palette.
## Prevent repeated UI drift
Before a new control, find its shared component and an existing example. Extend that component when the same change helps other callers.
A plugin can call `api.ui.showActionMenu` for the host menu. The host handles dismissal, focus return, and plugin cleanup.
See [UI-007](design-decisions.md#ui-007--repeated-menu-drift) for repeated menu drift and its prevention checks.
Rich pickers and forms can use separate layouts under the menu rules above. These permitted layouts do not need exception entries.
Check local style overrides when a shared control differs from its peers. Correct the shared component or token when it causes the problem.
### Current rules and decision history
This guide is the current design reference. The [design decision log](design-decisions.md) records reasons, recurring problems, and exceptions.
Keep current rules here so contributors do not need to reconstruct them from old entries.
The trigger for a rule-change entry is a changed design rule, even when only one control changes.
| Change | Required record |
| --- | --- |
| Isolated correction to an existing rule | Normal card or commit record. No design entry. |
| Intentional rule change | Update this guide and add a rule-change entry with its reason and scope. |
| Recurring problem | Link the occurrences and record the cause, prevention action, and check. |
| Deliberate exception | Record the user benefit, exact scope, and review date or trigger. Link it from the affected rule here. |
Restoring a menu to its specified color is a correction. Choosing a new font for the interface changes a rule.
Repeated wrong menu colors need a recurring-problem record. Check the shared component and local overrides before adding more guidance.
Repeated symptoms do not prove a cause. Record uncertainty until evidence identifies the cause.
Use the log templates for new entries. Update the existing entry when the same problem returns.
Keep historical decisions and link their replacements. A proposed entry does not replace the current rule.
### Evidence for review
For each UI change, include this evidence in the card or change review:
- Affected controls, the applicable guide section, and the shared component or token. Explain any separate implementation.
- Relevant screenshots of changed states in light and dark themes, including narrow layouts and applicable focus or disabled states.
- Results for keyboard use, empty and populated states, and the relevant checks listed above. State any unavailable checks.
- A check against the design principles: repeated headings, competing accents, unnecessary controls, and space left for the user's work.
- A link to a decision entry when a rule changes, a problem recurs, or an exception applies.
Keep screenshots as review evidence. An isolated correction still needs evidence, but it does not need a design entry.
Use accepted examples as visual references for later changes. Label each reference with its control, theme, state, and current rule.
Replace outdated references when the rule changes. Do not treat an unreviewed screenshot as an accepted design.
Run the shared menu check after menu changes and relevant feature checks after behavior changes.
Keep native desktop checks separate from browser tests with mocked desktop services.
Automated checks support visual and interaction review. They do not decide whether the interface keeps attention on the user's work.
Move implementation-ready work to Review after the relevant checks pass. Keep unresolved work In progress and reserve Done for the user's acceptance.
+1 -1
View File
@@ -1,6 +1,6 @@
# User guide # User guide
[RuneStone](../README.md) · [Installation](installation.md) · [Release history](releases.md) [RuneStone](../README.md) · [Installation](installation.md)
This guide describes current source behavior. A supplied installer can contain an earlier feature set. This guide describes current source behavior. A supplied installer can contain an earlier feature set.
Check its release notes if a control is missing. Check its release notes if a control is missing.
+6 -2
View File
@@ -1,12 +1,12 @@
{ {
"name": "runestone", "name": "runestone",
"version": "0.1.18", "version": "0.1.23a",
"description": "Desktop editor for a local workspace", "description": "Desktop editor for a local workspace",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite dev", "dev": "vite dev",
"build": "vite build", "build": "vite build",
"build:installer": "tauri build --bundles nsis -- --locked", "build:installer": "node scripts/buildInstaller.mjs",
"preview": "vite preview", "preview": "vite preview",
"prepare": "svelte-kit sync || echo ''", "prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tsconfig.plugins.json", "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tsconfig.plugins.json",
@@ -14,6 +14,10 @@
"tauri": "tauri", "tauri": "tauri",
"test": "node --experimental-strip-types --test scripts/*.spec.ts", "test": "node --experimental-strip-types --test scripts/*.spec.ts",
"build:plugins": "node scripts/buildPlugins.mjs", "build:plugins": "node scripts/buildPlugins.mjs",
"browser:check": "npm --prefix browser-runtime run check",
"browser:test": "npm --prefix browser-runtime test",
"browser:test:engine": "npm --prefix browser-runtime run test:browser",
"browser:stage": "npm --prefix browser-runtime run stage:host",
"package:plugin": "node scripts/packagePlugin.mjs" "package:plugin": "node scripts/packagePlugin.mjs"
}, },
"license": "MIT", "license": "MIT",
+19 -11
View File
@@ -81,10 +81,16 @@ try {
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3; return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
}, expected); }, expected);
} }
const themeName = theme => ({ default: 'RuneStone', claude: 'Claude', sakura: 'Sakura' })[theme];
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
async function choose(page, name, value) {
await picker(page, name).click();
await page.getByRole('menuitemradio', { name: name === 'Color theme' ? themeName(value) : value === 'light' ? 'Light' : 'Dark', exact: true }).click();
}
async function openAppearance(page) { async function openAppearance(page) {
await page.goto(`${origin}/?settingsWindow=true`); await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole("button", { name: "Appearance", exact: true }).click(); await page.getByRole("button", { name: "Appearance", exact: true }).click();
await page.getByRole("combobox", { name: "Color theme", exact: true }).waitFor(); await picker(page, "Color theme").waitFor();
} }
await openCode(0); await openCode(0);
await openAppearance(settings); await openAppearance(settings);
@@ -94,8 +100,8 @@ try {
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode }); await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode); assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
} }
assert.equal(await secondSettings.getByRole("combobox", { name: "Color theme", exact: true }).inputValue(), theme); assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme));
assert.equal(await secondSettings.getByRole("combobox", { name: "Appearance", exact: true }).inputValue(), mode); assert.equal((await picker(secondSettings, "Appearance").textContent()).trim(), mode === "light" ? "Light" : "Dark");
await main.waitForFunction(() => { await main.waitForFunction(() => {
const root = document.documentElement; const root = document.documentElement;
const probe = document.createElement("i"); const probe = document.createElement("i");
@@ -114,8 +120,8 @@ try {
for (const theme of ["default", "claude", "sakura"]) { for (const theme of ["default", "claude", "sakura"]) {
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) { for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
const before = await editorIds(); const before = await editorIds();
await settings.getByRole("combobox", { name: "Color theme", exact: true }).selectOption(theme); await choose(settings, 'Color theme', theme);
if (theme !== "sakura") await settings.getByRole("combobox", { name: "Appearance", exact: true }).selectOption(mode); if (theme !== "sakura") await choose(settings, 'Appearance', mode);
backgrounds.add(await expectAppearance(theme, mode)); backgrounds.add(await expectAppearance(theme, mode));
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes"); assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
await openCode(nextCode++); await openCode(nextCode++);
@@ -147,9 +153,11 @@ try {
} }
} }
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds"); assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
assert.deepEqual(await settings.getByRole('combobox', { name: 'Color theme', exact: true }).locator('option').evaluateAll(options => options.map(option => option.value)), ['default', 'claude', 'sakura']); await picker(settings, 'Color theme').click();
assert.equal(await settings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true); assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone', 'Claude', 'Sakura']);
assert.equal(await secondSettings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true); await settings.keyboard.press('Escape');
assert.equal(await picker(settings, 'Appearance').isDisabled(), true);
assert.equal(await picker(secondSettings, 'Appearance').isDisabled(), true);
const sakura = await settings.evaluate(() => { const sakura = await settings.evaluate(() => {
const css = getComputedStyle(document.documentElement); const css = getComputedStyle(document.documentElement);
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()])); return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
@@ -169,15 +177,15 @@ try {
} }
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) { for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
await settings.setViewportSize({ width: 1100, height: 780 }); await settings.setViewportSize({ width: 1100, height: 780 });
await settings.getByRole('combobox', { name: 'Color theme', exact: true }).selectOption(theme); await choose(settings, 'Color theme', theme);
if (theme !== 'sakura') await settings.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption(mode); if (theme !== 'sakura') await choose(settings, 'Appearance', mode);
await expectAppearance(theme, mode); await expectAppearance(theme, mode);
await settings.setViewportSize({ width: 360, height: 480 }); await settings.setViewportSize({ width: 360, height: 480 });
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport'); assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
const content = settings.locator('dialog .content'); const content = settings.locator('dialog .content');
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area'); assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
for (const name of ['Color theme', 'Appearance']) { for (const name of ['Color theme', 'Appearance']) {
const control = settings.getByRole('combobox', { name, exact: true }); const control = picker(settings, name);
await control.scrollIntoViewIfNeeded(); await control.scrollIntoViewIfNeeded();
const bounds = await control.boundingBox(); const bounds = await control.boundingBox();
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`); assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
+9
View File
@@ -19,3 +19,12 @@ test('Malformed storage returns a valid default appearance', () => {
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' }); assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
} }
}); });
test('Saved image layout restores valid choices and rejects CSS injection', () => {
const imageId = '01234567-89ab-cdef-0123-456789abcdef';
const restored = parseAppearance(JSON.stringify({ newTabBackground: { imageId, position: 'top left', size: 'auto', overlay: -0.4 } }));
assert.deepEqual(restored.newTabBackground, { imageId, position: 'top left', size: 'auto', overlay: -0.4 });
const invalid = normalizeAppearance({ newTabBackground: { imageId, position: 'url(https://example.com)', size: '100000px', overlay: Infinity } });
assert.deepEqual(invalid.newTabBackground, { imageId, position: 'center', size: 'cover', overlay: 0 });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId } }).newTabBackground, { imageId, overlay: 0, position: 'center', size: 'cover' });
});
+154
View File
@@ -0,0 +1,154 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve } from 'node:path';
const { chromium } = createRequire(import.meta.url)(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: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (!files.has(args.from)) throw new Error('Missing file');
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const errors = [];
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
await mkdir('output/appearance-pass3', { recursive: true });
async function background() { return main.locator('.empty').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); }
async function decoded(page, url) {
return page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
}
try {
await main.goto(origin); await main.locator('.empty').waitFor();
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const image = await main.evaluate(() => {
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
const ctx = canvas.getContext('2d'), pixels = ctx.createImageData(700, 700);
let seed = 23;
for (let i = 0; i < pixels.data.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels.data[i] = i % 4 === 3 ? 255 : seed >>> 24; }
ctx.putImageData(pixels, 0, 0); return canvas.toDataURL();
});
const bytes = Buffer.from(image.split(',')[1], 'base64');
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
let url = await background();
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
await main.reload(); await main.locator('.empty').waitFor();
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const large = Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]);
await writeFile('output/appearance-pass3/50MiB.png', large);
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/50MiB.png'));
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.empty')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
await writeFile('output/appearance-pass3/too-large.png', Buffer.alloc(50 * 1024 * 1024 + 1));
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/too-large.png'));
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId), acceptedId);
assert.equal(await settings.locator('input[type=color]').count(), 0);
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('0.55'));
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('255, 255, 255, 0.4'));
for (const mode of ['dark', 'light']) {
await settings.locator('.picker').and(settings.getByRole('button', { name: 'Appearance', exact: true })).click();
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'Dark' : 'Light', exact: true }).click();
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
await main.screenshot({ path: `output/appearance-pass3/background-${mode}.png` });
for (const name of ['Color theme', 'Appearance']) {
await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).click();
const menu = settings.getByRole('menu', { name, exact: true });
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '30px');
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 0);
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
await settings.screenshot({ path: `output/appearance-pass3/${name.replaceAll(' ', '-')}-${mode}.png` });
await settings.keyboard.press('Escape');
assert.equal(await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).evaluate(node => node === document.activeElement), true);
}
}
await settings.setViewportSize({ width: 360, height: 480 });
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
await settings.screenshot({ path: 'output/appearance-pass3/menu-narrow.png' });
await settings.keyboard.press('Escape');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
await settings.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
});
for (const theme of ['light', 'dark']) {
await settings.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, theme);
await settings.setViewportSize({ width: 360, height: 600 });
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
await settings.screenshot({ path: `output/appearance-pass3/long-plugin-list-${theme}-narrow.png` });
await main.setViewportSize({ width: 600, height: 700 });
await main.keyboard.press('F1');
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
assert.equal(await main.locator('.help-card details[open]').count(), 0);
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
assert.equal(await main.locator('.help-card details[open]').count(), 1);
await main.keyboard.press('Enter');
await main.screenshot({ path: `output/appearance-pass3/help-${theme}-narrow.png` });
await main.getByRole('button', { name: 'Close help', exact: true }).click();
}
assert.deepEqual(errors, []);
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
} finally { await browser.close(); }
+76
View File
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(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: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command) => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const main = await context.newPage(), settings = await context.newPage();
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const screenshots = [];
await mkdir('output/todo-background', { recursive: true });
try {
await main.goto(origin);
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
const button = settings.getByRole('button', { name: control, exact: true });
await button.click();
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
assert.equal(await button.evaluate(node => node === document.activeElement), true);
}
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('0% 0%'));
const layout = () => main.locator('.empty').evaluate(node => {
const style = getComputedStyle(node), box = node.getBoundingClientRect();
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
});
const before = await layout();
assert.equal(before.size, '100% 100%, auto');
await main.locator('.empty').evaluate(node => {
const content = document.createElement('div'); content.style.cssText = 'height:2000px;flex-shrink:0;width:100%'; node.append(content);
});
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
await main.reload();
await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
assert.equal((await layout()).position, before.position);
assert.equal((await layout()).size, before.size);
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
await settings.keyboard.press('End');
await settings.keyboard.press('Enter');
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('100% 100%'));
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 700 });
const file = `output/todo-background/settings-${mode}-${width}.png`;
await settings.screenshot({ path: file }); screenshots.push(file);
const pane = settings.locator('.content');
assert.equal(await pane.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
}
}
await writeFile('output/todo-background-report.json', JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
} finally { await browser.close(); }
+46 -5
View File
@@ -4,7 +4,7 @@ import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import os from 'node:os'; import os from 'node:os';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const runtime = path.resolve('../RuneStone_Browser'); const runtime = path.resolve('browser-runtime');
const require = createRequire(path.join(runtime, 'package.json')); const require = createRequire(path.join(runtime, 'package.json'));
const { chromium } = require('playwright'); const { chromium } = require('playwright');
const electron = require('electron'); const electron = require('electron');
@@ -45,7 +45,7 @@ const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_P
const errors = []; const errors = [];
try { try {
await ready; await ready;
page = await browser.newPage({ viewport: { width: 1280, height: 800 } }); page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
page.on('pageerror', error => errors.push(error.message)); page.on('pageerror', error => errors.push(error.message));
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; }); await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
await page.addInitScript(() => { await page.addInitScript(() => {
@@ -77,12 +77,53 @@ try {
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0); assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab'); const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code }); const evaluate = code => rpc('testEvaluate', { tabId, code });
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
const initialBox = await surface.boundingBox();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.type('Hello World!');
await page.waitForTimeout(200);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!');
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
await page.waitForTimeout(200);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!Hello World!');
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
});
await page.waitForTimeout(100);
assert.ok((await evaluate('document.querySelector("#typing").value')).endsWith('日本語'));
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart'), 27);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
await page.keyboard.press('Escape');
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#typing").value'), 'https://example.com/');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`); await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor(); await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); }); await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000); await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3); const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`); assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
const beforeWheels = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
await surface.evaluate(node => {
const bounds = node.getBoundingClientRect();
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
}));
});
await page.waitForTimeout(200);
const wheelBurstCalls = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length - beforeWheels;
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
await evaluate('window.testAnimate=false;true;'); await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`); await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor(); await page.locator('.surface img').waitFor();
@@ -94,7 +135,7 @@ try {
const scrolled = await evaluate('({x:scrollX,y:scrollY})'); const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`); assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
await page.waitForTimeout(150); await page.waitForTimeout(350);
const stopped = await evaluate('scrollY'); const stopped = await evaluate('scrollY');
await page.waitForTimeout(200); await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped); assert.equal(await evaluate('scrollY'), stopped);
@@ -131,8 +172,8 @@ try {
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2); await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.'); assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(errors, []); assert.deepEqual(errors, []);
await writeFile('output/browser-interaction.json', JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, passed: ['Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer bursts coalesce', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2)); await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
console.log('PASS browser UI with real Electron pages, autoscroll cleanup, pointer coalescing and center new-tab action'); console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
} finally { } finally {
await browser.close(); await browser.close();
await rpc('shutdown').catch(() => {}); child.kill(); await rpc('shutdown').catch(() => {}); child.kill();
+58
View File
@@ -0,0 +1,58 @@
import { createRequire } from 'node:module';
import path from 'node:path';
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
const require = createRequire(path.resolve('browser-runtime/package.json'));
const { chromium } = require('playwright');
const browser = await chromium.connectOverCDP(process.env.BROWSER_NATIVE_CDP || 'http://127.0.0.1:9224');
const page = browser.contexts()[0].pages()[0];
const raw = (command, args = {}) => page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args });
const profile = await raw('plugins_snapshot');
assert.ok(/[\\/]com\.runestone\.(?:browser|spelling)-test[\\/]plugins$/.test(profile.root), 'Native acceptance requires an isolated test profile.');
const session = await raw('browser_connect');
const request = (command, args = {}) => raw('browser_request', { command, args, session });
const initialTabs = (await request('state')).tabs.map(tab => tab.id);
let tabId;
try {
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true }).last();
await page.locator('.browser[data-browser-state="ready"]').last().waitFor();
tabId = await page.locator('.browser[data-browser-state="ready"]').last().getAttribute('data-browser-tab');
const address = page.getByRole('textbox', { name: 'Address or search', exact: true }).last();
await address.fill('https://example.com/'); await address.press('Enter');
for (let attempt = 0; attempt < 60; attempt++) {
const snapshot = await request('agentSnapshot', { tabId });
if (snapshot.text.includes('documentation examples')) break;
if (attempt === 59) throw Error(`Public test page did not load: ${snapshot.text}`);
await page.waitForTimeout(250);
}
await page.waitForFunction(() => [...document.querySelectorAll('.surface img')].some(image => image.complete && image.naturalWidth > 0));
const dimensions = await surface.locator('img').evaluate(image => ({ width: image.naturalWidth, height: image.naturalHeight,
css: image.getBoundingClientRect().width, scale: devicePixelRatio, source: image.src.slice(0, 30) }));
assert.ok(dimensions.width >= dimensions.css * dimensions.scale - 2, JSON.stringify(dimensions));
const bounds = await surface.boundingBox();
await page.mouse.click(bounds.x + 20, bounds.y + 20, { button: 'right' });
const menu = page.getByRole('menu', { name: 'Browser page actions', exact: true });
await menu.waitFor();
assert.equal(await menu.getByRole('menuitem', { name: 'Reload', exact: true }).count(), 1);
await page.keyboard.press('Escape'); await menu.waitFor({ state: 'detached' });
await request('edit', { tabId, action: 'selectAll' });
await page.waitForTimeout(100);
await request('edit', { tabId, action: 'copy' });
await page.waitForTimeout(100);
await address.focus(); await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
assert.match(await address.inputValue(), /documentation examples/);
await address.fill('https://example.com/');
await assert.rejects(raw('browser_request', { command: 'edit', args: { tabId, action: 'copy' }, session: 'invalid-session' }), /session/i);
await assert.rejects(request('contextAction', { tabId, token: 'stale-menu', action: 'saveImage' }), /no longer available/);
await page.screenshot({ path: 'output/browser-native-acceptance.png' });
await writeFile('output/browser-native-acceptance.json', JSON.stringify({ dimensions, passed: [
'Native Tauri-to-Electron page rendering and high-DPI frame delivery', 'Native page context event opens the shared host menu',
'Native editing commands copy real webpage text', 'Session and stale-menu checks reject invalid requests',
] }, null, 2));
console.log('PASS native browser transport, rendering, context menu, editing and session protection');
} finally {
if (tabId && !initialTabs.includes(tabId)) { await page.keyboard.press('Escape'); await page.keyboard.press('Control+w'); }
await browser.close();
}
+108
View File
@@ -0,0 +1,108 @@
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
import assert from 'node:assert/strict';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
window.browserMenuTest = { snapshot, calls: [] };
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
if (command === 'plugin:event|listen') return args.handler;
if (command === 'plugin:event|unlisten') return;
if (command === 'browser_connect') return 'menu-session';
if (command === 'browser_stop' || command === 'plugins_release') return;
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
if (command.startsWith('plugin:window|')) return false;
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
const details = args.args || {};
window.browserMenuTest.calls.push({ command: args.command, ...details });
if (args.command === 'webData') return { profileId: details.profileId, cookies: [], history: [] };
if (args.command === 'settings') Object.assign(snapshot.settings, details);
return structuredClone(snapshot);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const trigger = name => page.getByRole('button', { name, exact: true });
try {
await mkdir('output/todo-menus', { recursive: true });
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
await trigger('Browser').click();
await trigger('Search engine').waitFor();
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await trigger('Search engine').focus();
await page.keyboard.press('Enter');
const engines = menu('Search engine');
await engines.waitFor();
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
await page.screenshot({ path: `output/todo-menus/search-${mode}.png` });
await page.keyboard.press('End');
await page.keyboard.press('Space');
assert.equal(await trigger('Search engine').innerText(), 'Bing');
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
await trigger('Search engine').click();
await page.keyboard.press('Home');
await page.keyboard.press('Enter');
await trigger('Profile').focus();
await page.keyboard.press('Space');
await menu('Profile').waitFor();
await page.screenshot({ path: `output/todo-menus/profile-${mode}.png` });
await page.keyboard.press('ArrowDown');
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('button[aria-label="Profile"]')?.textContent === 'Work');
await page.waitForFunction(() => window.browserMenuTest.calls.some(call => call.command === 'webData' && call.profileId === 'work'));
await trigger('Profile').click();
await page.keyboard.press('Home');
await page.keyboard.press('Enter');
await page.setViewportSize({ width: 520, height: 700 });
await trigger('Search engine').click();
const bounds = await engines.boundingBox();
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
await page.screenshot({ path: `output/todo-menus/narrow-${mode}.png` });
await page.keyboard.press('Escape');
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
await page.setViewportSize({ width: 1100, height: 850 });
}
await trigger('Search engine').click();
await menu('Search engine').getByRole('menuitemradio', { name: 'Google', exact: true }).click();
assert.equal(await page.evaluate(() => window.browserMenuTest.calls.filter(call => call.command === 'settings').length), 0, 'A choice does not submit the form');
await trigger('Save browser settings').click();
await page.waitForFunction(() => window.browserMenuTest.snapshot.settings.search === 'google');
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.browserMenuTest.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
await page.setViewportSize({ width: 520, height: 700 });
await trigger('Profile').click();
const profiles = menu('Profile');
assert.equal(await profiles.evaluate(node => node.scrollHeight > node.clientHeight), true, 'Long profile lists scroll');
await page.keyboard.press('End');
assert.equal(await profiles.getByRole('menuitemradio', { name: 'Profile 59', exact: true }).evaluate(node => node === document.activeElement), true);
await page.screenshot({ path: 'output/todo-menus/profile-long-narrow.png' });
await page.keyboard.press('Escape');
assert.equal(await trigger('Profile').evaluate(node => node === document.activeElement), true);
await trigger('Profile').click();
await trigger('Profile').evaluate(node => {
let parent = node.parentElement;
while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
if (!parent) throw Error('Settings need a scroll area');
parent.scrollTop -= 40;
});
await profiles.waitFor({ state: 'detached' });
await trigger('Search engine').click();
await trigger('General').click();
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
assert.deepEqual(errors, []);
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
} finally { await browser.close(); }
+10 -6
View File
@@ -69,7 +69,11 @@ await page.addInitScript(() => {
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
}); });
const section = page.getByRole('region', { name: 'Individual web data', exact: true }); const section = page.getByRole('region', { name: 'Individual web data', exact: true });
const profile = page.getByRole('combobox', { name: 'Profile', exact: true }); const profile = page.getByRole('button', { name: 'Profile', exact: true });
async function selectProfile(id) {
await profile.click();
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
}
const kind = section.getByRole('combobox', { name: 'Web data type', exact: true }); const kind = section.getByRole('combobox', { name: 'Web data type', exact: true });
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true }); const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true }); const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
@@ -114,7 +118,7 @@ try {
await filter.fill('another.example/document'); await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor(); await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1); assert.equal(await section.locator('.entry').count(), 1);
await profile.selectOption('work'); await selectProfile('work');
await settle(); await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter'); assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor(); await section.getByText('Work guide', { exact: true }).waitFor();
@@ -126,7 +130,7 @@ try {
await refresh.click(); await refresh.click();
await pending('webData:work'); await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true); assert.equal(await workCookie().isDisabled(), true);
await profile.selectOption('user'); await selectProfile('user');
await settle(); await settle();
await release('webData:work'); await release('webData:work');
assert.equal(await workCookie().count(), 0); assert.equal(await workCookie().count(), 0);
@@ -136,7 +140,7 @@ try {
await hold('webData:user'); await hold('webData:user');
await refresh.click(); await refresh.click();
await pending('webData:user'); await pending('webData:user');
await profile.selectOption('work'); await selectProfile('work');
await workCookie().waitFor(); await workCookie().waitFor();
await settle(); await settle();
await release('webData:user', 'Stale personal error'); await release('webData:user', 'Stale personal error');
@@ -147,11 +151,11 @@ try {
await hold('removeCookie:work'); await hold('removeCookie:work');
await workCookie().click(); await workCookie().click();
await pending('removeCookie:work'); await pending('removeCookie:work');
await profile.selectOption('user'); await selectProfile('user');
await settle(); await settle();
const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length); const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length);
await release('removeCookie:work'); await release('removeCookie:work');
assert.equal(await profile.inputValue(), 'user'); assert.equal(await profile.innerText(), 'Personal');
assert.equal(await section.locator('.entry').count(), 2); assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore); assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0); assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
+89
View File
@@ -0,0 +1,89 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { releaseVersion } from './releaseVersion.mjs';
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const exists = file => fs.access(file).then(() => true, () => false);
const files = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'].map(file => path.join(root, file));
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
const current = releaseVersion(JSON.parse(before[0]).version);
const args = process.argv.slice(2);
if (args.length && (args.length !== 2 || args[0] !== '--version')) throw Error('Use --version followed by the release version.');
const next = releaseVersion(args[1] ?? current.version);
const config = JSON.parse(before[1]);
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
const platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8'));
if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
const releaseDir = path.join(root, 'output/releases', next.version);
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
const metadataPath = path.join(releaseDir, 'host.json');
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
const staging = path.join(root, 'output/installer-build', next.version);
await fs.mkdir(staging, { recursive: true });
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8');
for (const [key, value] of Object.entries({ RUNESTONE_VERSION: next.version, RUNESTONE_WINDOWS_VERSION: next.windows,
RUNESTONE_COMPARE: path.join(root, 'src-tauri/windows/versionCompare.nsh') })) {
if (!template.includes(`@${key}@`)) throw Error('The installer template is missing ' + key);
template = template.replaceAll(`@${key}@`, value);
}
const templatePath = path.join(staging, 'installer.nsi');
await fs.writeFile(templatePath, template);
const override = path.join(staging, 'config.json');
await fs.writeFile(override, JSON.stringify({ bundle: { windows: { allowDowngrades: false, nsis: { template: templatePath } } } }));
const packageJson = JSON.parse(before[0]);
packageJson.version = next.version;
config.version = next.toolchain;
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
if (/\[package\.metadata\.runestone\]/.test(cargo)) {
cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
} else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
async function run(command, parameters) {
console.log(command + ' ' + parameters.join(' '));
const code = await new Promise((resolve, reject) => {
const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true });
child.on('error', reject); child.on('exit', resolve);
});
if (code !== 0) throw Error('The build command failed with exit code ' + code);
}
let complete = false;
try {
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
const cli = path.join(root, 'node_modules/@tauri-apps/cli/tauri.js');
await run(process.execPath, [cli, 'build', '--no-bundle', '--', '--locked']);
await run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/setWindowsVersion.ps1'),
'-Path', path.join(root, 'src-tauri/target/release/runestone.exe'), '-Version', next.version, '-NumericVersion', next.windows]);
await run(process.execPath, [cli, 'bundle', '--bundles', 'nsis', '--config', override]);
await fs.access(internalArtifact);
if (internalArtifact !== artifact) await fs.rename(internalArtifact, artifact);
await fs.mkdir(releaseDir, { recursive: true });
await fs.copyFile(artifact, releaseArtifact, 1);
const bytes = await fs.readFile(releaseArtifact);
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
source: artifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
complete = true;
console.log('Installer available: ' + releaseArtifact);
} finally {
if (!complete) {
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
if (await exists(file)) await fs.rename(file, file + '.failed-' + Date.now());
}
}
}
+2 -2
View File
@@ -95,7 +95,7 @@ try {
await page.evaluate(value => { await page.evaluate(value => {
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }); window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } });
}, original); }, original);
await page.locator(".writer-preview pre").click(); await page.locator(".writer-code-line").first().click();
await page.locator(".writer-code-source").first().waitFor(); await page.locator(".writer-code-source").first().waitFor();
const position = original.indexOf("123") + 1; const position = original.indexOf("123") + 1;
await select(position); await select(position);
@@ -122,7 +122,7 @@ try {
const edited = original.slice(0, position - 1) + original.slice(position + 2); const edited = original.slice(0, position - 1) + original.slice(position + 2);
assert.equal(await contents(), edited); assert.equal(await contents(), edited);
await select(0); await select(0);
assert.ok((await page.locator(".writer-preview pre").textContent()).includes("const value = ;")); assert.ok((await page.locator(".writer-code-line").allTextContents()).join("\n").includes("const value = ;"));
await page.keyboard.press("Control+s"); await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited); await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited);
} }
+181
View File
@@ -0,0 +1,181 @@
// 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 === "spelling_menu_install") 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 mkdir('output/round4-editor-menu', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5187');
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/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const menu = () => page.getByRole('menu', { name: 'Markdown text actions', exact: true });
async function setSource(value, anchor = 0, head = anchor) {
await page.evaluate(({value,anchor,head}) => window.__CM__.dispatch({changes:{from:0,to:window.__CM__.state.doc.length,insert:value},selection:{anchor,head}}), {value,anchor,head});
}
async function openKeyboard() { await page.locator('.cm-content').focus(); await page.keyboard.press('Shift+F10'); await menu().waitFor(); }
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); }, theme);
await setSource('');
await page.locator('.cm-line').first().click({button:'right'});
await menu().waitFor();
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste','Paste as plain text','Select all']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
assert.equal(await menu().getByRole('menuitem',{name:'Cut',exact:true}).isDisabled(),true);
assert.equal(await menu().getByRole('menuitem',{name:'Copy',exact:true}).isDisabled(),true);
await page.screenshot({path:`output/round4-editor-menu/empty-${theme}.png`});
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
await page.keyboard.press('ArrowRight');
const format = page.getByRole('menu',{name:'Format',exact:true});
for (const label of ['Bold','Italic','Strikethrough','Highlight','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
await page.keyboard.press('End');
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
await page.screenshot({path:`output/round4-editor-menu/format-${theme}.png`});
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Escape');
assert.equal(await page.locator('.cm-content').evaluate(el=>el===document.activeElement),true);
await openKeyboard();
await menu().getByRole('menuitem',{name:'Paragraph',exact:true}).click();
await page.getByRole('menu',{name:'Paragraph',exact:true}).getByRole('menuitem',{name:'Heading 6',exact:true}).click();
assert.equal(await source(),'###### ');
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Insert',exact:true}).click();
await page.screenshot({path:`output/round4-editor-menu/insert-${theme}.png`});
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
assert.match(await source(),/^```\nCode\n```/);
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
assert.equal(await source(),'[]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1);
assert.equal(await page.getByRole('dialog').count(),0);
await setSource('label',0,5); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
assert.equal(await source(),'[label]()');
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8);
await setSource(''); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.screenshot({path:`output/round4-editor-menu/workspace-picker-${theme}.png`});
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
assert.equal(await source(),'[[/notes/second.md]]');
await setSource('Keep this text'); await openKeyboard();
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).waitFor();
await page.keyboard.press('Escape');
await page.getByRole('dialog').waitFor({state:'detached'});
assert.equal(await source(),'Keep this text');
await setSource('Populated paragraph\n\n');
await page.locator('.cm-line').last().click({button:'right'});
await menu().waitFor();
await page.keyboard.press('Escape');
await setSource('');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:420});
await page.locator('.cm-scroller').click({button:'right',position:{x:60,y:180}});
await menu().waitFor();
const box = await menu().boundingBox(); assert.ok(box.x>=8 && box.y>=8 && box.x+box.width<=552 && box.y+box.height<=412);
await page.screenshot({path:`output/round4-editor-menu/narrow-${theme}.png`});
await page.keyboard.press('Escape');
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Show outline',exact:true}).click();
}
await page.getByRole('group',{name:'Editor layout'}).hover();
await page.getByRole('button',{name:'IDE',exact:true}).click();
await page.locator('.monaco-editor').waitFor();
await page.locator('.monaco-editor textarea').focus();
await page.keyboard.press('Shift+F10');
await menu().waitFor();
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
await page.locator('.monaco-editor textarea').focus();
await page.keyboard.press('Control+a');
await page.keyboard.press('Backspace');
await page.keyboard.press('Shift+F10');
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
await page.keyboard.press('Enter');
await page.getByRole('dialog').waitFor({state:'detached'});
await page.screenshot({path:'output/round4-editor-menu/ide-links.png'});
assert.deepEqual(errors,[]);
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and IDE.');
} catch(error) {
await page.screenshot({path:'output/round4-editor-menu/failure.png'});
console.error('Browser errors:',errors); throw error;
} finally { await browser.close(); }
+182
View File
@@ -0,0 +1,182 @@
// 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 === "spelling_menu_install") 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 mkdir("output/editor-october12", { recursive: true });
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();
async function editor() {
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
}
await editor();
const source = "# First section\n\nParent text.[^long]\n\n## Child section\n\nChild content.\n\n### Nested section\n\nNested content.\n\n# Second section\n\nSecond content.[^long]\n\n## Last section\n\nFinal content.\n\n[^long]: A **bold** footnote.\n Continued on another line.\n";
async function setSource(value) {
await page.evaluate(value => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }), value);
}
await setSource(source);
const structural = "# Parent\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n```md\n# Not a heading\n```\n\n## Child\n\nText\n\n# Next\n\nNext text\n";
await setSource(structural);
assert.equal(await page.getByRole("button", { name: "Collapse Not a heading", exact: true }).count(), 0);
await page.getByRole("button", { name: "Collapse Parent", exact: true }).click();
assert.equal(await page.locator(".writer-table").count(), 0);
assert.equal(await page.getByRole("button", { name: "Collapse Child", exact: true }).count(), 0);
await page.getByRole("button", { name: "Expand Parent", exact: true }).click();
await page.locator(".writer-table").waitFor();
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), structural);
await setSource("Setext heading\n==============\n\nBody\n\n# Next\n\nNext body");
await page.getByRole("button", { name: "Collapse Setext heading", exact: true }).click();
await page.getByRole("button", { name: "Expand Setext heading", exact: true }).click();
await setSource(source);
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
assert.equal(await page.locator(".cm-content").textContent().then(text => text.includes("Child content.")), false);
await page.getByRole("button", { name: "Collapse First section", exact: true }).click();
assert.equal(await page.getByRole("button", { name: "Expand Child section", exact: true }).count(), 0);
await page.getByRole("button", { name: "Expand First section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
await page.keyboard.press("Enter");
await page.getByRole("button", { name: "Collapse Child section", exact: true }).waitFor();
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Collapse Child section');
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), source);
// Insert from the real shared menu and edit the selected definition.
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 20 } }); window.__CM__.focus(); });
await page.keyboard.press("Shift+F10");
await page.getByRole("menuitem", { name: "Insert", exact: true }).hover();
await page.getByRole("menuitem", { name: "Footnote", exact: true }).click();
await page.keyboard.type("New footnote");
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /\[\^1\]: New footnote/);
await page.keyboard.press("Control+z");
await setSource(source);
for (const theme of ["light", "dark"]) {
await page.evaluate(async theme => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode: theme }); }, theme);
await page.setViewportSize({ width: 760, height: 900 });
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
const bounds = button.getBoundingClientRect();
const pane = button.closest('.cm-scroller').getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
await page.screenshot({ path: `output/editor-october12/writer-${theme}-narrow.png` });
await page.keyboard.press("Space");
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
assert.ok(borders.every(border => border === "0px"));
assert.ok(await page.locator(".writer-heading").first().evaluate(heading => parseFloat(getComputedStyle(heading).paddingTop) > 8));
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Read", exact: true }).click();
await page.locator(".md-footnotes").waitFor();
assert.equal(await page.locator(".md-footnote-ref").count(), 2);
assert.equal(await page.locator(".md-footnotes li").count(), 1);
assert.equal(await page.locator(".md-footnote-back").count(), 2);
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
const bounds = button.getBoundingClientRect();
const pane = button.closest('.reading').parentElement.getBoundingClientRect();
return bounds.left >= pane.left && bounds.right <= pane.right;
}));
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), false);
await page.screenshot({ path: `output/editor-october12/reader-${theme}-narrow.png` });
await page.keyboard.press("Space");
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), true);
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
await page.locator(".md-footnote-ref a").first().click();
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
await page.locator(".md-footnote-back").first().click();
assert.equal(await page.evaluate(() => document.activeElement?.id), "rs-fnref-1-1");
await page.getByRole("group", { name: "Document view" }).hover();
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
await editor();
}
await page.keyboard.press("Control+s");
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, source);
assert.deepEqual(errors, []);
console.log("PASS: footnote menu, Writer edits, Reader numbering and backlinks, nested folding, keyboard toggles, source preservation, light/dark narrow screenshots.");
} catch (error) {
console.error("Browser errors:", errors);
await page.screenshot({ path: "output/editor-october12/failure.png" });
throw error;
} finally { await browser.close(); }
␍
+33
View File
@@ -0,0 +1,33 @@
import assert from "node:assert/strict";
import test from "node:test";
import MarkdownIt from "markdown-it";
import { footnotes, renderFootnotes } from "../src/lib/editor/footnotes.ts";
function render(source: string) {
const markdown = new MarkdownIt({ html: false }).use(footnotes);
const env = {};
return markdown.render(source, env) + renderFootnotes(markdown, env);
}
test("footnotes use first-reference order, repeated backlinks, and rich multiline definitions", () => {
const html = render("First[^b], then[^a], again[^b].\n\n[^a]: Second definition\n[^b]: **Bold** text\n continued\n\n Second paragraph.\n");
assert.match(html, /id="rs-fnref-1-1"/);
assert.match(html, /id="rs-fnref-1-2"/);
assert.match(html, /<strong>Bold<\/strong> text\ncontinued/);
assert.match(html, /<p>Second paragraph\.<\/p>/);
assert.ok(html.indexOf('<li id="rs-fn-1"') < html.indexOf('<li id="rs-fn-2"'));
assert.match(html, /href="#rs-fnref-1-2"/);
});
test("undefined, escaped, inline-code, fenced-code, and indented-code references stay literal", () => {
const html = render("Missing[^missing]. Escaped\\[^n]. `[^n]`\n\n```md\n[^n]\n```\n\n [^n]\n\n[^n]: Unused\n");
assert.doesNotMatch(html, /md-footnotes|md-footnote-ref/);
assert.match(html, /Missing\[\^missing\]/);
});
test("footnotes keep HTML escaped and support CRLF", () => {
const html = render("Body[^x]\r\n\r\n[^x]: <script>alert(1)</script>\r\n");
assert.match(html, /&lt;script&gt;/);
assert.doesNotMatch(html, /<script>/);
assert.match(html, /Footnote 1/);
});
+100
View File
@@ -0,0 +1,100 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, writeFile } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { tmpdir } from 'node:os';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.connectOverCDP(process.env.NAVIGATION_NATIVE_CDP || 'http://127.0.0.1:9236');
const context = browser.contexts()[0];
const page = context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
assert.ok(page, 'The isolated main window must be open.');
page.setDefaultTimeout(20000);
const output = resolve('output/host-navigation-pass3-native');
const workspace = join(tmpdir(), 'runestone-pass3-native-workspace');
const results = {};
let detached;
try {
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.pass3-test[\\/]?$/);
results.identity = identity;
await mkdir(output, { recursive: true });
await mkdir(join(workspace, 'folder', 'nested'), { recursive: true });
await mkdir(join(workspace, 'other'), { recursive: true });
await writeFile(join(workspace, 'folder', 'nested', 'note.md'), '# Native note\n\nText for transfer.\n');
await writeFile(join(workspace, 'other', 'keep.md'), '# Keep');
await page.evaluate(async path => {
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('workspace_open', { path });
localStorage.setItem('runestone.workbenchLayout', JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: 'files' }));
}, workspace);
await page.reload();
const row = path => page.locator(`[data-tree-rel="${path}"]`);
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
await row('folder/nested/note.md').click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click();
await page.locator('.tree input').fill('renamed.md'); await page.locator('.tree input').press('Enter');
await row('folder/nested/renamed.md').waitFor();
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/note.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) assert.equal(await row(path).getAttribute('aria-expanded'), 'true');
results.renameUndoPreservesExpandedFolders = true;
await row('folder/nested/note.md').click();
await page.getByRole('tab', { name: /note.md/ }).waitFor();
await page.getByText('Text for transfer.', { exact: true }).waitFor();
const savedLayout = await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout'));
const pending = context.waitForEvent('page');
await page.getByRole('tab', { name: /note.md/ }).click({ button: 'right' });
await page.getByRole('menuitem', { name: 'Open in new window', exact: true }).click();
detached = await pending;
await detached.getByRole('tab', { name: /note.md/ }).waitFor();
await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().minimize());
await detached.getByText('Text for transfer.', { exact: true }).waitFor();
assert.ok(detached.url().includes('tabTransfer='));
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
await page.getByRole('tab', { name: /note.md/ }).waitFor({ state: 'detached' });
const sourceClosed = await page.getByRole('tab', { name: /note.md/ }).count() === 0;
await detached.getByRole('button', { name: 'Show outline', exact: true }).click();
assert.equal(await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), savedLayout);
await detached.getByRole('button', { name: 'Hide outline', exact: true }).click();
results.nativeTransfer = { sourceClosed, columnsHidden: true, savedLayoutPreserved: true };
for (const mode of ['light', 'dark']) {
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await detached.screenshot({ path: join(output, `detached-${mode}.png`) });
}
results.imageJsonIpc = await page.evaluate(async () => {
const { invoke } = await import('/node_modules/@tauri-apps/api/core.js');
const bytes = 50 * 1024 * 1024;
const pixel = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII='), char => char.charCodeAt(0));
const blob = new Blob([pixel, new Uint8Array(bytes - pixel.length)], { type: 'image/png' });
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(blob); });
const contents = JSON.stringify({ schema: 1, data });
const start = performance.now();
await invoke('workspace_write', { rel: '.runestone/pm/images/native-50mib.json', contents });
const written = performance.now();
const read = await invoke('workspace_read', { rel: '.runestone/pm/images/native-50mib.json' });
return { bytes, jsonLength: contents.length, matches: read === contents, writeMs: Math.round(written - start), readMs: Math.round(performance.now() - written) };
});
assert.equal(results.imageJsonIpc.matches, true);
await page.goto('http://127.0.0.1:5186/?settingsWindow=true');
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]);
await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage });
await page.waitForFunction(() => !!JSON.parse(localStorage.getItem('runestone.appearance'))?.newTabBackground?.imageId);
await page.goto('http://127.0.0.1:5186/');
await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await page.reload(); await page.locator('.empty').waitFor();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
results.largeBackground = { bytes: largeImage.length, renderedAfterReload: true };
await page.screenshot({ path: join(output, 'large-background.png') });
await writeFile(join(output, 'results.json'), JSON.stringify(results, null, 2));
console.log(JSON.stringify(results));
} catch (error) {
await writeFile(join(output, 'partial-results.json'), JSON.stringify(results, null, 2));
console.error({ error: String(error), main: await page.locator('body').innerText().catch(() => ''), detached: detached && !detached.isClosed() ? await detached.locator('body').innerText().catch(() => '') : null });
throw error;
} finally {
if (detached && !detached.isClosed()) await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().destroy()).catch(() => {});
await browser.close();
}
+182
View File
@@ -0,0 +1,182 @@
import { createRequire } from 'node:module';
import assert from 'node:assert/strict';
import { mkdir, readFile } 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: 1200, height: 850 } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
const gitRoot = new URL('../../RuneStone_Git/dist/', import.meta.url);
const git = {
manifest: JSON.parse(await readFile(new URL('plugin.json', gitRoot), 'utf8')),
code: await readFile(new URL('main.js', gitRoot), 'utf8'),
css: (await readFile(new URL('style.css', gitRoot))).toString('base64'),
};
await context.addInitScript(git => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['folder/nested/note.md', '# Nested'], ['other/keep.md', '# Keep'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] };
if (command === 'plugins_load') return git.code;
if (command === 'plugins_asset') return git.css;
if (command === 'plugins_data') return 'null';
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (![...files.keys()].some(path => path === args.from || path.startsWith(args.from + '/'))) throw new Error('Missing file');
for (const [path, contents] of [...files]) { if (path === args.from || path.startsWith(args.from + '/')) { files.set(args.to + path.slice(args.from.length), contents); files.delete(path); } } return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
}, git);
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5186';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
async function rename(path, name) {
await row(path).click({ button: 'right' }); await item('Rename').click();
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
}
async function expanded(path) { assert.equal(await row(path).getAttribute('aria-expanded'), 'true', `${path} stays expanded`); }
await mkdir('output/host-navigation-pass3', { recursive: true });
try {
await page.goto(origin);
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
await rename('folder/nested/note.md', 'renamed.md'); await row('folder/nested/renamed.md').waitFor();
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/note.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
await rename('folder', 'renamed-folder'); await row('renamed-folder/nested/renamed.md').waitFor();
await row('renamed-folder').focus(); await page.keyboard.press('Control+z');
await row('folder/nested/renamed.md').waitFor();
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
await page.keyboard.press('Control+y'); await row('renamed-folder/nested/renamed.md').waitFor();
for (const path of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(path);
await paneMenu(); assert.equal(await item('Manage templates…').isVisible(), false);
await item('New note').click(); await row('untitled.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('untitled.md')), '');
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await item('Daily').click(); await row('Daily.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: `output/host-navigation-pass3/note-menu-${mode}.png` });
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 600, height: 600 });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
await page.screenshot({ path: 'output/host-navigation-pass3/note-menu-dark-narrow.png' });
assert.ok(await item('Manage templates…').evaluate(node => node.getBoundingClientRect().right <= innerWidth));
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
await page.setViewportSize({ width: 1200, height: 850 });
await page.evaluate(() => { window.__HOST_TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
assert.equal(await item('Daily').count(), 0);
await item('Manage templates…').click();
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
const creations = await page.evaluate(() => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length);
await paneMenu(); await item('New note').focus(); await page.keyboard.press('Enter');
await page.waitForFunction(count => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
const graph = page.getByRole('menuitem', { name: /Show Git graph/ });
await graph.waitFor();
assert.equal(await page.getByRole('menuitem', { name: /source control/i }).count(), 0);
const graphIcon = await graph.locator('.action-icon').innerHTML();
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
await page.screenshot({ path: 'output/host-navigation-pass3/real-git-command-dark.png' });
await page.keyboard.press('Escape');
await page.evaluate(async () => {
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]);
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
registry.pluginHost.get('browser').newTab = async () => { window.__HOST_TEST__.browserOpened = true; };
});
await page.locator('.header-right').getByRole('button', { name: 'New browser tab', exact: true }).click();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.browserOpened), true);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Project Management', exact: true }).count(), 0);
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
assert.equal(await page.getByRole('menuitem', { name: /Project Management/ }).count(), 1);
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
await page.keyboard.press('Escape');
}
const token = '00000000-0000-4000-8000-000000000001';
const saved = await page.evaluate(token => {
const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' });
localStorage.setItem('runestone.workbenchLayout', layout);
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
return layout;
}, token);
const detached = await context.newPage();
detached.on('pageerror', error => errors.push(error.message));
await detached.goto(`${origin}/?tabTransfer=${token}`);
await detached.getByRole('tab', { name: /a.md/ }).waitFor();
await detached.getByText('# Transferred', { exact: true }).waitFor();
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0);
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0);
await detached.keyboard.press('Control+b');
await detached.keyboard.press('Control+Shift+f');
assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0);
await detached.keyboard.press('Escape');
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
for (const mode of ['light', 'dark']) {
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await detached.setViewportSize({ width: 650, height: 600 });
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
}
assert.deepEqual(errors, []);
console.log('Host navigation passed: nested file/folder rename undo/redo, expanded folders, blank New note parent, template submenu, plugin navigation dedup, detached layout isolation.');
} finally { await browser.close(); }
+165
View File
@@ -0,0 +1,165 @@
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: 1200, height: 850 } });
const page = await context.newPage();
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await context.addInitScript(() => {
window.isTauri = true;
const root = 'C:\\host-todo-test';
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
window.__HOST_TEST__ = state;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async (command, args = {}) => {
state.calls.push({ command, args });
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'workspace_last_path') return root;
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
if (command === 'workspace_list') {
const prefix = args.rel ? args.rel + '/' : '';
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
const tail = path.slice(prefix.length), name = tail.split('/')[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
}
return [...entries.values()];
}
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
if (command === 'workspace_write') {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
files.set(args.rel, args.contents); return;
}
if (command === 'workspace_rename') {
if (files.has(args.to)) throw new Error('Destination exists');
if (!files.has(args.from)) throw new Error('Missing file');
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
}
if (command === 'workspace_delete') { files.delete(args.rel); return; }
if (command === 'workspace_search') return [];
if (command === 'plugin:event|listen') return ++sequence;
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:dialog|message') return 'Ok';
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5173';
const row = path => page.locator(`[data-tree-rel="${path}"]`);
const item = name => page.getByRole('menuitem', { name, exact: true });
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
await mkdir('output/host-todo', { recursive: true });
try {
await page.goto(origin);
await row('a.md').waitFor();
await page.getByRole('button', { name: 'New file Ctrl N' }).click();
await page.getByRole('textbox', { name: 'New file path relative to the workspace' }).waitFor();
await page.mouse.click(5, 700);
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses new-file dialog');
await page.getByRole('button', { name: 'Find a file Ctrl P' }).click();
await page.getByRole('textbox', { name: 'Find a file' }).click();
assert.equal(await page.locator('dialog').count(), 1, 'Inside click keeps file search open');
await page.mouse.click(5, 700);
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses file search');
await row('a.md').click({ button: 'right' });
assert.equal(await item('Copy path').count(), 0);
assert.equal(await item('Copy system path').count(), 1);
await item('Rename').click();
await page.locator('.tree input').fill('renamed.md');
await page.locator('.tree input').press('Enter');
await row('renamed.md').waitFor();
await row('renamed.md').click({ button: 'right' });
assert.equal(await item('Undo rename').count(), 1);
await page.keyboard.press('Escape');
await row('renamed.md').focus(); await page.keyboard.press('Control+z');
await row('a.md').waitFor();
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__HOST_TEST__.files.get('.runestone/marks.json')).pins), ['a.md']);
await row('a.md').focus(); await page.keyboard.press('Control+y');
await row('renamed.md').waitFor();
await paneMenu(); await item('New note').hover();
await item('Daily').click();
await row('Daily.md').waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Rename Daily', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Weekly');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor();
await page.evaluate(() => window.__HOST_TEST__.files.set('.runestone/templates/Existing.md', '# Keep this template'));
await page.getByRole('button', { name: 'Rename Weekly', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Existing');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('alert').filter({ hasText: 'Destination exists' }).waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Existing.md')), '# Keep this template');
for (const mode of ['light', 'dark']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
await page.screenshot({ path: `output/host-todo/templates-${mode}.png` });
}
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).click();
await page.getByRole('tab', { name: 'Weekly.md', exact: true }).waitFor();
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'New template', exact: true }).click();
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Meeting');
await page.getByRole('button', { name: 'Continue', exact: true }).click();
await page.getByRole('tab', { name: 'Meeting.md', exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Meeting.md')), '');
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
await page.getByRole('button', { name: 'Delete Weekly', exact: true }).click();
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor({ state: 'detached' });
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks', 'Deleting template preserves notes');
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
await page.evaluate(() => { for (let i = 0; i < 40; i++) window.__HOST_TEST__.files.set(`.runestone/templates/Long template name ${i}.md`, '# Template'); });
await page.setViewportSize({ width: 600, height: 600 });
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
assert.ok(await page.locator('dialog .list').evaluate(node => node.scrollHeight > node.clientHeight), 'Long template list scrolls');
await page.screenshot({ path: 'output/host-todo/templates-narrow-long.png' });
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
await page.setViewportSize({ width: 1200, height: 850 });
const settings = await context.newPage(); settings.on('pageerror', error => errors.push(error.message));
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByRole('status').filter({ hasText: 'Theme saved to' }).waitFor();
assert.equal(await settings.evaluate(() => JSON.parse(window.__HOST_TEST__.calls.find(call => call.command === 'theme_export').args.contents).schema), 1);
await settings.evaluate(() => window.__HOST_TEST__.exportResult = null);
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByText('Export canceled.', { exact: true }).waitFor();
await settings.evaluate(() => window.__HOST_TEST__.exportError = 'Disk is full');
await settings.getByRole('button', { name: 'Export theme template' }).click();
await settings.getByRole('alert').filter({ hasText: 'Disk is full' }).waitFor();
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
await settings.getByRole('menuitemradio', { name: 'RuneStone', exact: true }).focus();
await settings.keyboard.press('ArrowDown'); await settings.keyboard.press('Enter');
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), 'claude');
assert.equal(await settings.locator('input[type=color]').count(), 0);
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
await page.locator('.empty').waitFor();
await page.waitForFunction(() => document.documentElement.dataset.palette === 'claude');
assert.equal(await page.locator('.empty').evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-bg)'; node.append(reference); const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true);
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'test.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64') });
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
await page.reload(); await page.locator('.empty').waitFor();
assert.ok(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage.includes('blob:')), 'Background survives restart');
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => { const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, mode);
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: `output/host-todo/appearance-${mode}-narrow.png` });
}
assert.equal(await settings.getByRole('button', { name: 'Reset background', exact: true }).isDisabled(), true);
await page.waitForFunction(() => !JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground);
assert.deepEqual(errors, []);
console.log('Host To Do: dialog dismissal, rename undo/redo with marks, template creation/rename/edit/delete, theme export success/cancel/error, shared theme menu, background persistence/reset passed.');
} finally { await browser.close(); }
+33
View File
@@ -0,0 +1,33 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { normalizeAppearance, parseAppearance, exportAppearanceTheme } from '../src/lib/theme/appearance.ts';
test('New tab backgrounds retain supported data while rejecting active and remote content', () => {
const value = { theme: 'claude', mode: 'light', newTabBackground: { image: 'data:image/png;base64,YQ==', overlay: 0 } };
assert.deepEqual(parseAppearance(JSON.stringify(value)), value);
for (const image of ['https://example.com/photo.png', 'javascript:alert(1)', 'data:image/svg+xml;base64,YQ==', 'data:image/png;base64,' + 'A'.repeat(3_000_000)]) {
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: '#224466', image } }).newTabBackground, undefined);
}
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: 'red' } }).newTabBackground, undefined);
assert.equal(normalizeAppearance({ ...value, newTabBackground: undefined }).newTabBackground, undefined);
});
test('Background storage references retain overlay limits and discard obsolete colors', () => {
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, color: '#224466', overlay: 3 } }).newTabBackground, { imageId, overlay: 1 });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: -3 } }).newTabBackground, { imageId, overlay: -1 });
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0 });
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
});
test('Export follows the selected built-in palette and can be imported as a custom theme', async () => {
const { parseCustomTheme } = await import('../src/lib/theme/customThemes.ts');
globalThis.localStorage = { getItem: () => null };
try {
const claude = exportAppearanceTheme('claude');
assert.equal(claude.light.bg, '#faf9f5');
assert.equal(claude.dark.accent, '#d97757');
assert.deepEqual(parseCustomTheme(claude), claude);
const sakura = exportAppearanceTheme('sakura');
assert.deepEqual(sakura.light, sakura.dark);
} finally { delete globalThis.localStorage; }
});
+72
View File
@@ -0,0 +1,72 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { releaseVersion, nextHotfix, compareReleases } from './releaseVersion.mjs';
const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24'];
test('hotfix versions retain their release identity and advance in letter order', () => {
assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' });
for (const [before, after] of [['0.1.23', '0.1.23a'], ['0.1.23a', '0.1.23b'], ['0.1.23b', '0.1.23c'], ['0.1.23z', '0.1.23aa'], ['0.1.23aa', '0.1.23ab'], ['0.1.23zz', '0.1.23aaa']]) assert.equal(nextHotfix(before), after);
for (const version of ['0.1.23A', '0.1.23a1', '0.1.23-a', '0.1.23+1', '0.1', '0.1.23aaaaa', '0.1.65536']) assert.throws(() => releaseVersion(version));
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j));
});
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: process.platform !== 'win32' }, async () => {
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
try {
const checks: string[] = [];
checks.push('StrCpy $0 "keep0"\nStrCpy $1 "keep1"\nPush "0.1.23a"\nPush "0.1.23"\nCall RuneStoneCompareVersions\nPop $2\nStrCmp $0 "keep0" saved0\nSetErrorLevel 1\nQuit\nsaved0:\nStrCmp $1 "keep1" saved1\nSetErrorLevel 1\nQuit\nsaved1:');
let index = 0;
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) {
checks.push(`Push "${ordering[i]}"\nPush "${ordering[j]}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 ${Math.sign(i - j)} check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
}
for (const version of ['0.1.23A', '0.1.23a1', '0.1.a', '0.1.23-rc', '0.1.23aaaaa', '4294967296.0.0']) {
checks.push(`Push "0.1.23a"\nPush "${version}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 -1 check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
}
const executable = path.join(root, 'compare.exe');
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone version check"\nOutFile "${executable}"\n!include LogicLib.nsh\n!include WordFunc.nsh\n!include "${path.resolve('src-tauri/windows/versionCompare.nsh')}"\nSection\n${checks.join('\n')}\nSetErrorLevel 0\nSectionEnd\n`;
const script = path.join(root, 'compare.nsi');
await writeFile(script, source);
const compiler = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/makensis.exe');
const built = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true });
assert.equal(built.status, 0, built.stdout + built.stderr);
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(checked.status, 0, checked.stdout + checked.stderr);
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', executable, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
assert.equal(patched.status, 0, patched.stdout + patched.stderr);
assert.match(patched.stdout, /0\.1\.23a/);
const template = await readFile('src-tauri/windows/installer.nsi', 'utf8');
assert.ok(template.includes('Call RuneStoneCompareVersions'));
assert.ok(!template.includes('nsis_tauri_utils::SemverCompare'));
assert.match(template, /SetErrorLevel 2\n\s+Quit/);
const guard = / !if "\$\{ALLOWDOWNGRADES\}" == "false"\n \$\{If\} \$R0 = -1[\s\S]+? !endif/.exec(template)?.[0];
assert.ok(guard, 'The downgrade guard must precede reinstall and update actions.');
const blockExe = path.join(root, 'block.exe');
const blockScript = path.join(root, 'block.nsi');
await writeFile(blockScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone downgrade check"\nOutFile "${blockExe}"\n!include LogicLib.nsh\n!define ALLOWDOWNGRADES "false"\nLangString dontUninstallDowngrade 1033 "Older versions cannot replace this installation."\nSection\nStrCpy $R0 -1\n${guard}\nSetErrorLevel 1\nSectionEnd\n`);
const blockBuilt = spawnSync(compiler, ['/V2', blockScript], { encoding: 'utf8', windowsHide: true });
assert.equal(blockBuilt.status, 0, blockBuilt.stdout + blockBuilt.stderr);
for (const flags of [['/S'], ['/S', '/P'], ['/S', '/UPDATE']]) {
const blocked = spawnSync(blockExe, flags, { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(blocked.status, 2, 'The installer must block a downgrade with ' + flags.join(' '));
}
assert.match(template, /\$\{ElseIf\} \$R0 = 1 ; Upgrading\n\s+\$\{If\} \$R1 = 1\n\s+Goto reinst_done/);
assert.ok(template.includes('"RuneStoneReleaseVersion" "${VERSION}"'));
assert.ok(template.includes('"DisplayVersion" "${TOOLCHAINVERSION}"'));
const legacyExe = path.join(root, 'legacy.exe');
const legacyScript = path.join(root, 'legacy.nsi');
const pluginPath = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/Plugins/x86-unicode/additional');
await writeFile(legacyScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone legacy version check"\nOutFile "${legacyExe}"\n!addplugindir "${pluginPath}"\nSection\nnsis_tauri_utils::SemverCompare "0.1.23" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_ok\nSetErrorLevel 1\nQuit\nlegacy_ok:\nnsis_tauri_utils::SemverCompare "0.1.22" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_older_ok\nSetErrorLevel 1\nQuit\nlegacy_older_ok:\nnsis_tauri_utils::SemverCompare "0.1.24" "0.1.23+1"\nPop $0\nStrCmp $0 1 legacy_newer_ok\nSetErrorLevel 1\nQuit\nlegacy_newer_ok:\nSetErrorLevel 0\nSectionEnd\n`);
const legacyBuilt = spawnSync(compiler, ['/V2', legacyScript], { encoding: 'utf8', windowsHide: true });
assert.equal(legacyBuilt.status, 0, legacyBuilt.stdout + legacyBuilt.stderr);
const legacyChecked = spawnSync(legacyExe, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
assert.equal(legacyChecked.status, 0, 'Older installers must detect the encoded hotfix as newer.');
} finally {
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
await rm(root, { recursive: true, force: true });
}
});
+44
View File
@@ -0,0 +1,44 @@
import {createRequire} from 'node:module';
import assert from 'node:assert/strict';
const {chromium}=createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser=await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9224');
const context=browser.contexts()[0];
const page=context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
assert.ok(page, 'The isolated main window must be open.');
let transferred, settings;
try {
const identity=await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/);
const pending=context.waitForEvent('page');
const token=await page.evaluate(async()=>{
const {invoke}=await import('/node_modules/@tauri-apps/api/core.js');
const root=await invoke('workspace_last_path');
const token=crypto.randomUUID(), id=crypto.randomUUID();
localStorage.setItem('runestone.tab-transfer.'+token,JSON.stringify({root,created:Date.now(),reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}}));
await invoke('workspace_open_window',{path:root,transfer:token});
return token;
});
transferred=await pending;
await transferred.locator('.empty').waitFor();
assert.ok(transferred.url().includes('?tabTransfer='+token));
assert.ok(!transferred.url().includes('index.html'));
assert.equal(await transferred.getByText('404',{exact:true}).count(),0);
await page.waitForFunction(token=>localStorage.getItem('runestone.tab-transfer.'+token+'.accepted') === 'true',token);
console.log('PASS: native empty-tab transfer loads the splash screen and acknowledges its saved tab state.');
await transferred.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()); transferred=undefined;
settings=context.pages().find(page => page.url().includes('settingsWindow=true'));
const next=settings ? Promise.resolve(settings) : context.waitForEvent('page');
await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/core.js')).invoke('settings_open_window'));
settings=await next;
await settings.waitForURL(/settingsWindow=true/);
await settings.waitForLoadState('domcontentloaded');
const error=await settings.evaluate(async()=>{
try { await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('theme_export',{contents:'{',defaultName:'test.json'}); }
catch(error) { return String(error); }
});
assert.equal(error,'The theme contains invalid JSON.');
console.log('PASS: the native settings window can call theme export; invalid JSON stops before the save dialog.');
} finally {
for(const target of [transferred,settings]) if(target&&!target.isClosed()) await target.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()).catch(()=>{});
await browser.close();
}
+162
View File
@@ -0,0 +1,162 @@
// Run against the host dev server with PLAYWRIGHT_MODULE and CHROME_PATH when needed.
import { createRequire } from "node:module";
import { readFile, mkdir } from "node:fs/promises";
import { resolve } from "node:path";
import assert from "node:assert/strict";
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
const page = await context.newPage();
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
const root = "C:\\kanban-root-smoke";
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
const files = new Map([
["notes/draft.md", "Before.\n\nAfter.\n"],
["files/report [Q1] (#1).pdf", "PDF fixture"],
["images/diagram (#1).svg", btoa(svg)],
]);
const calls = [], callbacks = new Map(), listeners = new Map(); let sequence = 0;
window.kanbanRootSmoke = { files, calls };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback(callback) { callbacks.set(++sequence, callback); return sequence; },
unregisterCallback(id) { callbacks.delete(id); },
async invoke(command, args = {}) {
calls.push({ command, args });
if (command === "plugin:event|listen") { const values = listeners.get(args.event) || []; values.push(args.handler); listeners.set(args.event, values); return args.handler; }
if (command === "plugin:event|unlisten" || command === "spelling_menu_install" || command === "spelling_menu_uninstall") return;
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "kanban-root-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw Error("File missing"); return files.get(args.rel); }
if (command === "workspace_read_data_url") return "data:image/svg+xml;base64," + files.get(args.rel);
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error("Save conflict");
files.set(args.rel, args.contents); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length), name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_search") return [];
if (command === "workspace_recent") return [root];
if (command === "plugins_snapshot") return { plugins: [], issues: [] };
if (command === "plugin:dialog|message") return "Cancel";
if (command.startsWith("plugin:window|") || command === "browser_stop") return;
throw Error("Unhandled IPC: " + command);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
});
const row = path => page.locator(`[data-tree-rel="${path}"]`);
async function drag(path, target) {
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
assert.ok(from && to, "The file and editor must be visible");
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
await page.mouse.down();
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
await page.locator(".image-drop-target").waitFor();
await page.mouse.up();
}
async function writerSource() { return page.evaluate(() => window.kanbanWriter.state.doc.toString()); }
async function ideSource() {
return page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
});
}
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:5173");
await row("notes").click(); await row("notes/draft.md").dblclick();
await page.locator(".cm-content").waitFor();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
window.kanbanWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
});
await row("files").click();
const original = await writerSource();
await drag("files/report [Q1] (#1).pdf", ".cm-content");
await page.waitForFunction(() => window.kanbanWriter.state.doc.toString().includes(".pdf)"));
const linked = await writerSource();
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
assert.ok(!linked.includes("!["), "A document must be a link, not an image");
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original, "Writer undo restores the exact source");
await row("images").click();
await drag("images/diagram (#1).svg", ".cm-content");
await page.locator(".md-image-frame img").waitFor();
assert.ok((await writerSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
assert.equal(await writerSource(), original);
await page.keyboard.press("Control+e");
await page.locator(".monaco-editor textarea").waitFor();
const originalIde = await ideSource();
await page.evaluate(async () => {
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
window.kanbanMonaco = editor;
});
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
await page.waitForFunction(() => window.kanbanMonaco.getValue().includes(".pdf)"));
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
await page.evaluate(() => window.kanbanMonaco.focus());
assert.equal(await page.evaluate(() => window.kanbanMonaco.hasTextFocus()), true);
await page.keyboard.press("Control+z");
await page.waitForFunction(expected => window.kanbanMonaco.getValue() === expected, originalIde, { timeout: 3000 });
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
assert.ok((await ideSource()).includes("![](../images/diagram%20%28%231%29.svg)"));
assert.equal(await page.evaluate(() => window.kanbanRootSmoke.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
console.log("PASS: real FileTree pointer drags insert escaped document links in Writer and IDE, undo restores both, and image drags still embed.");
// Load current Git source through the host origin without creating a distributable.
const gitRoot = process.env.RUNESTONE_GIT_ROOT || resolve("../RuneStone_Git");
const sources = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, await readFile(resolve(gitRoot, "src", file), "utf8")])));
await page.route("**/__kanban_git/*", route => route.fulfill({ contentType: "text/javascript", body: sources.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
const css = await readFile(resolve(gitRoot, "src/style.css"), "utf8");
await page.evaluate(async css => {
const { mountSidebar } = await import("/__kanban_git/view.js");
const container = document.createElement("div"); container.id = "git-smoke"; container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
document.body.append(container);
window.gitGraphOpens = 0;
window.disposeGitSmoke = mountSidebar(container, {
workspace: {},
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
openView: () => window.gitGraphOpens++,
}, css, () => {});
}, css);
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
for (const theme of ["dark", "light"]) {
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
await graph.waitFor();
assert.equal(await graph.locator("svg").count(), 1);
assert.equal(await graph.getAttribute("title"), "Graph");
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
assert.equal(await graph.locator(":scope > :not(.rs-git-icon):not(.rs-git-tooltip)").count(), 0, "Graph has no visible text label");
await page.mouse.move(800, 800); await graph.evaluate(node => node.blur());
assert.equal(await graph.locator(".rs-git-tooltip").isVisible(), false);
await graph.hover(); await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
await page.mouse.move(800, 800); await page.keyboard.press("Tab"); await graph.focus();
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: `.audit/kanban-git-toolbar-${theme}.png` });
}
await graph.click(); assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
await page.evaluate(() => window.disposeGitSmoke());
assert.deepEqual(errors, []);
console.log("PASS: current Git Graph toolbar control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.");
} catch (error) {
await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/kanban-root-failure.png" });
console.error(errors); throw error;
} finally { await browser.close(); }
+31
View File
@@ -0,0 +1,31 @@
import assert from "node:assert/strict";
import test from "node:test";
import { externalLinkText, workspaceLinkText } from "../src/lib/editor/linkCommands.ts";
import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts";
test("external links prepare editable syntax with the cursor in the missing field", () => {
const empty = externalLinkText("", { from: 0, to: 0 });
assert.equal(empty.insert, "[]()");
assert.equal(empty.anchor, 1);
assert.equal(empty.head, 1);
const selected = externalLinkText("before [label] after", { from: 7, to: 14 });
assert.equal(selected.insert, "[\\[label\\]]()");
assert.equal(selected.anchor - selected.from, selected.insert.length - 1);
assert.equal(selected.anchor, selected.head);
});
test("workspace links retain the selected label and the exact workspace path", () => {
assert.equal(workspaceLinkText("", { from: 0, to: 0 }, "notes/Same name.md").insert, "[[/notes/Same%20name.md]]");
const edit = workspaceLinkText("before visible\nlabel after", { from: 7, to: 20 }, "nested/target.md");
assert.equal(edit.insert, "[[/nested/target.md|visible label]]");
assert.equal(edit.anchor, 7);
assert.equal(edit.head, 7 + edit.insert.length);
});
test("workspace link paths preserve spaces, brackets, hashes and literal percent signs", () => {
const path = "notes/Nested/[A] #50%.md";
const edit = workspaceLinkText("", { from: 0, to: 0 }, path);
const target = edit.insert.slice(2, -2);
assert.equal(target, "/notes/Nested/%5BA%5D%20%2350%25.md");
assert.deepEqual(linkCandidates("notes/current.md", target, "wiki"), [path]);
});
+8 -1
View File
@@ -123,7 +123,14 @@ try {
await page.locator(".live-writer td").first().click({ button: "right" }); await page.locator(".live-writer td").first().click({ button: "right" });
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles"); assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
await dismiss(); await dismiss();
await page.getByText("Original text.", { exact: true }).click({ button: "right" }); const wordPoint = await page.getByText("Original text.", { exact: true }).evaluate(element => {
const node = element.firstChild;
const range = document.createRange();
range.setStart(node, 0); range.setEnd(node, "Original".length);
const bounds = range.getBoundingClientRect();
return { x: bounds.left + bounds.width / 2, y: bounds.top + bounds.height / 2 };
});
await page.mouse.click(wordPoint.x, wordPoint.y, { button: "right" });
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [ await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] }, { id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] }, { id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
+71
View File
@@ -0,0 +1,71 @@
// Use only an isolated com.runestone.spelling-test debug window.
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
import assert from 'node:assert/strict';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9237');
const page = browser.contexts()[0].pages()[0];
page.setDefaultTimeout(15000);
const captures = [];
try {
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__);
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).waitFor();
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/);
await page.evaluate(async () => {
const { listen } = await import('/node_modules/@tauri-apps/api/event.js');
window.nativeMenuPayload = null;
await listen('spelling-menu', ({ payload }) => window.nativeMenuPayload = payload);
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('spelling_menu_install');
});
await mkdir('output/todo-menus', { recursive: true });
const menu = page.getByRole('menu', { name: 'Spelling actions', exact: true });
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
for (const kind of ['input', 'textarea', 'dialog']) {
await page.evaluate(kind => {
document.getElementById('native-menu-field')?.remove(); document.getElementById('native-menu-dialog')?.remove();
const field = document.createElement(kind === 'input' ? 'input' : 'textarea');
field.id = 'native-menu-field'; field.spellcheck = true; field.value = 'I recieved a letter.';
field.style.cssText = 'position:fixed;left:100px;top:100px;width:500px;height:100px;font:16px/24px Arial;padding:10px;z-index:100';
if (kind === 'dialog') { const dialog = document.createElement('dialog'); dialog.id = 'native-menu-dialog'; dialog.append(field); document.body.append(dialog); dialog.showModal(); }
else document.body.append(field);
field.focus();
}, kind);
const field = page.locator('#native-menu-field');
await field.press('End');
await field.pressSequentially(' TEST');
await field.click({ button: 'right', position: { x: 300, y: kind === 'input' ? 50 : 22 } });
await menu.waitFor();
const payload = await page.evaluate(() => window.nativeMenuPayload);
captures.push({ mode, kind, value: await field.inputValue(), payload });
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
const flatten = items => items.flatMap(item => [item, ...flatten(item.children)]);
const entries = flatten(payload.items);
assert.ok(entries.every(item => item.kind === 3 || !['share', 'writingDirection', 'voiceTyping', 'other'].includes(item.name)));
assert.ok(entries.some(item => item.name === 'undo' && item.enabled), mode + ' ' + kind + ' keeps native Undo enabled');
assert.ok(entries.some(item => item.name === 'emoji'));
assert.ok(entries.some(item => item.name === 'copy'));
assert.equal(await menu.getByRole('menuitem', { name: /More tools|Writing direction|Voice typing|Share/ }).count(), 0);
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
if (kind === 'textarea') await page.screenshot({ path: `output/todo-menus/native-${mode}.png` });
await menu.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
await page.waitForFunction(() => document.getElementById('native-menu-field').value === 'I recieved a letter.').catch(async error => { console.error('Undo result', await field.inputValue()); throw error; });
await field.click({ button: 'right', position: { x: 48, y: kind === 'input' ? 50 : 22 } });
await menu.getByRole('menuitem', { name: 'received', exact: true }).click();
assert.equal(await field.inputValue(), 'I received a letter.');
await field.press('Control+z');
assert.equal(await field.inputValue(), 'I recieved a letter.');
await field.click({ button: 'right', position: { x: 48, y: kind === 'input' ? 50 : 22 } });
await menu.waitFor();
await page.keyboard.press('Escape');
assert.equal(await field.evaluate(node => document.activeElement === node), true);
}
}
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
console.log('PASS: real WebView2 menus omit unsupported commands, retain editing and spelling, execute native Undo, correct spelling with undo, and restore focus in fields and dialogs in both themes.');
} finally {
await page.evaluate(() => { document.getElementById('native-menu-field')?.remove(); document.getElementById('native-menu-dialog')?.remove(); }).catch(() => {});
await browser.close();
}
+77
View File
@@ -0,0 +1,77 @@
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { mkdir, writeFile } from 'node:fs/promises';
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
await context.addInitScript(() => {
window.isTauri = true;
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
transformCallback: () => ++sequence, unregisterCallback: () => {},
invoke: async command => {
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
if (command === 'plugin:window|is_maximized') return false;
if (command === 'plugin:event|listen') return ++sequence;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
const settings = await context.newPage();
const errors = [];
settings.on('pageerror', error => errors.push(error.message));
await mkdir('output/round4-overlay', { recursive: true });
try {
await settings.goto(origin + '/?settingsWindow=true');
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
name: 'image.png', mimeType: 'image/png',
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'),
});
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay);
await input.fill('-37');
assert.equal(await slider.inputValue(), '-37');
assert.equal(await saved(), -0.37);
await settings.reload();
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
assert.equal(await input.inputValue(), '-37');
await input.fill('');
assert.equal(await saved(), -0.37);
await input.blur();
assert.equal(await input.inputValue(), '-37');
await input.fill('150');
await input.blur();
assert.equal(await input.inputValue(), '100');
assert.equal(await saved(), 1);
await slider.fill('24');
assert.equal(await input.inputValue(), '24');
assert.equal(await saved(), 0.24);
for (const mode of ['light', 'dark']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
window.dispatchEvent(new Event('focus'));
}, mode);
for (const width of [1100, 360]) {
await settings.setViewportSize({ width, height: 780 });
await input.focus();
assert.equal(await input.evaluate(node => node === document.activeElement), true);
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
await settings.screenshot({ path: `output/round4-overlay/${mode}-${width}.png` });
}
}
assert.deepEqual(errors, []);
await writeFile('output/round4-overlay-report.json', JSON.stringify({
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
screenshotFolder: 'output/round4-overlay',
native: 'Native desktop acceptance remains pending.',
}, null, 2));
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
} finally { await browser.close(); }
+1 -1
View File
@@ -86,7 +86,7 @@ export async function packagePlugin(source, destination = "plugin-packages") {
for (const key of ["name", "author", "description", "version"]) { for (const key of ["name", "author", "description", "version"]) {
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`); requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
} }
requireValue(/^\d+\.\d+\.\d+$/.test(manifest.version), "Use a plugin version such as 1.0.0."); requireValue(/^\d+\.\d+\.\d+[a-z]*$/.test(manifest.version), "Use a plugin version such as 1.0.0 or 1.0.0a.");
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module."); requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
const entry = files.find(([name]) => name === manifest.entry)?.[1]; const entry = files.find(([name]) => name === manifest.entry)?.[1];
requireValue(entry, "The entry module is missing."); requireValue(entry, "The entry module is missing.");
+1 -1
View File
@@ -70,7 +70,7 @@ try {
await main.goto(origin); await main.goto(origin);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor(); await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor();
assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0); assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0);
assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 0); assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 1);
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click(); await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click();
await main.getByText('Task content', { exact: true }).waitFor(); await main.getByText('Task content', { exact: true }).waitFor();
await main.evaluate(async () => { await main.evaluate(async () => {
+6
View File
@@ -21,6 +21,12 @@ test("installed RuneStone packages retain access before their next package updat
assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands"); assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands");
}); });
test("command launchers retain the plugin action icon", () => {
const tools = pluginAccess("runestone.git", [command("graph", { category: "open", icon: "git" })], []);
assert.equal(tools[0].icon, "git");
assert.equal(tools[0].surface, "open");
});
test("settings listeners are removable and revoked before plugin cleanup", async () => { test("settings listeners are removable and revoked before plugin cleanup", async () => {
let api!: PluginApi, notify!: () => void; let api!: PluginApi, notify!: () => void;
let received = 0, disposed = 0; let received = 0, disposed = 0;
+11
View File
@@ -23,6 +23,10 @@ test("plugin packaging rejects invalid release inputs before writing an archive"
for (const [changes, message] of [ for (const [changes, message] of [
[{ id: "../escape" }, /ID is invalid/], [{ id: "../escape" }, /ID is invalid/],
[{ version: "1.0" }, /version such as/], [{ version: "1.0" }, /version such as/],
[{ version: "1.0.0A" }, /version such as/],
[{ version: "1.0.0a1" }, /version such as/],
[{ version: "1.0.0-beta" }, /version such as/],
[{ version: "1.0.0+build" }, /version such as/],
[{ entry: "../main.js" }, /compiled JavaScript/], [{ entry: "../main.js" }, /compiled JavaScript/],
[{ apiVersion: 99 }, /Unsupported/], [{ apiVersion: 99 }, /Unsupported/],
[{ author: "" }, /valid author/], [{ author: "" }, /valid author/],
@@ -40,6 +44,13 @@ test("plugin packaging rejects invalid release inputs before writing an archive"
const first = await readFile(path); const first = await readFile(path);
await packagePlugin(source, output); await packagePlugin(source, output);
assert.deepEqual(await readFile(path), first); assert.deepEqual(await readFile(path), first);
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
await save({ version });
const hotfix = await packagePlugin(source, output);
assert.equal(hotfix, join(await realpath(output), `org.test.demo-${version}.zip`));
assert.ok((await readFile(hotfix)).length > 0);
assert.deepEqual(await readFile(path), first);
}
} finally { } finally {
// mkdtemp returns this test's unique directory under the operating system temp folder. // mkdtemp returns this test's unique directory under the operating system temp folder.
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true); assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
+30
View File
@@ -0,0 +1,30 @@
export function releaseVersion(value) {
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)([a-z]*)$/.exec(value);
if (!match) throw Error('Use a release version such as 0.1.23 or 0.1.23a.');
const parts = match.slice(1, 4).map(Number);
let revision = 0;
for (const letter of match[4]) revision = revision * 26 + letter.charCodeAt(0) - 96;
if (parts.some(part => part > 65535) || revision > 65535) throw Error('The Windows version exceeds 65535.');
const base = parts.join('.');
return { version: value, base, suffix: match[4], revision,
toolchain: revision ? `${base}+${revision}` : base, windows: `${base}.${revision}` };
}
export function nextHotfix(value) {
const parsed = releaseVersion(value);
let revision = parsed.revision + 1;
let suffix = '';
while (revision) {
revision--;
suffix = String.fromCharCode(97 + revision % 26) + suffix;
revision = Math.floor(revision / 26);
}
return releaseVersion(parsed.base + suffix).version;
}
export function compareReleases(left, right) {
const a = releaseVersion(left).windows.split('.').map(Number);
const b = releaseVersion(right).windows.split('.').map(Number);
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return Math.sign(a[i] - b[i]);
return 0;
}
+70
View File
@@ -0,0 +1,70 @@
param(
[Parameter(Mandatory)][string]$Path,
[Parameter(Mandatory)][string]$Version,
[Parameter(Mandatory)][string]$NumericVersion
)
$ErrorActionPreference = 'Stop'
Add-Type -TypeDefinition @'
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class RuneStoneVersionResource {
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
static extern IntPtr BeginUpdateResource(string path, bool deleteExisting);
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool UpdateResource(IntPtr handle, IntPtr type, IntPtr name, ushort language, byte[] data, uint size);
[DllImport("kernel32.dll", SetLastError=true)]
static extern bool EndUpdateResource(IntPtr handle, bool discard);
static void Align(BinaryWriter writer) { while (writer.BaseStream.Position % 4 != 0) writer.Write((byte)0); }
static byte[] Text(string value) { return Encoding.Unicode.GetBytes(value + "\0"); }
static byte[] Block(string key, ushort type, byte[] value, ushort valueLength, params byte[][] children) {
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
writer.Write((ushort)0); writer.Write(valueLength); writer.Write(type);
writer.Write(Text(key)); Align(writer); writer.Write(value);
foreach (var child in children) { Align(writer); writer.Write(child); }
long length = stream.Length; stream.Position = 0; writer.Write(checked((ushort)length));
return stream.ToArray();
}
}
static byte[] StringValue(string key, string value) {
var bytes = Text(value); return Block(key, 1, bytes, checked((ushort)(bytes.Length / 2)));
}
public static void Set(string path, string version, string numeric) {
var p = Array.ConvertAll(numeric.Split('.'), UInt16.Parse);
if (p.Length != 4) throw new ArgumentException("Use four Windows version parts.");
var previous = FileVersionInfo.GetVersionInfo(path);
byte[] fixedInfo;
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
uint high = ((uint)p[0] << 16) | p[1], low = ((uint)p[2] << 16) | p[3];
foreach (uint value in new uint[] { 0xFEEF04BD, 0x10000, high, low, high, low, 0x3F, 0, 4, 1, 0, 0, 0 }) writer.Write(value);
fixedInfo = stream.ToArray();
}
var strings = Block("StringFileInfo", 1, new byte[0], 0,
Block("040904B0", 1, new byte[0], 0,
StringValue("CompanyName", previous.CompanyName ?? "RuneStone"),
StringValue("FileDescription", previous.FileDescription ?? "RuneStone"),
StringValue("ProductName", "RuneStone"),
StringValue("OriginalFilename", "runestone.exe"),
StringValue("FileVersion", version), StringValue("ProductVersion", version)));
var vars = Block("VarFileInfo", 1, new byte[0], 0,
Block("Translation", 0, new byte[] { 9, 4, 0xB0, 4 }, 4));
var data = Block("VS_VERSION_INFO", 0, fixedInfo, 52, strings, vars);
var handle = BeginUpdateResource(path, false);
if (handle == IntPtr.Zero) throw new Win32Exception();
if (!UpdateResource(handle, (IntPtr)16, (IntPtr)1, 0, data, (uint)data.Length)) {
var error = new Win32Exception(); EndUpdateResource(handle, true); throw error;
}
if (!EndUpdateResource(handle, false)) throw new Win32Exception();
}
}
'@
$resolvedPath = (Resolve-Path -LiteralPath $Path).Path
[RuneStoneVersionResource]::Set($resolvedPath, $Version, $NumericVersion)
$actual = [Diagnostics.FileVersionInfo]::GetVersionInfo($resolvedPath)
if ($actual.ProductVersion -ne $Version -or $actual.FileVersion -ne $Version) {
throw 'The executable version resource does not match the release version.'
}
$actual | Select-Object FileVersion, ProductVersion, FileMajorPart, FileMinorPart, FileBuildPart, FilePrivatePart
+34 -4
View File
@@ -36,15 +36,26 @@ try {
const before = await editor.innerText(); const before = await editor.innerText();
await page.keyboard.press("End"); await page.keyboard.press("End");
await page.keyboard.type(" TEST"); await page.keyboard.type(" TEST");
assert.notEqual(await editor.innerText(), before); const typed = await editor.innerText();
assert.notEqual(typed, before);
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" }); await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
const menu = page.getByRole("menu", { name: "Spelling actions", exact: true }); const menu = page.getByRole("menu", { name: "Spelling actions", exact: true });
await menu.waitFor(); await menu.waitFor();
await mkdir(".audit", { recursive: true }); await mkdir(".audit", { recursive: true });
await page.screenshot({ path: ".audit/spelling-native.png" }); await page.screenshot({ path: ".audit/spelling-native.png" });
await menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true }).click(); const undo = menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true });
await page.waitForFunction(expected => document.querySelector(".cm-content")?.innerText === expected, before); assert.equal(await undo.isEnabled(), true, "The native Undo command is enabled after typing");
console.log("PASS: real WebView2 command dispatch through the shared menu restores the editor text."); await undo.click();
await page.waitForFunction(previous => document.querySelector(".cm-content")?.innerText !== previous, typed);
const remaining = (await editor.innerText()).match(/^I recieved a letter\.(.*)$/m)?.[1];
assert.ok(remaining !== undefined && remaining.length < " TEST".length && " TEST".startsWith(remaining), "Native Undo reduces the appended text and preserves the original paragraph");
// WebView2 and CodeMirror can group typing differently. Restore the fixture through editor history.
for (let attempt = 0; attempt < 8 && await editor.innerText() !== before; attempt++) {
await page.keyboard.press("Control+z");
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
assert.equal(await editor.innerText(), before, "Bounded keyboard Undo restores the exact original editor text");
console.log("PASS: real WebView2 Undo reduces the typed text, and bounded editor Undo restores the fixture.");
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" }); await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
await menu.waitFor(); await menu.waitFor();
@@ -60,6 +71,25 @@ try {
assert.notEqual(process.env.REQUIRE_NATIVE_SUGGESTIONS, "1", "The test WebView2 profile supplied no spelling suggestions"); assert.notEqual(process.env.REQUIRE_NATIVE_SUGGESTIONS, "1", "The test WebView2 profile supplied no spelling suggestions");
console.log("SKIP: native spelling correction. This WebView2 profile supplied no suggestions. Desktop acceptance is still required."); console.log("SKIP: native spelling correction. This WebView2 profile supplied no suggestions. Desktop acceptance is still required.");
} }
for (const kind of ["input", "textarea", "dialog"]) {
await page.evaluate(kind => {
const field = document.createElement(kind === "input" ? "input" : "textarea");
field.id = "native-spelling-field"; field.spellcheck = true;
field.value = "I recieved a letter.";
field.style.cssText = "position:fixed;left:250px;top:200px;width:500px;height:100px;font:16px/24px Arial;padding:10px;z-index:100";
if (kind === "dialog") { const dialog = document.createElement("dialog"); dialog.id = "native-spelling-dialog"; dialog.append(field); document.body.append(dialog); dialog.showModal(); }
else document.body.append(field);
field.focus();
}, kind);
const field = page.locator("#native-spelling-field"), box = await field.boundingBox();
await page.mouse.click(box.x + 48, box.y + (kind === "input" ? box.height / 2 : 22), { button: "right" });
await menu.getByRole("menuitem", { name: "received", exact: true }).click();
assert.equal(await field.inputValue(), "I received a letter.", kind + " corrects the clicked word");
await page.keyboard.press("Control+z");
assert.equal(await field.inputValue(), "I recieved a letter.", kind + " retains undo");
await page.evaluate(() => { document.getElementById("native-spelling-field")?.remove(); document.getElementById("native-spelling-dialog")?.remove(); });
}
console.log("PASS: native spelling corrections and undo in inputs, card textareas, and top-layer dialogs.");
} finally { } finally {
await page.keyboard.press("Escape").catch(() => {}); await page.keyboard.press("Escape").catch(() => {});
await browser.close(); await browser.close();
+222
View File
@@ -0,0 +1,222 @@
// 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 === "spelling_menu_install") 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 mkdir('output/todo-table', { recursive: true });
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/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const source = '# Table selection\n\n| Name | Value | Notes |\n| --- | :---: | ---: |\n| Alpha | 10 | First |\n| Beta | 20 | Second |\n| Gamma | 30 | Third |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r,c) => table.locator('tr').nth(r).locator('th,td').nth(c);
const selected = table.locator('.is-cell-selected');
async function reset() {
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
await table.waitFor();
}
const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
async function drag(r,c,r2,c2) {
const start = await cell(r,c).boundingBox(), end = await cell(r2,c2).boundingBox();
await page.mouse.move(start.x+start.width/2,start.y+start.height/2);
await page.mouse.down();
await page.mouse.move(end.x+end.width/2,end.y+end.height/2,{steps:8});
await page.mouse.up();
}
await reset();
await drag(1,0,2,1);
assert.equal(await selected.count(),4);
assert.deepEqual(await selected.evaluateAll(cells => cells.map(c => c.getAttribute('data-selection-edges'))),['top left','top right','bottom left','bottom right']);
await page.keyboard.press('Delete');
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
assert.equal(await selected.count(),1);
await page.keyboard.press('Control+z');
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,source);
await drag(2,1,1,0);
await page.keyboard.press('Backspace');
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
await reset();
await drag(1,0,2,1);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Clear cells',exact:true}).click();
assert.equal(await contents(),source.replace('Alpha','').replace('10','').replace('Beta','').replace('20',''));
assert.equal(await selected.count(),4);
await reset();
await cell(1,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
assert.equal(await selected.count(),1);
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),4);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
await reset();
await cell(1,0).click();
await cell(2,2).click({modifiers:['Shift']});
assert.equal(await selected.count(),6);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('tr').count(),2);
assert.ok((await contents()).includes('Gamma'));
await reset();
await drag(0,1,3,1);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('th').count(),2);
assert.ok(!(await contents()).includes('Value'));
const emptyColumns = '# Empty columns\n\n| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.\n';
for (const theme of ['light','dark']) for (const width of [1440,760]) {
await page.setViewportSize({width,height:900});
await page.evaluate(async theme => { const {applyAppearance} = await import('/src/lib/theme/appearance.ts'); applyAppearance({theme:'default',mode:theme}); },theme);
await reset();
await cell(0,1).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 3; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),8);
assert.ok(await selected.evaluateAll(cells => cells.every(c => getComputedStyle(c).borderRadius === '0px')));
await page.screenshot({path:`output/todo-table/selection-${theme}-${width}.png`});
await page.keyboard.press('Shift+F10');
await page.screenshot({path:`output/todo-table/menu-${theme}-${width}.png`});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.writer-table').evaluate(el => document.activeElement === el),true);
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), emptyColumns);
await table.waitFor();
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),15);
await page.screenshot({path:`output/todo-table/empty-columns-selected-${theme}-${width}.png`});
await page.keyboard.press('Delete');
assert.equal(await table.locator('th').count(),3);
assert.equal(await table.locator('tr').count(),5);
assert.equal(await selected.count(),1);
assert.ok((await contents()).includes('| 2cm | Value | |'));
await page.screenshot({path:`output/todo-table/empty-columns-deleted-${theme}-${width}.png`});
await page.keyboard.press('Control+z');
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,emptyColumns);
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('th').count(),3);
await reset();
await cell(2,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
await page.keyboard.press('Backspace');
assert.equal(await table.locator('tr').count(),2);
assert.ok((await contents()).includes('Alpha'));
assert.ok(!(await contents()).includes('Beta'));
await reset();
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Delete');
assert.equal(await table.locator('th').first().innerText(),'Alpha');
await page.keyboard.press('Control+a');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.count(),0);
assert.ok((await contents()).includes('After.'));
}
assert.deepEqual(errors,[]);
console.log('PASS: drag and Shift-click ranges, keyboard range entry and extension, Delete/Backspace remove cells, explicit clear, undo, partial/row/column/all delete, outer edges, light/dark narrow screenshots.');
} catch(error) {
await page.screenshot({path:'output/todo-table/failure.png'});
console.error(errors);
throw error;
} finally { await browser.close(); }
+15
View File
@@ -54,3 +54,18 @@ test("clear preserves structure; delete removes whole rows/columns or shifts par
assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |")); assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |"));
assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail"); assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail");
}); });
test("deleting the empty columns shown on the card removes their structure", () => {
const emptyColumns = "| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.";
const result = deleteTableCells(emptyColumns, { anchor: { row: 4, column: 5 }, head: { row: 0, column: 3 } });
assert.equal(parseMarkdownTable(result)?.columns, 3);
assert.equal(parseMarkdownTable(result)?.rows.length, 6);
assert.ok(result.includes("| 2cm | Value | |"));
assert.ok(result.endsWith("\n\nAfter."));
});
test("deleting the last body rows retains a valid header and alignment", () => {
const result = deleteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 1, column: 0 } });
assert.equal(result, "| A | B | C |\r\n| --- | :---: | ---: |\r\n\r\nTail");
assert.equal(parseMarkdownTable(result)?.rows.length, 2);
});
+16
View File
@@ -0,0 +1,16 @@
import test from "node:test";
import assert from "node:assert/strict";
import { workspaceFileLink } from "../src/lib/editor/workspaceFileLink.ts";
import { wordAt } from "../src/lib/editor/spellingWord.ts";
test("file links resolve across nested folders and escape Markdown punctuation", () => {
assert.equal(workspaceFileLink("notes/deep/source.md", "docs/a [draft](1).pdf"), "[a \\[draft\\](1).pdf](../../docs/a%20%5Bdraft%5D%281%29.pdf)");
assert.equal(workspaceFileLink("notes/source.md", "notes/target.md"), "[target.md](target.md)");
assert.equal(workspaceFileLink("notes/source.md", "assets/pic.png"), "![](../assets/pic.png)");
});
test("spelling finds Unicode words and apostrophes without including punctuation", () => {
assert.deepEqual(wordAt("A naïve word.", 5), { word: "naïve", from: 2, to: 7 });
assert.equal(wordAt("Don't stop", 3)?.word, "Don't");
assert.equal(wordAt("word next", 5), null);
});

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