Files
RuneStone/scripts/browserWebData.smoke.mjs
T

214 lines
13 KiB
JavaScript

// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
import { createRequire } from 'node:module';
import { mkdir } from 'node:fs/promises';
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 },
],
},
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('combobox', { name: 'Profile', exact: true });
const kind = section.getByRole('combobox', { name: 'Web data type', exact: true });
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
const 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 kind.selectOption('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 profile.selectOption('work');
await settle();
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
await section.getByText('Work guide', { exact: true }).waitFor();
await kind.selectOption('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 profile.selectOption('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 profile.selectOption('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 profile.selectOption('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.inputValue(), 'user');
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);
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 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 kind.selectOption(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');
}
}
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(); }