RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-03 00:23:07 -07:00
commit 5557443ed1
818 changed files with 239368 additions and 0 deletions
+61
View File
@@ -0,0 +1,61 @@
// The built-in browser shows about:blank as a transparent surface with no frame image, and paints real pages, in both themes.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const name = "browser/blankPage";
await runSmoke(name, async ({ browser }) => {
const output = await outputDir(name);
for (const theme of ["light", "dark"]) {
const page = await openPage(browser, { viewport: { width: 1100, height: 780 } });
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\blank-page", files: { "sample.md": "# Sample\n" } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
browser_request: args => {
if (args.command === "frameAck") window.blankAcks = (window.blankAcks || 0) + 1;
return window.browserSnapshot;
},
}),
});
await page.goto(smokeUrl);
await page.getByText("blank-page", { exact: true }).waitFor();
await page.evaluate(async theme => {
(await import("/src/lib/theme/appearance.ts")).saveAppearance({ theme: "default", mode: theme });
const { mount } = await import("/node_modules/svelte/src/index-client.js");
const { default: Browser } = await import("/src/lib/browser/Browser.svelte");
const client = await import("/src/lib/browser/client.ts");
const container = document.createElement("div");
container.id = "browser-test";
Object.assign(container.style, { position: "fixed", inset: "50px 10px 20px", zIndex: "2000", background: "linear-gradient(120deg,#945975,#395c72)" });
document.body.append(container);
window.browserSnapshot = { profiles: [{ id: "user", name: "User" }], tabs: [{ id: "blank", profileId: "user", url: "about:blank", title: "", loading: false }], bookmarks: [], settings: {} };
client.state.set(window.browserSnapshot);
mount(Browser, { target: container, props: { initial: { tabId: "blank" }, onSessionChange() {}, async newTab() {} } });
window.browserClient = client;
}, theme);
const surface = page.locator("#browser-test .surface");
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
await page.evaluate(() => window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 1, width: 10, height: 10, mime: "image/png", data: "AA==" }));
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.equal(await surface.locator("img").count(), 0);
assert.equal(await page.evaluate(() => window.blankAcks), 1);
await page.screenshot({ path: path.join(output, `${theme}-blank-browser.png`) });
await page.evaluate(() => {
window.browserSnapshot.tabs[0].url = "https://example.com/minimal";
window.browserClient.state.set({ ...window.browserSnapshot });
const canvas = document.createElement("canvas");
canvas.width = 10;
canvas.height = 10;
const context = canvas.getContext("2d");
context.fillStyle = "white";
context.fillRect(0, 0, 10, 10);
window.browserClient.frames.get("blank")({ tabId: "blank", frameId: 2, width: 10, height: 10, mime: "image/png", data: canvas.toDataURL().split(",")[1] });
});
await surface.locator("img").waitFor();
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
assert.deepEqual(page.errors, []);
await page.close();
console.log(`PASS: ${theme} blank and painted browser pages`);
}
});
+100
View File
@@ -0,0 +1,100 @@
// The built-in browser: navigation, profiles, independence from the legacy package, same-tab view replacement, a plug-in sidebar, and settings.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/builtin', async ({ page }) => {
await mockTauri(page, {
commands: test => {
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
const check = Object.assign(test, { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] });
let next = 0;
const plugin = (id, name, version, hash) => ({ manifest: { schemaVersion: 1, id, name, author: 'Test', description: '', version, apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash, enabled: true, installedAt: 1, path: '', error: null, removal: false });
return {
browser_connect: () => 'window-session',
workspace_last_path: () => null,
'plugin:window|is_maximized': () => false,
plugins_snapshot: () => ({ root: 'test', plugins: [
plugin('org.test.boards', 'Boards', '0.1.0', 'fixture'),
...(check.legacy && !check.removed ? [plugin('runestone.browser', 'Browser', '0.1.6', 'old')] : []),
] }),
plugins_load: ({ id }) => {
check.loads.push(id);
if (id === 'runestone.browser') throw Error('The old browser package must not load');
return `export function activate(api) {
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
window.__TEST__.mounts.push(id); el.textContent = id;
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
return () => { window.__TEST__.cleanups.push(id); };
}});
api.registerView({ id:'sidebar', title:'Sidebar fixture', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Plugin sidebar fixture'; }});
}`;
},
browser_request: ({ session, command, args }) => {
if (session !== 'window-session') throw Error('Missing browser session');
check.commands.push(command);
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; tab.title = 'Example'; }
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/builtin');
const external = () => page.evaluate(() => performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const editorKeys = module => page.evaluate(async module => {
const { get } = await import('/node_modules/.vite/deps/svelte_store.js');
return get((await import(module)).pluginEditors).map(view => view.key);
}, module);
try {
await page.goto(smokeUrl);
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.waitForFunction(() => window.__TEST__.commands.includes('navigate'));
await page.getByRole('button', { name: 'Browser profile' }).click();
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
await page.keyboard.press('Escape');
const module = await external();
await page.evaluate(async module => { window.__TEST__.legacy = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.evaluate(() => window.__TEST__.loads.includes('runestone.browser')), false);
await page.evaluate(async module => { window.__TEST__.removed = true; await (await import(module)).refreshPlugins(); }, module);
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
await page.evaluate(async module => { (await import(module)).openPluginView('org.test.boards', 'board-a'); }, module);
const before = await editorKeys(module);
await page.getByRole('button', { name: 'Select board B' }).click();
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
await page.waitForFunction(() => window.__TEST__.mounts.includes('board-b') && window.__TEST__.cleanups.includes('board-a'));
assert.deepEqual(await editorKeys(module), before);
await page.getByRole('button', { name: 'Sidebar fixture', exact: true }).click();
await page.getByText('Plugin sidebar fixture', { exact: true }).waitFor();
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `builtin-browser-${theme}.png`) });
}
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await page.getByRole('button', { name: 'Search engine', exact: true }).waitFor({ state: 'visible' });
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
await page.screenshot({ path: path.join(output, `browser-settings-${theme}.png`) });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
}
} catch (error) {
console.error(await page.evaluate(async () => {
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
const { calls, emit, workspace, ...state } = window.__TEST__;
return { state, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
}).catch(reason => ({ diagnosticError: String(reason) })), page.errors);
throw error;
}
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
}, { viewport: { width: 1280, height: 800 } });
+112
View File
@@ -0,0 +1,112 @@
// The browser engine as a separate download: links without an engine, the setup panel in a tab, progress, cancel,
// failure and retry, the switch to the page, and Settings → Browser → Browser engine, in both themes and a narrow window.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/engine', async ({ page }) => {
await mockTauri(page, {
commands: test => {
const status = { state: 'missing', version: '0.1.8', bytes: 160612374, received: 0, error: null };
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
let next = 0;
Object.assign(test, { status, opened: [], requests: [], confirms: [] });
const copy = () => structuredClone(status);
test.setEngine = value => { Object.assign(status, value); test.emit('browser-engine', copy()); };
return {
workspace_last_path: () => null,
'plugin:window|is_maximized': () => false,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
browser_connect: () => 'engine-session',
browser_stop: () => null,
browser_engine_status: copy,
browser_engine_install: () => { Object.assign(status, { state: 'downloading', received: 0, error: null }); return copy(); },
browser_engine_install_file: copy,
browser_engine_cancel: () => { Object.assign(status, { state: 'missing', received: 0 }); return copy(); },
browser_engine_remove: () => { Object.assign(status, { state: 'missing' }); return copy(); },
'plugin:opener|open_url': ({ url }) => { test.opened.push(url); return null; },
'plugin:dialog|message': ({ message }) => { test.confirms.push(message); return 'Remove'; },
browser_request: ({ session, command, args }) => {
if (session !== 'engine-session') throw Error('Missing browser session');
if (status.state !== 'installed') throw Error('The browser engine is not installed.');
test.requests.push(command);
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: args.url || 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'webData') return { profileId: args.profileId, cookies: [], history: [] };
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/engine');
const shots = async name => {
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 page.screenshot({ path: path.join(output, `${name}-${mode}.png`) });
}
};
const panel = page.locator('.engine.tab');
await page.goto(smokeUrl);
// The welcome page shows this button when the browser contribution exists.
await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
// A web link without an engine goes to the system browser. The contribution reports that it did not open the link.
assert.equal(await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').open('https://example.com/link')), false);
assert.deepEqual(await page.evaluate(() => window.__TEST__.requests), [], 'A link does not start the engine.');
// "Open link in app browser" opens a tab with the setup panel and a way out to the system browser.
await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').newTab('https://example.com/docs'));
await panel.waitFor();
assert.equal(await panel.getAttribute('data-engine-state'), 'missing');
await panel.getByText('The engine is a separate download of 161 MB.', { exact: false }).waitFor();
await panel.getByRole('button', { name: 'Open in default browser' }).click();
await page.waitForFunction(() => window.__TEST__.opened.includes('https://example.com/docs'));
const download = panel.getByRole('button', { name: 'Download the engine' });
await download.focus();
assert.equal(await download.evaluate(element => element.matches(':focus-visible') || document.activeElement === element), true);
await shots('missing');
// Download, progress, and cancel.
await download.click();
await page.locator('.engine.tab[data-engine-state="downloading"]').waitFor();
await page.evaluate(() => window.__TEST__.setEngine({ received: 80306187 }));
await panel.getByText('80 MB of 161 MB', { exact: false }).waitFor();
assert.equal(await panel.locator('progress').evaluate(element => element.value), 80306187);
await shots('downloading');
await panel.getByRole('button', { name: 'Cancel' }).click();
await page.locator('.engine.tab[data-engine-state="missing"]').waitFor();
// A failed download shows its cause and Retry.
await page.evaluate(() => window.__TEST__.setEngine({ state: 'missing', error: 'The download stopped: the connection was reset.' }));
await panel.getByRole('alert').getByText('the connection was reset', { exact: false }).waitFor();
await panel.getByRole('button', { name: 'Retry' }).waitFor();
await shots('failed');
// After the installation, the same tab opens the page.
await panel.getByRole('button', { name: 'Retry' }).click();
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installing' }));
await page.locator('.engine.tab[data-engine-state="installing"]').waitFor();
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installed', error: null, received: 0 }));
await page.locator('[data-browser-state="ready"]').waitFor();
assert.equal(await panel.count(), 0);
assert.ok((await page.evaluate(() => window.__TEST__.requests)).includes('newTab'));
assert.equal(await page.evaluate(async () => (await import('/src/lib/plugins/registry.ts')).pluginHost.get('browser').open('https://example.com/link')), true);
// Settings → Browser: the installed engine, Remove with a confirmation, and the missing engine.
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.evaluate(() => window.__TEST__.setEngine({ state: 'installed' }));
await page.getByRole('button', { name: 'Browser', exact: true }).click();
const section = page.locator('.engine.settings');
await section.getByText('Version 0.1.8 is installed.').waitFor();
await page.getByRole('button', { name: 'Search engine', exact: true }).waitFor();
await shots('settings-installed');
await section.getByRole('button', { name: 'Remove engine' }).click();
await page.locator('.engine.settings[data-engine-state="missing"]').waitFor();
assert.match((await page.evaluate(() => window.__TEST__.confirms))[0], /Your profiles, bookmarks, and history stay/);
assert.equal(await page.getByRole('button', { name: 'Search engine', exact: true }).count(), 0, 'Settings that need the engine are hidden.');
await page.getByText('The other browser settings show after the engine is installed.').waitFor();
await page.setViewportSize({ width: 360, height: 800 });
await shots('settings-missing-narrow');
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
console.log('Browser engine setup, progress, failure, install, links, and Settings checks passed.');
}, { viewport: { width: 1280, height: 800 } });
+162
View File
@@ -0,0 +1,162 @@
// Embedded browser fields with the real Electron engine: visible caret, page focus, toolbar blur, inputs, rich text, iframes, and navigation.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>'); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/fields', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
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 mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/fields');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
await page.locator('[data-browser-state="ready"]').waitFor();
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100; attempt++) {
if (await evaluate(code) === expected) return;
await page.waitForTimeout(50);
}
assert.equal(await evaluate(code), expected);
}
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
await page.locator('.surface img').waitFor();
await page.waitForTimeout(300);
const box = await surface.boundingBox();
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(150);
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
await page.waitForFunction(() => {
const image = document.querySelector('.surface img');
if (!image?.complete || !image.naturalWidth) return false;
const surface = document.querySelector('.surface');
const ratio = image.naturalWidth / surface.clientWidth;
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
const context = canvas.getContext('2d');
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
const pixels = context.getImageData(0, 0, 12, 28).data;
let dark = 0;
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
return dark >= 8;
}, null, { timeout: 5000, polling: 50 });
await page.screenshot({ path: path.join(output, `caret-${scale}x.png`) });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
await page.mouse.click(box.x + 100, box.y + 60);
await page.waitForTimeout(100);
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
await page.keyboard.type('Hello World!');
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
await page.mouse.move(box.x + 50, box.y + 60);
await page.mouse.down();
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
await page.mouse.up();
await page.waitForTimeout(200);
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
await page.mouse.click(box.x + 100, box.y + 170);
await page.keyboard.type('Second field');
await expectRemote('document.querySelector("#other").value', 'Second field');
await page.mouse.click(box.x + 100, box.y + 310);
await page.keyboard.press('Control+a');
await page.keyboard.type('Edited rich text');
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
await page.waitForTimeout(200);
await page.mouse.click(box.x + 100, box.y + 415);
await page.keyboard.type('Frame input');
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
await page.getByRole('textbox', { name: 'Address or search' }).focus();
await page.waitForTimeout(100);
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
await rpc('navigate', { tabId, input: 'about:blank' });
await page.waitForTimeout(100);
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
await page.waitForTimeout(400);
await page.mouse.click(box.x + 100, box.y + 60);
await page.keyboard.type('After navigation');
await page.waitForTimeout(500);
assert.equal(await evaluate('devicePixelRatio'), scale, 'Navigation preserves the host pixel ratio');
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
assert.equal(await evaluate('document.hasFocus()'), true);
assert.deepEqual(page.errors, []);
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
} finally {
await engine.stop();
await fixture.close();
}
});
+239
View File
@@ -0,0 +1,239 @@
// Embedded browser input with the real Electron engine: typing, clipboard, composition, page menus, autoscroll, input coalescing, and new tabs.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scale = Number(process.env.BROWSER_TEST_SCALE || 1);
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, commands: [], child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
// A two-frame GIF that the fixture gives only one time, as some image hosts do.
const onceGif = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQACgAAACwAAAAAAQABAAACAkQBACH5BAAKAAAALAAAAAABAAEAAAICTAEAOw==', 'base64');
/** Serve an empty page. A tab on about:blank shows the host background instead of frames (docs/ui-design.md:218). */
async function startFixture() {
let gifServed = false;
const server = createServer((request, response) => {
if (request.url === '/once.gif') {
response.writeHead(200, { 'content-type': gifServed ? 'text/html' : 'image/gif' });
response.end(gifServed ? 'Invalid request' : onceGif); gifServed = true; return;
}
response.writeHead(200, { 'content-type': 'text/html' }); response.end('<!doctype html><title>Fixture</title><body></body>');
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
await runSmoke('browser/interaction', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const { rpc, commands } = engine;
try {
const page = engine.page = await openPage(browser, { viewport: { width: 1280, height: 800 }, deviceScaleFactor: scale, timeout: 30000 });
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 mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
const output = await outputDir('browser/interaction');
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
// The browser toolbar has no new-tab button. The header globe button opens browser tabs
// (src/lib/layout/Workbench.svelte:1300; docs/user-guide.md:177).
assert.equal(await ready.getByRole('button', { name: /New browser tab/ }).count(), 0);
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => rpc('testEvaluate', { tabId, code });
// Load an empty page first: the host shows frames only for loaded pages (src/lib/browser/Browser.svelte:18,264).
await rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
// Input reaches the engine asynchronously, so poll the page for up to five seconds before asserting.
async function expectRemote(code, expected) {
for (let attempt = 0; attempt < 100 && await evaluate(code) !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate(code), expected);
}
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 expectRemote('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 expectRemote('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 expectRemote('document.querySelector("#typing").value.endsWith("日本語")', true);
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 expectRemote('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 expectRemote('document.querySelector("#typing").value', 'https://example.com/');
// Copy image keeps the GIF bytes that the page loaded, also when the website refuses a second request.
const gifUrl = `${fixture.url}once.gif`;
await evaluate(`document.body.innerHTML='<img id="gif" src="${gifUrl}" style="position:absolute;left:40px;top:300px;width:80px;height:80px">';true;`);
await expectRemote('document.querySelector("#gif").complete && document.querySelector("#gif").naturalWidth', 1);
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Copy image', exact: true }).click();
const copied = await page.evaluate(async url => (await import('/src/lib/workspace/copiedImage.ts')).copiedImage(url), gifUrl);
assert.equal(copied, `data:image/gif;base64,${onceGif.toString('base64')}`);
assert.equal(commands.filter(call => call.command === 'copiedImage').length, 1);
// A new browser tab opens in front. Close it, so that the next steps use the first tab again.
async function expectTab(url) {
for (let attempt = 0; attempt < 100 && !(await rpc('state')).tabs.some(tab => tab.url === url); attempt++) await page.waitForTimeout(50);
assert.ok((await rpc('state')).tabs.some(tab => tab.url === url), `A new browser tab opens ${url}`);
await page.keyboard.press('Control+w');
for (let attempt = 0; attempt < 100 && (await rpc('state')).tabs.length > 1; attempt++) await page.waitForTimeout(50);
assert.equal((await rpc('state')).tabs.length, 1);
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
}
await page.mouse.click(initialBox.x + 80, initialBox.y + 340, { button: 'right' });
await page.getByRole('menuitem', { name: 'Open image in new tab', exact: true }).click();
await expectTab(gifUrl);
// A middle-click on a link opens the link in a new tab instead of scrolling.
const linked = `${fixture.url}linked`;
await evaluate(`document.body.innerHTML='<a href="${linked}" style="position:absolute;left:40px;top:300px;display:block;width:200px;height:40px">Linked page</a>';true;`);
await page.mouse.click(initialBox.x + 100, initialBox.y + 320, { button: 'middle' });
await expectTab(linked);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A middle-click on a link does not keep scrolling');
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
await page.locator('.surface img').waitFor();
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
await page.waitForTimeout(3000);
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
const wheelCount = () => commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
const beforeWheels = wheelCount();
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 = wheelCount() - beforeWheels;
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
await evaluate('window.testAnimate=false;true;');
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
await page.locator('.surface img').waitFor();
const box = await surface.boundingBox();
const x = box.x + 220, y = box.y + 180;
await page.mouse.click(x, y, { button: 'middle' });
// The marker draws the four-way scroll icon, not a text glyph that depends on the font.
const marker = page.locator('.scroll-anchor');
assert.equal(await marker.locator('svg path').count(), 1);
assert.equal(await marker.evaluate(node => node.textContent.trim()), '');
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).applyAppearance({ theme: 'default', mode }), theme);
await page.screenshot({ path: path.join(output, `scroll-marker-${theme}.png`), clip: { x: x - 30, y: y - 30, width: 60, height: 60 } });
}
await page.mouse.move(x + 90, y + 120);
await page.waitForTimeout(1500);
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors: page.errors })}`);
await page.keyboard.press('Escape');
await page.waitForTimeout(350);
const stopped = await evaluate('scrollY');
await page.waitForTimeout(200);
assert.equal(await evaluate('scrollY'), stopped);
assert.equal(await page.locator('.scroll-anchor').count(), 0);
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
await page.waitForTimeout(100);
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
await page.mouse.click(x, y, { button: 'middle' });
await page.mouse.click(x, y, { button: 'left' });
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
await page.mouse.click(x, y, { button: 'middle' });
await page.getByRole('textbox', { name: 'Address or search' }).focus();
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
const motionCount = () => commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
const beforeMotion = motionCount();
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i = 0; i < 500; i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX: x + i % 20, clientY: y, bubbles: true })); }, { x, y });
await page.waitForTimeout(100);
const pointerBurstCalls = motionCount() - beforeMotion;
assert.ok(pointerBurstCalls < 10, `Pointer bursts must not queue hundreds of native calls: ${pointerBurstCalls}`);
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
await page.mouse.click(x, y, { button: 'middle' });
await page.screenshot({ path: path.join(output, `browser-interaction-${theme}.png`) });
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 420, height: 650 });
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
await page.setViewportSize({ width: 1280, height: 800 });
await page.keyboard.press('Control+t');
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
assert.deepEqual(page.errors, []);
await writeFile(path.join(output, `browser-interaction-${scale}x.json`), JSON.stringify({ decodedFps, scrolled, pointerBurstCalls, 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 typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
} finally {
await engine.stop();
await fixture.close();
}
});
+179
View File
@@ -0,0 +1,179 @@
// Embedded browser sharpness with the real Electron engine: frames map one page pixel to one host pixel at each display scale,
// a display scale change (a move to another monitor) updates the frame scale, and pointer input lands on the page point under it.
// @requires electron
import { createRequire } from 'node:module';
import { spawn } from 'node:child_process';
import { createServer } from 'node:http';
import { mkdtemp, writeFile } from 'node:fs/promises';
import path from 'node:path';
import os from 'node:os';
import assert from 'node:assert/strict';
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
const runtime = path.join(repoRoot, 'browser-runtime');
const electron = createRequire(path.join(runtime, 'package.json'))('electron');
const scales = process.env.BROWSER_TEST_SCALE ? [Number(process.env.BROWSER_TEST_SCALE)] : [1, 1.25, 1.5, 2];
/** Start the Electron browser engine and relay its frames and state events to `page` once it is set. */
async function startEngine() {
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-scale-'));
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
});
const engine = { page: undefined, child };
let sequence = 0, pendingFrame, painting = false;
const pending = new Map();
engine.rpc = (command, args = {}) => new Promise((resolve, reject) => {
const id = ++sequence;
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
child.send({ id, command, args });
});
async function paint() {
if (painting || !engine.page || !pendingFrame) return;
painting = true;
const frame = pendingFrame; pendingFrame = undefined;
await engine.page.evaluate(value => window.__TEST__?.emit('browser-frame', value), frame).catch(() => {});
painting = false;
if (pendingFrame) void paint();
}
await new Promise((resolve, reject) => {
child.on('error', reject);
child.on('message', message => {
if (message.ready) resolve();
if (message.id) {
const callback = pending.get(message.id); pending.delete(message.id);
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
}
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
else if (message.event && engine.page) void engine.page.evaluate(value => window.__TEST__?.emit('browser-state', value), message.event).catch(() => {});
});
});
engine.stop = async () => { await engine.rpc('shutdown').catch(() => {}); child.kill(); };
return engine;
}
/**
* Serve a page and return the markup of the scale fixture. The engine gateway blocks local addresses, so the test writes the markup into the page.
* The fixture has 1-device-pixel black and white columns in its top-left 200 by 100 CSS pixels, and text below them.
* `draw()` draws the columns again for the current pixel ratio. The page records the position of each click.
*/
async function startFixture() {
const html = `<!doctype html><title>Scale fixture</title><body style="margin:0;background:#fff;color:#111;font:14px sans-serif">
<canvas id="stripes" style="display:block;width:200px;height:100px"></canvas><p style="margin:8px">Sharp text: The quick brown fox jumps over the lazy dog. 0123456789</p>
<script>
function draw(){const c=document.getElementById('stripes'),r=devicePixelRatio;c.width=Math.round(200*r);c.height=Math.round(100*r);const g=c.getContext('2d');g.fillStyle='#fff';g.fillRect(0,0,c.width,c.height);g.fillStyle='#000';for(let x=0;x<c.width;x+=2)g.fillRect(x,0,1,c.height);}
draw();window.clicks=[];addEventListener('mousedown',e=>clicks.push([e.clientX,e.clientY]));
</script>`;
const server = createServer((_request, response) => { response.writeHead(200, { 'content-type': 'text/html' }); response.end(html); });
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
return { html, url: `http://127.0.0.1:${server.address().port}/`, close: () => new Promise(resolve => server.close(resolve)) };
}
/**
* Return the mean absolute difference between horizontal neighbours in the stripe area of the frame image, read from a screenshot of the whole host page.
* The value is 255 for an exact copy of the page pixels. Resampling blends neighbours and lowers it.
* The test does not measure an element screenshot, because a clip at a fractional device pixel resamples the screenshot itself.
*/
async function stripeContrast(page, png, scale) {
return page.evaluate(async ({ data, scale }) => {
const box = document.querySelector('.surface img').getBoundingClientRect();
const left = Math.round(box.left * devicePixelRatio), top = Math.round(box.top * devicePixelRatio);
const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode();
const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height;
const context = canvas.getContext('2d'); context.drawImage(image, 0, 0);
const width = Math.round(180 * scale), row = context.getImageData(left, top + Math.round(50 * scale), width, 1).data;
let sum = 0;
for (let x = 0; x < width - 1; x++) sum += Math.abs(row[x * 4] - row[x * 4 + 4]);
return sum / (width - 1);
}, { data: png.toString('base64'), scale });
}
await runSmoke('browser/scale', async ({ browser }) => {
const engine = await startEngine();
const fixture = await startFixture();
const output = await outputDir('browser/scale');
const report = {};
try {
for (const scale of scales) {
const context = await browser.newContext({ viewport: { width: 1000, height: 700 }, deviceScaleFactor: scale });
const page = engine.page = await openPage(context, { timeout: 30000 });
await page.exposeFunction('browserRpc', (command, args) => engine.rpc(command, args));
// Keep each resolution media query list of the host, so the test can report a scale change to the host page.
await page.addInitScript(() => { const native = matchMedia.bind(window); window.__resolutionQueries = []; window.matchMedia = query => { const list = native(query); if (query.includes('resolution')) window.__resolutionQueries.push(list); return list; }; });
await mockTauri(page, {
commands: () => ({
browser_connect: () => 'test-session',
browser_request: ({ command, args }) => window.browserRpc(command, args),
workspace_last_path: () => null,
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
}),
});
await page.goto(smokeUrl);
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
const ready = page.locator('[data-browser-state="ready"]');
await ready.waitFor();
const tabId = await ready.getAttribute('data-browser-tab');
const evaluate = code => engine.rpc('testEvaluate', { tabId, code });
await engine.rpc('navigate', { tabId, input: fixture.url });
await page.locator('.browser:not(.blank)[data-browser-state="ready"]').waitFor();
await evaluate(`document.open();document.write(${JSON.stringify(fixture.html)});document.close();true;`);
await page.locator('.browser:not(.blank)[data-browser-state="ready"] .surface img').waitFor();
const surface = page.getByRole('application', { name: 'Web page', exact: true });
/**
* Wait for the lossless frame of the current scale, then measure and save the host pixels of the surface.
* `cdp` takes the screenshot through a CDP session with its own scale override, because a Playwright screenshot applies the context scale again.
*/
async function measure(expected, name, cdp) {
for (let attempt = 0; attempt < 100 && await evaluate('devicePixelRatio') !== expected; attempt++) await page.waitForTimeout(50);
assert.equal(await evaluate('devicePixelRatio'), expected, `The page pixel ratio follows the host at ${name}`);
// Emulation in the engine also changes the ratio without a media query event, so draw the columns again.
await evaluate('draw();true;');
await page.waitForTimeout(400);
await page.waitForFunction(() => document.querySelector('.surface img')?.src.startsWith('data:image/png'));
let png;
if (cdp) png = Buffer.from((await cdp.send('Page.captureScreenshot', { format: 'png' })).data, 'base64');
else {
await surface.screenshot({ path: path.join(output, `surface-${name}.png`) });
png = await page.screenshot();
}
await writeFile(path.join(output, `window-${name}.png`), png);
return stripeContrast(page, png, expected);
}
const contrast = await measure(scale, `${scale}x`);
assert.ok(contrast > 240, `Frames must not be resampled at ${scale}x: neighbour contrast ${contrast.toFixed(1)}`);
const box = await surface.boundingBox();
await evaluate('clicks.length=0;true;');
for (const [x, y] of [[37, 61], [412, 233]]) await page.mouse.click(box.x + x, box.y + y);
for (let attempt = 0; attempt < 100 && (await evaluate('clicks.length')) < 2; attempt++) await page.waitForTimeout(50);
const clicks = await evaluate('clicks');
// Native input uses whole device pixels, and the frame can start up to one device pixel inside the surface. Allow one CSS pixel.
assert.ok(clicks.length === 2 && clicks.every(([x, y], index) => Math.abs(x - [37, 412][index]) <= 1 && Math.abs(y - [61, 233][index]) <= 1),
`Clicks land on the page point under the pointer at ${scale}x: ${JSON.stringify(clicks)}`);
report[`${scale}x`] = { contrast, clicks };
if (scale === 1.5) {
// A move to a monitor with a different scale changes devicePixelRatio but not the CSS size of the surface.
// Emulation changes the pixel ratio without a media query change event, so the test sends the event that a real display change sends.
const cdp = await page.context().newCDPSession(page);
await cdp.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 700, deviceScaleFactor: 1.25, mobile: false });
await page.evaluate(() => { for (const list of [...window.__resolutionQueries]) list.dispatchEvent(new Event('change')); });
const moved = await measure(1.25, '1.5x-to-1.25x', cdp);
assert.ok(moved > 240, `Frames must follow a display scale change: neighbour contrast ${moved.toFixed(1)}`);
report['1.5x-to-1.25x'] = { contrast: moved };
}
assert.deepEqual(page.errors, []);
engine.page = undefined;
await engine.rpc('closeTab', { tabId });
await context.close();
}
await writeFile(path.join(output, 'browser-scale.json'), JSON.stringify(report, null, 2));
console.log(`PASS browser frames are sharp at ${scales.join(', ')}x, follow a scale change, and keep pointer positions`);
} finally {
await engine.stop();
await fixture.close();
}
});
@@ -0,0 +1,98 @@
// Browser settings choice menus: keyboard selection and dismissal, saving, long profile lists, both themes, narrow layout, and cleanup.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/settingsMenus', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
// `requests` records browser requests; `calls` records every IPC command.
Object.assign(test, { snapshot, requests: [] });
return {
browser_connect: () => 'menu-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: ({ command, args = {} }) => {
test.requests.push({ command, ...args });
if (command === 'webData') return { profileId: args.profileId, cookies: [], history: [] };
if (command === 'settings') Object.assign(snapshot.settings, args);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/settingsMenus');
const shot = name => page.screenshot({ path: path.join(output, name) });
const menu = name => page.getByRole('menu', { name, exact: true });
const trigger = name => page.getByRole('button', { name, exact: true });
await page.goto(smokeUrl + '/?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 shot(`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 shot(`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.__TEST__.requests.some(request => request.command === 'webData' && request.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 shot(`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();
// A choice applies at once (src/lib/browser/Settings.svelte).
await page.waitForFunction(() => window.__TEST__.snapshot.settings.search === 'google');
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.__TEST__.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 shot('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');
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
}, { viewport: { width: 1100, height: 850 }, timeout: 30000 });
+205
View File
@@ -0,0 +1,205 @@
// Browser web data settings: cookie and history lists, filters, removal, profile isolation, stale-response guards, and narrow layouts.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, outputDir, runSmoke, settle as settleFrames, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/webData', async ({ page }) => {
await mockTauri(page, {
label: 'settings-main',
commands: test => {
const snapshot = {
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
bookmarks: [],
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
};
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
const data = {
user: {
profileId: 'user',
cookies: [
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
],
history: [
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
],
},
work: {
profileId: 'work',
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
},
};
// `requests` records browser requests; `hold` keys delay a request until the test releases it.
const check = Object.assign(test, { data, snapshot, requests: [], hold: [], pending: [], failNext: {} });
return {
browser_connect: () => 'web-data-session',
plugins_snapshot: () => ({ root: 'test', plugins: [] }),
'plugin:window|is_maximized': () => false,
browser_request: async ({ session, command: operation, args: details = {} }) => {
if (session !== 'web-data-session') throw Error('Missing browser session');
const key = `${operation}:${details.profileId}`;
check.requests.push({ operation, ...details });
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
if (operation === 'webData') return nextData;
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
return structuredClone(snapshot);
},
};
},
});
const output = await outputDir('browser/webData');
const section = page.getByRole('region', { name: 'Individual web data', 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('button', { name: 'Web data type', exact: true });
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
async function hold(key) { await page.evaluate(key => { window.__TEST__.hold.push(key); }, key); }
async function pending(key) { await page.waitForFunction(key => window.__TEST__.pending.some(item => item.key === key), key); }
async function release(key, error) {
await page.evaluate(({ key, error }) => {
const check = window.__TEST__;
check.hold = check.hold.filter(item => item !== key);
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
if (!item) throw Error('No pending request for ' + key);
if (error) item.reject(Error(error)); else item.resolve();
}, { key, error });
await settleFrames(page);
}
try {
await page.goto(smokeUrl + '/?settingsWindow=true');
await page.getByRole('button', { name: 'Browser', exact: true }).click();
await personalCookie().waitFor();
assert.equal(await section.locator('.entry').count(), 3);
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
await filter.fill('PERSONAL.EXAMPLE');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('/settings');
assert.equal(await section.locator('.entry').count(), 1);
await filter.fill('no matches');
await section.getByText('No matching cookies.', { exact: true }).waitFor();
await filter.fill('session');
await personalCookie().click();
await settle();
await section.getByText('No matching cookies.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
await selectKind('history');
await filter.fill('GUIDE');
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
await settle();
await section.getByText('No matching history.', { exact: true }).waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.data.work.history.length), 1);
await filter.fill('another.example/document');
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
assert.equal(await section.locator('.entry').count(), 1);
await selectProfile('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await selectKind('cookies');
await workCookie().waitFor();
// A delayed successful response from the previous profile must not replace the current rows.
await hold('webData:work');
await refresh.click();
await pending('webData:work');
assert.equal(await workCookie().isDisabled(), true);
await selectProfile('user');
await settle();
await release('webData:work');
assert.equal(await workCookie().count(), 0);
assert.equal(await section.locator('.entry').count(), 2);
// The same guard must ignore an old request error.
await hold('webData:user');
await refresh.click();
await pending('webData:user');
await selectProfile('work');
await workCookie().waitFor();
await settle();
await release('webData:user', 'Stale personal error');
assert.equal(await section.getByRole('alert').count(), 0);
assert.equal(await refresh.isEnabled(), true);
// Removal finishes for its original profile without refreshing the selected profile.
await hold('removeCookie:work');
await workCookie().click();
await pending('removeCookie:work');
await selectProfile('user');
await settle();
const readsBefore = await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length);
await release('removeCookie:work');
assert.equal(await profile.innerText(), 'Personal');
assert.equal(await section.locator('.entry').count(), 2);
assert.equal(await page.evaluate(() => window.__TEST__.requests.filter(item => item.operation === 'webData').length), readsBefore);
assert.equal(await page.evaluate(() => window.__TEST__.data.work.cookies.length), 0);
await page.evaluate(() => { window.__TEST__.failNext['webData:user'] = 'Cannot read personal data'; });
await refresh.click();
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
assert.equal(await refresh.isEnabled(), true);
await refresh.click();
await settle();
assert.equal(await section.getByRole('alert').count(), 0);
await page.evaluate(() => { window.__TEST__.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
await unnamed.click();
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
assert.equal(await unnamed.isEnabled(), true);
await unnamed.click();
await settle();
assert.equal(await unnamed.count(), 0);
assert.equal(await section.getByRole('alert').count(), 0);
assert.deepEqual(await page.evaluate(() => window.__TEST__.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
assert.equal(await page.evaluate(() => window.__TEST__.requests.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
await page.setViewportSize({ width: 360, height: 800 });
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => {
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
saveAppearance({ theme: 'default', mode });
}, theme);
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#fdfdfa' : '#151617');
for (const dataType of ['cookies', 'history']) {
await selectKind(dataType);
await section.scrollIntoViewIfNeeded();
await page.screenshot({ path: path.join(output, `browser-web-data-${dataType}-${theme}.png`) });
const overflow = await section.evaluate(node => {
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
});
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
}));
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
await filter.focus();
await page.keyboard.press('Tab');
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
}
}
} catch (error) {
console.error(await page.locator('body').innerText());
throw error;
}
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
}, { viewport: { width: 1100, height: 850 } });
+53
View File
@@ -0,0 +1,53 @@
// A browser window (`?browserWindow=true`): it adopts the moved tab, starts no installed plugin,
// and calls only the commands that src-tauri/capabilities/browser.json grants.
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, repoRoot, runSmoke, smokeUrl } from '../_harness/index.mjs';
await runSmoke('browser/window', async ({ page }) => {
await mockTauri(page, {
label: 'browser-smoke',
commands: test => {
const snapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'moved', profileId: 'user', url: 'https://example.com', title: 'Example', loading: false, blocked: 0, canBack: false, canForward: false, transferToken: 'token' }], bookmarks: [], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
let next = 0;
return {
browser_connect: () => 'window-session',
browser_stop: () => null,
browser_request: ({ session, command, args }) => {
if (session !== 'window-session') throw Error('Missing browser session');
if (command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
if (command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.tabId);
if (command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.tabId); tab.url = args.input; }
return structuredClone(snapshot);
},
// An installed plugin that a browser window must not load.
plugins_snapshot: () => ({ root: 'test', plugins: [{ manifest: { schemaVersion: 1, id: 'org.test.tasks', name: 'Tasks', author: 'Test', description: '', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'tasks', enabled: true, installedAt: 1, path: '', error: null, removal: false }] }),
spelling_menu_install: () => null,
spelling_menu_uninstall: () => null,
'plugin:window|is_maximized': () => false,
};
},
});
await page.goto(smokeUrl + '/?browserWindow=true&browserTab=moved');
await page.getByRole('application', { name: 'RuneStone browser' }).waitFor();
await page.locator('[data-browser-state="ready"]').waitFor();
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.org');
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
await page.keyboard.press('Control+t');
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'browser_request' && call.args.command === 'newTab'));
const capability = JSON.parse(await readFile(path.join(repoRoot, 'src-tauri/capabilities/browser.json'), 'utf8'));
const granted = new Set(capability.permissions);
const calls = await page.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
assert(!calls.includes('plugins_load'), 'A browser window loads no installed plugin.');
const missing = calls.filter(command => {
const plugin = /^plugin:([^|]+)\|(.+)$/.exec(command);
// core:default grants the event plugin and the read-only window commands. Window actions need their own permission.
if (plugin) return plugin[1] === 'window' && /^(destroy|close|minimize|toggle_maximize|start_dragging)$/.test(plugin[2])
? !granted.has(`core:window:allow-${plugin[2].replaceAll('_', '-')}`) : !['event', 'window', 'webview', 'app'].includes(plugin[1]);
return !granted.has(`allow-${command.replaceAll('_', '-')}`);
});
assert.deepEqual(missing, [], 'Every command of the browser window is in capabilities/browser.json.');
console.log(`Browser window commands: ${calls.join(', ')}`);
}, { viewport: { width: 1100, height: 750 } });