Files
RuneStone/browser-runtime/test/engine-smoke.mjs
T

202 lines
16 KiB
JavaScript

import { app, BrowserWindow } from 'electron';
import assert from 'node:assert/strict';
import { mkdir, writeFile, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pathToFileURL } from 'node:url';
const { createEngine } = await import(process.env.RUNESTONE_TEST_PACKAGE ? pathToFileURL(path.join(process.env.RUNESTONE_TEST_PACKAGE, 'src/engine.mjs')).href : '../src/engine.mjs');
app.enableSandbox();
app.on('window-all-closed', () => {});
app.commandLine.appendSwitch('disable-quic');
app.commandLine.appendSwitch('host-resolver-rules', 'MAP * ~NOTFOUND, EXCLUDE 127.0.0.1');
app.setPath('userData', process.env.RS_TEST_ROOT);
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const until = async predicate => { for (let attempt = 0; attempt < 100; attempt++) { if (await predicate()) return; await wait(50); } throw new Error('Browser condition timed out.'); };
app.whenReady().then(async () => {
let engine, exitCode = 0;
const passed = [];
try {
const frames = [], external = [], events = [];
engine = await createEngine({ directory: process.env.RS_TEST_ROOT, allowedTestHosts: new Set(['127.0.0.1']), openExternal: async url => { external.push(url); }, emit: value => { if (value.event === 'frame') { frames.push(value); void engine?.command('frameAck', { tabId: value.tabId, frameId: value.frameId }); } else events.push(value); } });
if (process.env.RS_TEST_PHASE === 'restore') {
const plan = JSON.parse(process.env.RS_TEST_PLAN);
await engine.command('commitDuplicate', plan);
const made = await engine.command('newTab', { profileId: plan.id });
await engine.command('navigate', { tabId: made.tabId, input: process.env.RS_TEST_URL });
const wc = engine.tabs.get(made.tabId).view.webContents;
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.match(await wc.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(await wc.executeJavaScript("localStorage.getItem('identity')"), 'source');
await wc.executeJavaScript("localStorage.setItem('identity', 'copy'); document.cookie='login=copy; path=/'; true");
const original = engine.tabs.get(plan.tabs[0].id).view.webContents;
await until(async () => await original.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await original.executeJavaScript("localStorage.getItem('identity')"), 'source');
assert.match(await original.executeJavaScript('document.cookie'), /login=kept/);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === plan.id).length, 1);
passed.push('duplicate preserves cookies, local storage and bookmarks without sharing later changes');
} else {
assert.deepEqual(engine.snapshot().profiles, [{ id: 'user', name: 'User' }]);
const first = (await engine.command('newTab')).tabId;
const wc = engine.tabs.get(first).view.webContents;
await until(() => wc.getURL() === 'about:blank');
assert.equal(wc.getURL(), 'about:blank');
await assert.rejects(engine.command('openExternal', { tabId: first }));
assert.deepEqual(external, []);
assert.ok(BrowserWindow.getAllWindows().every(win => !win.isVisible()));
passed.push('one default User profile and no standalone browser window');
assert.equal(engine.snapshot().tabs.find(tab => tab.id === first).favicon, null);
const iconTab = (await engine.command('newTab', { url: process.env.RS_TEST_URL + 'with-icon' })).tabId;
const iconContents = engine.tabs.get(iconTab).view.webContents;
const favicon = () => engine.snapshot().tabs.find(tab => tab.id === iconTab)?.favicon;
await until(() => favicon()?.startsWith('data:image/svg+xml;base64,'));
const originalIcon = favicon();
await iconContents.executeJavaScript(`document.querySelector('link').href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a6XcAAAAASUVORK5CYII='; true`);
await until(() => favicon()?.startsWith('data:image/png;base64,'));
assert.notEqual(favicon(), originalIcon);
await engine.command('navigate', { tabId: iconTab, input: process.env.RS_TEST_URL + 'no-icon' });
await until(() => iconContents.getURL().endsWith('/no-icon') && !iconContents.isLoading());
assert.equal(favicon(), null);
await engine.command('back', { tabId: iconTab });
await until(() => favicon() === originalIcon);
await engine.command('closeTab', { tabId: iconTab });
passed.push('site icons load, update dynamically, clear on navigation, and return with history');
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL + 'slow' });
const slow = await Promise.race([
engine.command('newTab'),
wait(2000).then(() => { throw new Error('Slow homepage blocked the new-tab response.'); }),
]);
const slowContents = engine.tabs.get(slow.tabId).view.webContents;
await until(() => slowContents.isLoading());
assert.ok((await engine.command('state')).tabs.some(tab => tab.id === slow.tabId));
await engine.command('stop', { tabId: slow.tabId });
await engine.command('closeTab', { tabId: slow.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: process.env.RS_TEST_URL });
const home = await engine.command('newTab');
const homeContents = engine.tabs.get(home.tabId).view.webContents;
await until(() => homeContents.getURL() === process.env.RS_TEST_URL);
await engine.command('closeTab', { tabId: home.tabId });
const explicit = await engine.command('newTab', { url: 'about:blank' });
await until(() => engine.tabs.get(explicit.tabId).view.webContents.getURL() === 'about:blank');
await engine.command('closeTab', { tabId: explicit.tabId });
await engine.command('settings', { ...engine.snapshot().settings, homepage: '' });
passed.push('homepage loads in new tabs, explicit links override it, and slow pages do not block commands');
await engine.command('settings', { ...engine.snapshot().settings, personalRules: '/blocked-ad.js\n127.0.0.1##.advertisement' });
await engine.command('navigate', { tabId: first, input: process.env.RS_TEST_URL });
await until(async () => await wc.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.deepEqual(await wc.executeJavaScript('[typeof require,typeof process,typeof browserHost,typeof window.__TAURI_INTERNALS__]'), ['undefined','undefined','undefined','undefined']);
passed.push('remote content has no Node, native bridge or terminal access');
await until(() => frames.some(frame => frame.tabId === first));
assert.ok(frames.some(frame => frame.width > 100 && frame.height > 100 && frame.data.length > 100 && ['image/png', 'image/jpeg'].includes(frame.mime)));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 50, y: 35, button: 'left' } });
await engine.command('input', { tabId: first, input: { type: 'char', keyCode: 'x' } });
await until(async () => await wc.executeJavaScript("document.querySelector('input').value") === 'x');
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('focus', { tabId: first, focused: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
wc.debugger.detach();
await engine.command('focus', { tabId: first, focused: true });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), true);
await engine.command('visible', { tabId: first, visible: false });
assert.equal(await wc.executeJavaScript('document.hasFocus()'), false);
await engine.command('visible', { tabId: first, visible: true });
await engine.command('focus', { tabId: first, focused: true });
await assert.rejects(engine.command('focus', { tabId: first, focused: 'true' }), /Invalid browser focus/);
passed.push('offscreen focus supports the caret, blur, hidden tabs, and debugger reattachment');
passed.push('offscreen frames and forwarded pointer and keyboard input work');
await engine.command('insertText', { tabId: first, text: '日本語 🙂' });
await until(async () => (await wc.executeJavaScript("document.querySelector('input').value")).endsWith('日本語 🙂'));
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="save-image" src="${process.env.RS_TEST_URL}picture.png" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
await until(async () => await wc.executeJavaScript('document.querySelector("#save-image").complete'));
await engine.command('input', { tabId: first, input: { type: 'mouseDown', x: 440, y: 80, button: 'right' } });
await engine.command('input', { tabId: first, input: { type: 'mouseUp', x: 440, y: 80, button: 'right' } });
await until(() => events.some(event => event.event === 'context-menu' && event.hasImageContents));
const context = events.findLast(event => event.event === 'context-menu');
const downloadPath = path.join(process.env.RS_TEST_ROOT, 'saved-image.png');
const saved = new Promise((resolve, reject) => wc.session.once('will-download', (_event, download) => {
download.setSavePath(downloadPath);
download.once('done', (_event, state) => state === 'completed' ? resolve() : reject(new Error(`Image download: ${state}`)));
}));
await engine.command('contextAction', { tabId: first, token: context.token, action: 'saveImage' });
await saved;
assert.equal((await readFile(downloadPath)).subarray(1, 4).toString(), 'PNG');
await assert.rejects(engine.command('contextAction', { tabId: first, token: 'expired', action: 'saveImage' }), /no longer available/);
await wc.executeJavaScript('document.querySelector("#save-image").remove();true;');
passed.push('Unicode text, native image context menus, saved image bytes and stale menu protection work');
await until(async () => await wc.executeJavaScript("getComputedStyle(document.querySelector('.advertisement')).display") === 'none');
assert.equal(await wc.executeJavaScript('typeof window.adExecuted'), 'undefined');
passed.push('network and cosmetic ad blocking remain active');
const finding = () => engine.snapshot().tabs.find(tab => tab.id === first).find;
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await until(() => finding()?.matches === 3 && !finding()?.pending);
assert.equal(finding().activeMatch, 1);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true });
await until(() => finding()?.activeMatch === 2 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'Runestone needle', next: true, forward: false });
await until(() => finding()?.activeMatch === 1 && !finding()?.pending);
await engine.command('find', { tabId: first, text: 'missing phrase' });
await until(() => finding()?.text === 'missing phrase' && !finding()?.pending);
assert.equal(finding().matches, 0);
await engine.command('find', { tabId: first, text: 'Runestone needle' });
await engine.command('stopFind', { tabId: first });
await wait(100);
assert.equal(finding(), null);
await engine.command('find', { tabId: first, text: '' });
assert.equal(finding(), null);
await assert.rejects(engine.command('find', { tabId: first, text: 'x'.repeat(1001) }));
await engine.command('openExternal', { tabId: first });
assert.deepEqual(external, [process.env.RS_TEST_URL]);
passed.push('Find counts matches, moves both ways, clears results, and external opening uses the current web URL');
await wc.executeJavaScript("document.cookie='login=kept; path=/'; localStorage.setItem('identity','source'); true");
await engine.command('bookmark', { tabId: first });
const created = await engine.command('createProfile', { name: 'Research' });
const second = (await engine.command('newTab', { profileId: created.profiles.at(-1).id })).tabId;
await engine.command('navigate', { tabId: second, input: process.env.RS_TEST_URL });
const other = engine.tabs.get(second).view.webContents;
await until(async () => await other.executeJavaScript('document.title').catch(() => '') === 'Browser fixture');
assert.equal(await other.executeJavaScript('document.cookie'), '');
assert.equal(await other.executeJavaScript("localStorage.getItem('identity')"), null);
const observation = await engine.command('agentSnapshot', { tabId: first });
assert.equal(observation.untrusted, true); assert.equal(observation.profileId, 'user');
passed.push('blank profiles are isolated and agent observation has no special profile name');
await wc.executeJavaScript("document.cookie='selected=root; path=/'; document.cookie='selected=nested; path=/nested'; document.cookie='keep=unchanged; path=/'; true");
await other.executeJavaScript("document.cookie='selected=other-profile; path=/'; true");
let webData = await engine.command('webData', { profileId: 'user' });
assert.ok(webData.cookies.every(cookie => !Object.hasOwn(cookie, 'value')));
const nestedCookie = webData.cookies.find(cookie => cookie.name === 'selected' && cookie.path === '/nested');
assert.ok(nestedCookie);
const openTabs = engine.snapshot().tabs.map(tab => tab.id);
await engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id });
webData = await engine.command('webData', { profileId: 'user' });
assert.ok(!webData.cookies.some(cookie => cookie.id === nestedCookie.id));
assert.ok(webData.cookies.some(cookie => cookie.name === 'selected' && cookie.path === '/'));
assert.ok(webData.cookies.some(cookie => cookie.name === 'keep'));
assert.match(await other.executeJavaScript('document.cookie'), /selected=other-profile/);
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
await assert.rejects(engine.command('removeCookie', { profileId: 'user', id: nestedCookie.id }), /no longer exists/);
await assert.rejects(engine.command('webData', { profileId: 'missing' }), /Unknown profile/);
const visit = webData.history[0];
assert.ok(visit.id);
const otherProfile = created.profiles.at(-1).id;
await assert.rejects(engine.command('removeHistory', { profileId: otherProfile, id: visit.id }), /no longer exists/);
await engine.command('removeHistory', { profileId: 'user', id: visit.id });
const afterRemoval = await engine.command('webData', { profileId: 'user' });
assert.equal(afterRemoval.history.length, webData.history.length - 1);
assert.ok(!afterRemoval.history.some(item => item.id === visit.id));
assert.deepEqual(engine.snapshot().tabs.map(tab => tab.id), openTabs);
assert.equal(engine.snapshot().bookmarks.filter(item => item.profileId === 'user').length, 1);
passed.push('individual cookie and history removal preserves other paths, entries, profiles, bookmarks and tabs');
const plan = await engine.command('prepareDuplicate', { profileId: 'user', name: 'User copy' });
await writeFile(process.env.RS_TEST_ROOT + '/clone-plan.json', JSON.stringify(plan));
}
} catch (error) { console.error(error); exitCode = 1; }
finally {
if (engine) await engine.shutdown();
for (const name of passed) console.log(`PASS ${name}`);
await mkdir('output', { recursive: true });
await writeFile(`output/engine-${process.env.RS_TEST_PHASE || 'initial'}.json`, JSON.stringify({ exitCode, passed, platform: process.platform }, null, 2));
app.exit(exitCode);
}
});