- A middle-click on a link opens the link in a new tab. Scrolling starts at once, as before. The new engine command linkAt reads the link under the pointer in an isolated world. When it finds a web link, the tab stops the scroll and opens the link. - The image menu of a page starts with Open image in new tab. A new tab opens in front, like Open link in new tab. The engine smoke test checks linkAt, and the interaction test checks both actions with the real engine. Cards 333909d1 and f7ee842d.
260 lines
22 KiB
JavaScript
260 lines
22 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');
|
|
// Copy image keeps the bytes that the page loaded. The test server gives this GIF only one time.
|
|
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<img id="copy-image" src="${process.env.RS_TEST_URL}once.gif" style="position:absolute;left:400px;top:40px;width:80px;height:80px">');true;`);
|
|
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete'));
|
|
const menus = events.length;
|
|
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.slice(menus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
|
const imageMenu = events.findLast(event => event.event === 'context-menu');
|
|
const { copied } = await engine.command('contextAction', { tabId: first, token: imageMenu.token, action: 'copyImage' });
|
|
assert.deepEqual([copied.url, copied.mime, copied.size], [`${process.env.RS_TEST_URL}once.gif`, 'image/gif', 85]);
|
|
const part = await engine.command('copiedImage', { tabId: first, token: copied.token, offset: 0 });
|
|
const bytes = Buffer.from(part.data, 'base64');
|
|
assert.equal(bytes.subarray(0, 6).toString(), 'GIF89a');
|
|
assert.equal(bytes.length, 85);
|
|
assert.equal(part.next, null);
|
|
await assert.rejects(engine.command('copiedImage', { tabId: first, token: copied.token, offset: 85 }), /no longer available/);
|
|
await assert.rejects(engine.command('copiedImage', { tabId: 'other', token: copied.token, offset: 0 }), /no longer available/);
|
|
// A large image comes in parts that stay below the line limit of the host.
|
|
await wc.executeJavaScript(`document.querySelector("#copy-image").src = "${process.env.RS_TEST_URL}large.gif";true;`);
|
|
await until(async () => await wc.executeJavaScript('document.querySelector("#copy-image").complete && document.querySelector("#copy-image").naturalWidth === 1'));
|
|
const largeMenus = events.length;
|
|
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.slice(largeMenus).some(event => event.event === 'context-menu' && event.hasImageContents));
|
|
const large = (await engine.command('contextAction', { tabId: first, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
|
const parts = [];
|
|
for (let offset = 0; offset !== null;) {
|
|
const next = await engine.command('copiedImage', { tabId: first, token: large.token, offset });
|
|
assert.ok(next.data.length <= 4_000_000);
|
|
parts.push(Buffer.from(next.data, 'base64')); offset = next.next;
|
|
}
|
|
const whole = Buffer.concat(parts);
|
|
assert.ok(parts.length >= 3);
|
|
assert.equal(whole.length, large.size);
|
|
assert.equal(whole.subarray(0, 6).toString(), 'GIF89a');
|
|
assert.equal(whole.at(-1), 0x3b);
|
|
await wc.executeJavaScript('document.querySelector("#copy-image").remove();true;');
|
|
// A middle-click asks for the link under the pointer. Only web links count.
|
|
await wc.executeJavaScript(`document.body.insertAdjacentHTML('beforeend', '<a id="middle-link" href="${process.env.RS_TEST_URL}linked" style="position:absolute;left:600px;top:40px;width:120px;height:30px;display:block">Linked</a><a id="script-link" href="javascript:void(0)" style="position:absolute;left:600px;top:100px;width:120px;height:30px;display:block">Script</a>');true;`);
|
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 50 }), { url: `${process.env.RS_TEST_URL}linked` });
|
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 650, y: 110 }), { url: null });
|
|
assert.deepEqual(await engine.command('linkAt', { tabId: first, x: 900, y: 600 }), { url: null });
|
|
await assert.rejects(engine.command('linkAt', { tabId: first, x: -1, y: 50 }), /Invalid pointer position/);
|
|
await wc.executeJavaScript('document.querySelector("#middle-link").remove(); document.querySelector("#script-link").remove();true;');
|
|
// An image that opens as the page itself is the main resource of the tab.
|
|
const direct = (await engine.command('newTab', { url: `${process.env.RS_TEST_URL}direct.gif` })).tabId;
|
|
const directContents = engine.tabs.get(direct).view.webContents;
|
|
await until(async () => await directContents.executeJavaScript('document.images[0]?.complete === true').catch(() => false));
|
|
const box = await directContents.executeJavaScript('(({ x, y, width, height }) => ({ x: Math.floor(x + width / 2), y: Math.floor(y + height / 2) }))(document.images[0].getBoundingClientRect())');
|
|
const directMenus = events.length;
|
|
await engine.command('input', { tabId: direct, input: { type: 'mouseDown', ...box, button: 'right' } });
|
|
await engine.command('input', { tabId: direct, input: { type: 'mouseUp', ...box, button: 'right' } });
|
|
await until(() => events.slice(directMenus).some(event => event.event === 'context-menu' && event.tabId === direct && event.hasImageContents));
|
|
const directCopy = (await engine.command('contextAction', { tabId: direct, token: events.findLast(event => event.event === 'context-menu').token, action: 'copyImage' })).copied;
|
|
assert.deepEqual([directCopy.mime, directCopy.size], ['image/gif', large.size]);
|
|
await engine.command('closeTab', { tabId: direct });
|
|
passed.push('Copy image keeps the loaded GIF bytes without a second request, also for an image that opens as the page');
|
|
passed.push('A middle-click finds the web link under the pointer');
|
|
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);
|
|
}
|
|
});
|