Move the smoke tests onto the shared harness
Each smoke test now uses tests/smoke/_harness/ for Playwright, the Tauri IPC mock, the in-memory workspace, and output folders, instead of its own copy. The tests keep their interactions and assertions. Mock handlers that the app never calls are gone. - Split the four mixed regression scripts into 18 feature tests. - Update tests that broke when the app changed on purpose. Each update cites the app source that shows the new behavior. - Mark two real app defects with @known-issue: the settings window controls are 1px shorter than the main window controls, and plugin tabs cannot be reordered by dragging without a workspace. - Merge three palette unit tests into one table-driven test. - The native tests load Playwright through the harness and read NATIVE_CDP_URL, with their old variable names as fallbacks. - A failed smoke test saves a screenshot and prints the console errors. - The runner runs failed tests once more, alone, and reports a test that then passes as flaky. Result: 89 passed, 1 flaky, 2 known issues, 0 failed. Before, 45 of 78 passed.
This commit is contained in:
@@ -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`);
|
||||
}
|
||||
});
|
||||
@@ -1,109 +1,100 @@
|
||||
import { createRequire } from 'node:module';
|
||||
// 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 { mkdir } from 'node:fs/promises';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(); let next = 0;
|
||||
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
|
||||
window.builtinCheck = { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'window-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [
|
||||
{ manifest: { schemaVersion: 1, id: 'org.test.boards', name: 'Boards', author: 'Test', description: '', version: '0.1.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'fixture', enabled: true, installedAt: 1, path: '', error: null, removal: false },
|
||||
...(window.builtinCheck.legacy && !window.builtinCheck.removed ? [{ manifest: { schemaVersion: 1, id: 'runestone.browser', name: 'Browser', author: 'Test', description: '', version: '0.1.6', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'old', enabled: true, installedAt: 1, path: '', error: null, removal: false }] : [])
|
||||
] };
|
||||
if (command === 'plugins_load') {
|
||||
window.builtinCheck.loads.push(args.id);
|
||||
if (args.id === 'runestone.browser') throw Error('The old browser package must not load');
|
||||
return `export function activate(api) {
|
||||
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
|
||||
window.builtinCheck.mounts.push(id); el.textContent = id;
|
||||
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
|
||||
return () => { window.builtinCheck.cleanups.push(id); };
|
||||
}});
|
||||
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
|
||||
}`;
|
||||
}
|
||||
if (command === 'browser_request') {
|
||||
if (args.session !== 'window-session') throw Error('Missing browser session');
|
||||
window.builtinCheck.commands.push(args.command);
|
||||
if (args.command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||
if (args.command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.args.tabId);
|
||||
if (args.command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.args.tabId); tab.url = args.args.input; tab.title = 'Example'; }
|
||||
if (args.command === 'settings') Object.assign(snapshot.settings, args.args);
|
||||
return structuredClone(snapshot);
|
||||
}
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error('Unhandled IPC: ' + command);
|
||||
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:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git 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: 'Source control', exact: true }).click();
|
||||
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
|
||||
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`) });
|
||||
}
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
});
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5174');
|
||||
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
|
||||
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
|
||||
await page.getByRole('button', { name: 'Browser profile' }).click();
|
||||
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
|
||||
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
|
||||
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
|
||||
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
|
||||
await page.evaluate(async () => { const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); openPluginView('org.test.boards', 'board-a'); });
|
||||
const before = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
|
||||
await page.getByRole('button', { name: 'Select board B' }).click();
|
||||
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
|
||||
await page.waitForFunction(() => window.builtinCheck.mounts.includes('board-b') && window.builtinCheck.cleanups.includes('board-a'));
|
||||
const after = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
|
||||
assert.deepEqual(after, before);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).click();
|
||||
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
|
||||
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await page.screenshot({ path: `.audit/cards-2026-10-08-next/builtin-browser-${theme}.png` });
|
||||
await page.goto(smokeUrl + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Browser', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Save browser settings' }).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;
|
||||
}
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Browser', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
|
||||
assert.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: `.audit/cards-2026-10-08-next/browser-settings-${theme}.png` });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error(await page.evaluate(async () => {
|
||||
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
|
||||
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
|
||||
}).catch(reason => ({ diagnosticError: String(reason) })), errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
}, { viewport: { width: 1280, height: 800 } });
|
||||
|
||||
@@ -1,154 +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 { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
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';
|
||||
const runtime = path.resolve('browser-runtime');
|
||||
const require = createRequire(path.join(runtime, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const electron = require('electron');
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
|
||||
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
|
||||
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
|
||||
});
|
||||
let sequence = 0, page, pendingFrame, painting = false;
|
||||
const pending = new Map();
|
||||
const commands = [];
|
||||
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
|
||||
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
||||
child.send({ id, command, args });
|
||||
});
|
||||
async function paint() {
|
||||
if (painting || !page || !pendingFrame) return;
|
||||
painting = true;
|
||||
const frame = pendingFrame; pendingFrame = undefined;
|
||||
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
|
||||
painting = false;
|
||||
if (pendingFrame) void paint();
|
||||
}
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
child.on('error', reject);
|
||||
child.on('message', message => {
|
||||
if (message.ready) resolve();
|
||||
if (message.id) {
|
||||
const callback = pending.get(message.id); pending.delete(message.id);
|
||||
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
|
||||
}
|
||||
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
|
||||
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
|
||||
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 browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const errors = [];
|
||||
try {
|
||||
await ready;
|
||||
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map(); let next = 0;
|
||||
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
|
||||
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
|
||||
if (command === 'browser_connect') return 'test-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
|
||||
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 });
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
|
||||
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
||||
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);
|
||||
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 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 mkdir('.audit/browser-fields', { recursive: 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: `.audit/browser-fields/caret-${process.env.BROWSER_TEST_SCALE || 1}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'), Number(process.env.BROWSER_TEST_SCALE || 1), 'Navigation preserves the host pixel ratio');
|
||||
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
|
||||
assert.equal(await evaluate('document.hasFocus()'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
|
||||
} finally {
|
||||
await browser.close();
|
||||
await rpc('shutdown').catch(() => {}); child.kill();
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,181 +1,194 @@
|
||||
// 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 { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
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';
|
||||
const runtime = path.resolve('browser-runtime');
|
||||
const require = createRequire(path.join(runtime, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const electron = require('electron');
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
|
||||
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
|
||||
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
|
||||
});
|
||||
let sequence = 0, page, pendingFrame, painting = false;
|
||||
const pending = new Map();
|
||||
const commands = [];
|
||||
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
|
||||
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
||||
child.send({ id, command, args });
|
||||
});
|
||||
async function paint() {
|
||||
if (painting || !page || !pendingFrame) return;
|
||||
painting = true;
|
||||
const frame = pendingFrame; pendingFrame = undefined;
|
||||
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
|
||||
painting = false;
|
||||
if (pendingFrame) void paint();
|
||||
}
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
child.on('error', reject);
|
||||
child.on('message', message => {
|
||||
if (message.ready) resolve();
|
||||
if (message.id) {
|
||||
const callback = pending.get(message.id); pending.delete(message.id);
|
||||
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
|
||||
}
|
||||
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
|
||||
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
|
||||
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 browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const errors = [];
|
||||
try {
|
||||
await ready;
|
||||
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map(); let next = 0;
|
||||
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
|
||||
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
|
||||
if (command === 'browser_connect') return 'test-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
|
||||
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 });
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
|
||||
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
|
||||
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
||||
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
|
||||
const initialBox = await surface.boundingBox();
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
||||
await page.keyboard.type('Hello World!');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!');
|
||||
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
|
||||
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!Hello World!');
|
||||
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
|
||||
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
|
||||
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
|
||||
});
|
||||
await page.waitForTimeout(100);
|
||||
assert.ok((await evaluate('document.querySelector("#typing").value')).endsWith('日本語'));
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
|
||||
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
|
||||
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart'), 27);
|
||||
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
|
||||
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
||||
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'https://example.com/');
|
||||
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
|
||||
await 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 beforeWheels = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
|
||||
await surface.evaluate(node => {
|
||||
const bounds = node.getBoundingClientRect();
|
||||
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
|
||||
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
|
||||
}));
|
||||
});
|
||||
await page.waitForTimeout(200);
|
||||
const wheelBurstCalls = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length - beforeWheels;
|
||||
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
|
||||
await evaluate('window.testAnimate=false;true;');
|
||||
await evaluate(`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' });
|
||||
await page.mouse.move(x + 90, y + 120);
|
||||
await page.waitForTimeout(1500);
|
||||
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
|
||||
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
|
||||
await page.keyboard.press('Escape');
|
||||
await page.waitForTimeout(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 beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
|
||||
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
|
||||
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
|
||||
await page.waitForTimeout(100);
|
||||
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
|
||||
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
|
||||
await mkdir('output', { recursive: true });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
|
||||
await page.mouse.click(x, y, { button: 'middle' });
|
||||
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
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 page.setViewportSize({ width: 420, height: 650 });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
|
||||
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
|
||||
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
|
||||
} finally {
|
||||
await browser.close();
|
||||
await rpc('shutdown').catch(() => {}); child.kill();
|
||||
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/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/');
|
||||
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' });
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,44 +1,36 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
// Browser settings choice menus: keyboard selection and dismissal, saving, long profile lists, both themes, narrow layout, and cleanup.
|
||||
import assert from 'node:assert/strict';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const snapshot = {
|
||||
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
|
||||
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
|
||||
};
|
||||
window.browserMenuTest = { snapshot, calls: [] };
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'menu-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
|
||||
const details = args.args || {};
|
||||
window.browserMenuTest.calls.push({ command: args.command, ...details });
|
||||
if (args.command === 'webData') return { profileId: details.profileId, cookies: [], history: [] };
|
||||
if (args.command === 'settings') Object.assign(snapshot.settings, details);
|
||||
return structuredClone(snapshot);
|
||||
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);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const menu = name => page.getByRole('menu', { name, exact: true });
|
||||
const trigger = name => page.getByRole('button', { name, exact: true });
|
||||
try {
|
||||
await mkdir('output/todo-menus', { recursive: true });
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
});
|
||||
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']) {
|
||||
@@ -49,7 +41,7 @@ try {
|
||||
await engines.waitFor();
|
||||
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
|
||||
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: `output/todo-menus/search-${mode}.png` });
|
||||
await shot(`search-${mode}.png`);
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.press('Space');
|
||||
assert.equal(await trigger('Search engine').innerText(), 'Bing');
|
||||
@@ -60,11 +52,11 @@ try {
|
||||
await trigger('Profile').focus();
|
||||
await page.keyboard.press('Space');
|
||||
await menu('Profile').waitFor();
|
||||
await page.screenshot({ path: `output/todo-menus/profile-${mode}.png` });
|
||||
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.browserMenuTest.calls.some(call => call.command === 'webData' && call.profileId === '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');
|
||||
@@ -72,24 +64,24 @@ try {
|
||||
await trigger('Search engine').click();
|
||||
const bounds = await engines.boundingBox();
|
||||
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
|
||||
await page.screenshot({ path: `output/todo-menus/narrow-${mode}.png` });
|
||||
await 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();
|
||||
assert.equal(await page.evaluate(() => window.browserMenuTest.calls.filter(call => call.command === 'settings').length), 0, 'A choice does not submit the form');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.requests.filter(request => request.command === 'settings').length), 0, 'A choice does not submit the form');
|
||||
await trigger('Save browser settings').click();
|
||||
await page.waitForFunction(() => window.browserMenuTest.snapshot.settings.search === 'google');
|
||||
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.browserMenuTest.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
|
||||
await page.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 page.screenshot({ path: 'output/todo-menus/profile-long-narrow.png' });
|
||||
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();
|
||||
@@ -103,6 +95,5 @@ try {
|
||||
await trigger('Search engine').click();
|
||||
await trigger('General').click();
|
||||
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
|
||||
} finally { await browser.close(); }
|
||||
}, { viewport: { width: 1100, height: 850 }, timeout: 30000 });
|
||||
|
||||
@@ -1,218 +1,205 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
// Browser web data settings: cookie and history lists, filters, removal, profile isolation, stale-response guards, and narrow layouts.
|
||||
import assert from 'node:assert/strict';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const snapshot = {
|
||||
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
|
||||
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
|
||||
bookmarks: [],
|
||||
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
|
||||
};
|
||||
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
|
||||
const data = {
|
||||
user: {
|
||||
profileId: 'user',
|
||||
cookies: [
|
||||
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
|
||||
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
|
||||
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
|
||||
],
|
||||
history: [
|
||||
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
|
||||
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
|
||||
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
|
||||
],
|
||||
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);
|
||||
},
|
||||
};
|
||||
},
|
||||
work: {
|
||||
profileId: 'work',
|
||||
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
|
||||
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
|
||||
},
|
||||
};
|
||||
const check = window.webDataTest = { data, snapshot, calls: [], hold: [], pending: [], failNext: {} };
|
||||
let sequence = 0;
|
||||
const callbacks = new Map();
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'web-data-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
|
||||
if (args.session !== 'web-data-session') throw Error('Missing browser session');
|
||||
const operation = args.command, details = args.args || {}, key = `${operation}:${details.profileId}`;
|
||||
check.calls.push({ operation, ...details });
|
||||
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
|
||||
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
|
||||
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
|
||||
if (operation === 'webData') return nextData;
|
||||
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
|
||||
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
|
||||
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
});
|
||||
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
|
||||
const profile = page.getByRole('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.webDataTest.hold.push(key); }, key); }
|
||||
async function pending(key) { await page.waitForFunction(key => window.webDataTest.pending.some(item => item.key === key), key); }
|
||||
async function release(key, error) {
|
||||
await page.evaluate(({ key, error }) => {
|
||||
const check = window.webDataTest;
|
||||
check.hold = check.hold.filter(item => item !== key);
|
||||
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
|
||||
if (!item) throw Error('No pending request for ' + key);
|
||||
if (error) item.reject(Error(error)); else item.resolve();
|
||||
}, { key, error });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
try {
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Browser', exact: true }).click();
|
||||
await personalCookie().waitFor();
|
||||
assert.equal(await section.locator('.entry').count(), 3);
|
||||
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
|
||||
await filter.fill('PERSONAL.EXAMPLE');
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await filter.fill('/settings');
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await filter.fill('no matches');
|
||||
await section.getByText('No matching cookies.', { exact: true }).waitFor();
|
||||
await filter.fill('session');
|
||||
await personalCookie().click();
|
||||
await settle();
|
||||
await section.getByText('No matching cookies.', { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
|
||||
await 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.webDataTest.data.work.history.length), 1);
|
||||
await filter.fill('another.example/document');
|
||||
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await 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();
|
||||
});
|
||||
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);
|
||||
// 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);
|
||||
// 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.webDataTest.calls.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.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
|
||||
// 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.webDataTest.failNext['webData:user'] = 'Cannot read personal data'; });
|
||||
await refresh.click();
|
||||
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
|
||||
assert.equal(await refresh.isEnabled(), true);
|
||||
await refresh.click();
|
||||
await settle();
|
||||
assert.equal(await section.getByRole('alert').count(), 0);
|
||||
await page.evaluate(() => { window.webDataTest.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
|
||||
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
|
||||
await unnamed.click();
|
||||
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
|
||||
assert.equal(await unnamed.isEnabled(), true);
|
||||
await unnamed.click();
|
||||
await settle();
|
||||
assert.equal(await unnamed.count(), 0);
|
||||
assert.equal(await section.getByRole('alert').count(), 0);
|
||||
assert.deepEqual(await page.evaluate(() => window.webDataTest.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.calls.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
|
||||
await 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 mkdir('.audit/cards-2026-10-08-next', { recursive: true });
|
||||
await page.setViewportSize({ width: 360, height: 800 });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
|
||||
for (const dataType of ['cookies', 'history']) {
|
||||
await selectKind(dataType);
|
||||
await section.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
|
||||
const overflow = await section.evaluate(node => {
|
||||
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
|
||||
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
|
||||
});
|
||||
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
|
||||
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
|
||||
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
|
||||
}));
|
||||
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
|
||||
await filter.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
|
||||
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
|
||||
await page.setViewportSize({ width: 360, height: 800 });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
|
||||
for (const dataType of ['cookies', 'history']) {
|
||||
await 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;
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
|
||||
} catch (error) {
|
||||
console.error(await page.locator('body').innerText());
|
||||
console.error('Page errors:', errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
}, { viewport: { width: 1100, height: 850 } });
|
||||
|
||||
Reference in New Issue
Block a user