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
+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));