import { nativeRequest } from './native-support.mjs'; import { chromium } from 'playwright'; import { spawn } from 'node:child_process'; import { cp, mkdir, writeFile } from 'node:fs/promises'; import { resolve, basename, dirname } from 'node:path'; import net from 'node:net'; import assert from 'node:assert/strict'; const host = resolve(process.env.RUNESTONE_ROOT || '..'); const portServer = net.createServer(); await new Promise(resolve => portServer.listen(0, '127.0.0.1', resolve)); const port = portServer.address().port; await new Promise(resolve => portServer.close(resolve)); const native = spawn(resolve(host, 'src-tauri/target/debug/runestone.exe'), [], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port}` }, }); let nativeOutput = ''; for (const stream of [native.stdout, native.stderr]) stream.on('data', chunk => nativeOutput = (nativeOutput + chunk).slice(-8000)); let browser, page; const passed = [], errors = []; const ipc = nativeRequest; const state = page => ipc(page, 'browser_request', { command: 'state', args: {} }); const menuItem = (page, name) => page.getByRole('menuitem', { name: name === 'Find…' ? 'Find… Ctrl+F' : name, exact: true }); const tabs = page => page.locator('.header').getByRole('tab'); async function action(page, tab, name) { await tab.click({ button: 'right' }); await menuItem(page, name).click(); } async function ready(page, count) { await page.waitForFunction(count => [...document.querySelectorAll('.browser[data-browser-state="ready"]')].filter(node => node.getBoundingClientRect().width > 0).length === count, count); } async function painted(page, count) { await page.waitForFunction(count => { const images = [...document.querySelectorAll('.surface img')].filter(img => img.getBoundingClientRect().width > 0); return images.length === count && images.every(img => { const bounds = img.getBoundingClientRect(); return img.naturalHeight > 0 && Math.abs(img.naturalWidth / img.naturalHeight - bounds.width / bounds.height) < 0.02; }); }, count); } async function dragToWindow(context, source, sourceTab, destination) { const targetSession = await context.newCDPSession(destination); const before = (await state(source)).tabs.map(tab => tab.id); await source.evaluate(() => { window.__tabDragData = undefined; window.addEventListener('dragstart', event => { window.__tabDragData = { items: [...event.dataTransfer.types].map(mimeType => ({ mimeType, data: event.dataTransfer.getData(mimeType) })), dragOperationsMask: 16, }; }, { once: true }); }); const bounds = await sourceTab.boundingBox(); await source.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); await source.mouse.down(); await source.mouse.move(bounds.x + bounds.width / 2 + 30, bounds.y + bounds.height / 2 + 12, { steps: 5 }); await source.waitForFunction(() => window.__tabDragData?.items.length); const transfer = await source.evaluate(() => window.__tabDragData); assert.ok(transfer.items.some(item => item.mimeType === 'application/x-runestone-tab' && item.data)); await source.mouse.up(); assert.deepEqual((await state(source)).tabs.map(tab => tab.id), before, 'A drag without a destination keeps the live tabs.'); const drop = await destination.locator('.header [role="tablist"]').boundingBox(); assert.ok(drop.width > 0 && drop.height > 0); for (const type of ['dragEnter', 'dragOver', 'drop']) { await targetSession.send('Input.dispatchDragEvent', { type, x: drop.x + 2, y: drop.y + drop.height / 2, data: transfer }); } await targetSession.detach(); } try { for (let attempt = 0; attempt < 60; attempt++) { if (native.exitCode !== null) throw new Error(`The test app exited (${native.exitCode}). ${nativeOutput}`); try { browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`); break; } catch { await new Promise(resolve => setTimeout(resolve, 500)); } } assert.ok(browser, `The isolated native app must start. ${nativeOutput}`); const context = browser.contexts()[0]; page = context.pages()[0] || await context.waitForEvent('page'); page.setDefaultTimeout(20000); page.on('pageerror', error => errors.push(error.message)); await page.waitForFunction(() => !!window.__TAURI_INTERNALS__?.invoke); let plugins = await ipc(page, 'plugins_snapshot'); const root = resolve(plugins.root); assert.equal(basename(dirname(root)), 'com.runestone.browser-test'); await page.evaluate(() => window.dispatchEvent(new Event('focus'))); await page.getByRole('button', { name: 'Open browser', exact: true }).waitFor(); const initial = await state(page); await ipc(page, 'browser_request', { command: 'settings', args: { ...initial.settings, homepage: '', linkDestination: 'internal' } }); await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); await tabs(page).filter({ hasText: 'New tab' }).waitFor(); await action(page, tabs(page).first(), 'Pin'); await page.getByRole('button', { name: 'Open browser', exact: true }).click(); await ready(page, 1); assert.equal(await tabs(page).count(), 1); assert.equal(await page.locator('.header .pin').count(), 1); await action(page, tabs(page).first(), 'Unpin'); passed.push('Open browser replaces the empty tab and keeps its pin'); await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); const emptyPath = await tabs(page).last().getAttribute('data-path'); await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click(); const untouchedPath = await tabs(page).last().getAttribute('data-path'); await page.locator(`.header [role="tab"][data-path="${emptyPath}"]`).click(); await page.getByRole('button', { name: 'Open browser', exact: true }).click(); await ready(page, 1); assert.equal(await tabs(page).count(), 3); assert.equal(await tabs(page).last().getAttribute('data-path'), untouchedPath); assert.match(await tabs(page).nth(1).getAttribute('data-path'), /^plugin:/); await action(page, tabs(page).nth(1), 'Close'); await action(page, tabs(page).last(), 'Close'); assert.equal(await tabs(page).count(), 1); passed.push('splash replacement keeps the tab position and other empty tabs'); await tabs(page).first().click({ button: 'right' }); assert.equal(await menuItem(page, 'Open in default browser').isDisabled(), true); assert.equal(await menuItem(page, 'Bookmark').isDisabled(), true); await page.keyboard.press('Escape'); const address = page.getByRole('textbox', { name: 'Address or search', exact: true }); await address.fill('https://example.com/'); await address.press('Enter'); await page.waitForFunction(() => document.querySelector('.header [role="tab"]')?.textContent.includes('Example')); const firstId = (await state(page)).tabs[0].id; for (const theme of ['dark', 'light']) { await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme); await tabs(page).first().click({ button: 'right' }); for (const label of ['Close', 'Pin', 'Move to new window', 'Split right', 'Split down', 'Find…', 'Open in default browser', 'Bookmark']) { assert.equal(await menuItem(page, label).isEnabled(), true, label); assert.equal(await menuItem(page, label).locator('svg').count(), 1, label); } await mkdir('output', { recursive: true }); await page.screenshot({ path: `output/browser-tab-menu-${theme}.png` }); await page.keyboard.press('Escape'); } passed.push('all eight tab actions use the shared menu in both themes'); await action(page, tabs(page).first(), 'Pin'); await page.getByRole('button', { name: 'New browser tab', exact: true }).click(); await ready(page, 1); await page.getByRole('button', { name: 'New browser tab', exact: true }).click(); await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 3); await ready(page, 1); await action(page, tabs(page).last(), 'Close others'); await page.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2); assert.equal(await tabs(page).count(), 2); await action(page, tabs(page).first(), 'Bookmark'); assert.ok((await state(page)).bookmarks.some(bookmark => bookmark.url === 'https://example.com/')); await action(page, tabs(page).last(), 'Close'); await ready(page, 1); passed.push('pins survive bulk close and inactive-tab actions target the clicked page'); await page.locator('.surface:visible').focus(); await page.keyboard.press('Control+f'); const find = page.getByRole('textbox', { name: 'Find in page', exact: true }); await find.fill('Learn more'); await page.getByText('1 of 1', { exact: true }).waitFor(); await find.press('Enter'); await find.press('Shift+Enter'); await find.fill('no such phrase exists'); await page.getByText('No matches', { exact: true }).waitFor(); await find.press('Escape'); await find.waitFor({ state: 'detached' }); await address.focus(); await page.keyboard.press('Control+f'); await find.waitFor(); await page.getByText('No matches', { exact: true }).waitFor(); await find.press('Escape'); await action(page, tabs(page).first(), 'Find…'); await find.fill('Learn more'); await page.getByText('1 of 1', { exact: true }).waitFor(); await find.press('Escape'); passed.push('Ctrl+F works from the page and address bar, with counts, navigation, and Escape'); await action(page, tabs(page).first(), 'Split right'); await ready(page, 2); assert.equal((await state(page)).tabs[0].id, firstId); const surfaces = page.locator('.surface:visible'); const a = await surfaces.nth(0).boundingBox(), b = await surfaces.nth(1).boundingBox(); assert.ok(b.x > a.x + a.width - 5); await action(page, tabs(page).last(), 'Split down'); await ready(page, 3); const c = await surfaces.nth(2).boundingBox(), upper = await surfaces.nth(1).boundingBox(); assert.ok(c.y > upper.y + upper.height - 5); assert.equal((await state(page)).tabs.length, 3); await painted(page, 3); await page.screenshot({ path: 'output/browser-split-panes.png' }); await action(page, tabs(page).last(), 'Close'); await ready(page, 2); passed.push('nested splits preserve the source tab and closing a pane fills its space'); const movingId = (await state(page)).tabs.find(tab => tab.id !== firstId).id; await action(page, tabs(page).last(), 'Pin'); const opened = context.waitForEvent('page'); await action(page, tabs(page).last(), 'Move to new window'); const target = await opened; target.setDefaultTimeout(20000); target.on('pageerror', error => errors.push(error.message)); await ready(target, 1); await target.evaluate(async () => { window.__browserStates = []; const handler = window.__TAURI_INTERNALS__.transformCallback(event => { window.__browserStates.push({ revision: event.payload.state?.revision, tabs: event.payload.state?.tabs }); window.__browserStates = window.__browserStates.slice(-5); }); await window.__TAURI_INTERNALS__.invoke('plugin:event|listen', { event: 'browser-state', target: { kind: 'WebviewWindow', label: window.__TAURI_INTERNALS__.metadata.currentWindow.label }, handler }); }); await ready(page, 1); assert.equal(await target.getByRole('application', { name: 'RuneStone browser', exact: true }).count(), 1); assert.equal(await target.getByRole('application', { name: 'RuneStone workbench', exact: true }).count(), 0); assert.equal(await target.getByRole('button', { name: 'Files', exact: true }).count(), 0); assert.equal(await target.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).count(), 0); assert.equal((await state(target)).tabs[0].id, movingId); assert.equal((await state(page)).tabs.length, 1); assert.equal((await state(target)).tabs[0].url, 'https://example.com/'); assert.equal(await target.locator('.header .pin').count(), 1); await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: movingId } }), /another window/); await target.locator('.surface:visible').focus(); await target.keyboard.press('Control+f'); await target.getByRole('textbox', { name: 'Find in page', exact: true }).fill('Learn more'); await target.getByText('1 of 1', { exact: true }).waitFor(); await target.screenshot({ path: 'output/browser-moved-window.png' }); assert.equal(await tabs(target).first().getAttribute('draggable'), 'true'); const beforeDrop = (await state(target)).tabs[0]; await assert.rejects(ipc(page, 'browser_request', { command: 'adoptTab', args: { tabId: movingId, transferToken: 'invalid-token' } }), /valid transfer/); const updates = await target.evaluate(() => window.__browserStates); assert.ok(updates.length > 0 && updates.every(update => update.tabs.every(tab => tab.id === movingId))); const closed = target.waitForEvent('close'); await dragToWindow(context, target, tabs(target).first(), page); await closed; await ready(page, 1); await page.waitForFunction(() => document.querySelectorAll('.browser[data-browser-state="ready"]').length === 2); const returned = (await state(page)).tabs.find(tab => tab.id === movingId); assert.equal(returned.url, beforeDrop.url); assert.equal(returned.profileId, beforeDrop.profileId); assert.equal(returned.canBack, beforeDrop.canBack); assert.equal(returned.canForward, beforeDrop.canForward); assert.notEqual(returned.transferToken, beforeDrop.transferToken); assert.equal(await page.locator('.header .tab').first().locator('.pin').count(), 1); assert.equal(await page.locator('.browser:visible').getAttribute('data-browser-tab'), movingId); assert.equal((await state(page)).tabs.length, 2); await assert.rejects(ipc(page, 'browser_request', { command: 'closeTab', args: { tabId: 'missing-tab' } }), /Unknown browser tab/); await painted(page, 1); await page.screenshot({ path: 'output/browser-returned-tab.png' }); passed.push('the browser-only window returns its live tab by drag and closes when empty'); await action(page, tabs(page).first(), 'Close'); assert.equal((await state(page)).tabs[0].id, firstId); const another = context.waitForEvent('page'); await action(page, tabs(page).first(), 'Move to new window'); const secondWindow = await another; secondWindow.setDefaultTimeout(20000); secondWindow.on('pageerror', error => errors.push(error.message)); await ready(secondWindow, 1); assert.equal(await tabs(page).count(), 0); await secondWindow.locator('.surface:visible').focus(); await secondWindow.keyboard.press('Control+t'); await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 2); await ready(secondWindow, 1); await dragToWindow(context, secondWindow, tabs(secondWindow).first(), page); await ready(page, 1); await secondWindow.waitForFunction(() => document.querySelectorAll('.header [role="tab"]').length === 1); assert.equal((await state(page)).tabs[0].id, firstId); assert.equal((await state(secondWindow)).tabs.length, 1); const secondClosed = secondWindow.waitForEvent('close'); await secondWindow.keyboard.press('Control+w'); await secondClosed; assert.equal((await state(page)).tabs[0].id, firstId); passed.push('an empty RuneStone tab bar accepts a tab, and the source window keeps its remaining tab'); await action(page, tabs(page).first(), 'Close'); await page.waitForFunction(() => !document.querySelector('.browser')); assert.equal((await state(page)).tabs.length, 0); assert.deepEqual(errors, []); await writeFile('output/browser-tab-actions.json', JSON.stringify({ passed, errors }, null, 2)); for (const label of passed) console.log(`PASS ${label}`); } catch (error) { for (const current of browser?.contexts()[0]?.pages() || []) { if (current !== page) { console.error(await current.locator('body').innerText().catch(() => '')); console.error(JSON.stringify((await state(current).catch(() => ({ tabs: [] }))).tabs)); console.error(JSON.stringify(await current.evaluate(() => window.__browserStates).catch(() => []))); await current.screenshot({ path: 'output/browser-window-failure.png' }).catch(() => {}); } } if (page) { await mkdir('output', { recursive: true }); await page.screenshot({ path: 'output/browser-tab-actions-failure.png' }).catch(() => {}); console.error(await page.locator('body').innerText().catch(() => '')); } throw error; } finally { if (page) await ipc(page, 'browser_stop').catch(() => {}); if (browser) await browser.close().catch(() => {}); native.kill(); }