import { createRequire } from 'node:module'; import { spawn } from 'node:child_process'; import { mkdtemp, mkdir, 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('../RuneStone_Browser'); 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(() => {}); }); }); 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 } }); 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) }; }); 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=''; 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}`); await evaluate('window.testAnimate=false;true;'); await evaluate(`document.body.innerHTML='

Native scroll fixture

'; 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(150); 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'); } 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.json', JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, passed: ['Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer bursts coalesce', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2)); console.log('PASS browser UI with real Electron pages, autoscroll cleanup, pointer coalescing and center new-tab action'); } finally { await browser.close(); await rpc('shutdown').catch(() => {}); child.kill(); }