diff --git a/tests/e2e/android.mjs b/tests/e2e/android.mjs index 0f3e75d..73fe599 100644 --- a/tests/e2e/android.mjs +++ b/tests/e2e/android.mjs @@ -184,7 +184,13 @@ async function rediscovery() { return false } catch { v = await attach().catch(() => v); return false } }, ms, 500) - if (!ok) shot(`android-rediscovery-timeout-${++shots}`) + if (!ok) { + shot(`android-rediscovery-timeout-${++shots}`) + // what the page really holds (a blank screen: render crash? gate stuck?) and its console + const dom = await v.evaluate("location.pathname + ' | root: ' + (document.getElementById('root')?.innerHTML || '').slice(0, 300)").catch(e => String(e)) + console.log(` timeout ${shots}: ${dom} + console: ${v.logs.slice(-8).join(' || ').slice(0, 1500)}`) + } return ok } r.check('setup: paired and logged in', !!(await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/tables', 45_000))) @@ -365,7 +371,11 @@ server { listen 443 ssl; ssl_certificate /t/cert.pem; ssl_certificate_key /t/key let s = await waitFor(async () => { const st = await state(); return st.active === 'test-site-2' && st.current === m2.version && st }, 90_000, 2000) r.check('bundles: pairing venue 2 → venue 2 bundle', !!s) const switchTo = async (label, site, want) => { - const vv = await attach(); await goTo(vv, '/venues'); await sleep(1200); await tap(vv, 'button', label); vv.close() + // the app may still be reloading into the last venue's bundle: open /venues until the list shows + const vv = await attach() + const listed = `[...document.querySelectorAll('button')].some(e => e.textContent.includes(${JSON.stringify(label)}))` + await waitFor(async () => { if (await vv.evaluate(listed)) return true; await goTo(vv, '/venues'); return false }, 30_000, 1500) + await tap(vv, 'button', label); vv.close() return waitFor(async () => { const st = await state(); return st.active === site && st.current === want && st }, 90_000, 2000) } await switchTo(`${H}:18443`, 'test-site-1', manifest.version) diff --git a/tests/e2e/lib/android.mjs b/tests/e2e/lib/android.mjs index e101608..27accf5 100644 --- a/tests/e2e/lib/android.mjs +++ b/tests/e2e/lib/android.mjs @@ -4,7 +4,7 @@ import { execFileSync, spawn } from 'node:child_process' import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { connectWebView } from './cdp.mjs' +import { connectWebView, liveTarget } from './cdp.mjs' import { OUT, WAITER, sleep } from './env.mjs' export const APP_ID = 'gr.bonamin.xenia' @@ -15,18 +15,33 @@ export const ADB = exe('platform-tools/adb') export const adb = (...args) => execFileSync(ADB, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) -/** Make sure a device is attached; boot the test AVD headless if none is. */ +/** Make sure a device is attached; boot the test AVD headless if none is. + * An emulator that has been up for long gets slow first connections to the host (0.9 s + * instead of 15 ms, KI-015) and lingering WebView state, so one that has been running + * longer than EMULATOR_MAX_UPTIME_MIN (default 30, 0 = never) is rebooted first. */ export async function ensureDevice() { - if (/\tdevice$/m.test(adb('devices'))) return + if (/\tdevice$/m.test(adb('devices'))) { + const maxMin = Number(process.env.EMULATOR_MAX_UPTIME_MIN ?? 30) + const upMin = parseFloat(adb('shell', 'cat', '/proc/uptime')) / 60 + if (!(maxMin > 0 && upMin > maxMin)) return + console.log(` rebooting the emulator (up ${Math.round(upMin)} min)…`) + adb('reboot') + await sleep(8000) + return waitForBoot('the emulator') + } const avd = process.env.AVD || 'Xenia_Test_Phone' console.log(` booting emulator ${avd} (headless)…`) spawn(exe('emulator/emulator'), ['-avd', avd, '-no-window', '-no-audio', '-no-boot-anim', '-gpu', 'swiftshader_indirect', '-no-snapshot'], { detached: true, stdio: 'ignore' }).unref() + return waitForBoot(`emulator ${avd}`, ' — create it in Android Studio or set AVD=') +} + +async function waitForBoot(what, hint = '') { for (let i = 0; i < 90; i++) { - try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') return } catch {} + try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') { await sleep(3000); return } } catch {} await sleep(3000) } - throw new Error(`emulator ${avd} did not boot — create it in Android Studio or set AVD=`) + throw new Error(`${what} did not boot${hint}`) } /** Newest debug APK from `npm run apk:debug` (WebView debugging needs a debug build). */ @@ -49,19 +64,66 @@ export const clearData = () => adb('shell', 'pm', 'clear', APP_ID) export const focusedWindow = () => adb('shell', 'dumpsys', 'window').match(/mCurrentFocus=[^}]*\}/)?.[0] || '' export const shot = name => writeFileSync(path.join(OUT, `${name}.png`), execFileSync(ADB, ['exec-out', 'screencap', '-p'])) -/** Attach to the app's WebView over DevTools (the socket changes when the process restarts). */ -export async function attach() { +/** The running app process's DevTools socket. It is named after the pid, and an old + * process's socket can linger after a restart, so "the first one listed" is not enough. */ +function appSocket() { + try { + const out = adb('shell', `p=$(pidof ${APP_ID}); [ -n "$p" ] && grep -ao "webview_devtools_remote_$p" /proc/net/unix | head -1`).trim() + return out || null + } catch { return null } +} + +let forwarded = null +async function connectLive() { for (let i = 0; i < 40; i++) { - const sock = adb('shell', 'cat', '/proc/net/unix').match(/webview_devtools_remote_\d+/)?.[0] + const sock = appSocket() if (sock) { - adb('forward', 'tcp:9333', `localabstract:${sock}`) - try { return await connectWebView() } catch {} + try { + if (forwarded !== sock) { adb('forward', 'tcp:9333', `localabstract:${sock}`); forwarded = sock } + const c = await connectWebView() + c.sock = sock + return c + } catch { forwarded = null } } await sleep(750) } throw new Error('could not attach to the app WebView (is this a debug build?)') } +/** Attach to the app's WebView over DevTools. + * The handle heals itself (KI-009, KI-015): before every call it checks that it still talks + * to the app's current process and to the page on screen, and re-attaches when not — a + * restart changes the socket, a reload into a new bundle or a recreated activity can leave + * the old page target answering for a document that is gone. A call cut off by the page + * going away is retried once on the live page; errors thrown by the page itself are not. */ +export async function attach() { + let conn = await connectLive() + const live = async () => { + try { + if (!conn.isClosed() && appSocket() === conn.sock) { + const t = await liveTarget() + if (t && t.id === conn.targetId) return conn + } + } catch {} + try { conn.close() } catch {} + forwarded = null + conn = await connectLive() + return conn + } + return { + get logs() { return conn.logs }, + send: async (...a) => (await live()).send(...a), + async evaluate(expression) { + try { return await (await live()).evaluate(expression) } catch (e) { + if (e.pageError) throw e + try { conn.close() } catch {} + return (await live()).evaluate(expression) + } + }, + close() { try { conn.close() } catch {} }, + } +} + export async function relaunch() { adb('shell', 'am', 'force-stop', APP_ID) launch() diff --git a/tests/e2e/lib/cdp.mjs b/tests/e2e/lib/cdp.mjs index 4fa1923..e25ebc1 100644 --- a/tests/e2e/lib/cdp.mjs +++ b/tests/e2e/lib/cdp.mjs @@ -1,16 +1,39 @@ // Minimal Chrome DevTools Protocol client for the app's Android WebView // (exposed with `adb forward tcp:9333 localabstract:webview_devtools_remote_`). // Playwright can't drive an Android WebView's browser context, so this speaks CDP directly. + +/** The page the person sees: a WebView can list more than one page target while it is + * replaced (a reload into a new bundle, a recreated activity) and the old one lingers + * hidden/empty for a while; the first `page` in the list is not necessarily the live one. */ +export async function liveTarget(port = 9333) { + const targets = await fetch(`http://127.0.0.1:${port}/json`, { signal: AbortSignal.timeout(3000) }).then(r => r.json()) + const pages = targets.filter(t => t.type === 'page') + const info = t => { try { return JSON.parse(t.description || '{}') } catch { return {} } } + return pages.find(t => info(t).visible && !info(t).empty) + || pages.find(t => info(t).attached && !info(t).empty) + || pages[0] || null +} + export async function connectWebView(port = 9333) { - const targets = await fetch(`http://127.0.0.1:${port}/json`).then(r => r.json()) - const target = targets.find(t => t.type === 'page') + const target = await liveTarget(port) if (!target) throw new Error('no WebView page target') const ws = new WebSocket(target.webSocketDebuggerUrl) - await new Promise((resolve, reject) => { ws.onopen = resolve; ws.onerror = reject }) + await new Promise((resolve, reject) => { + const t = setTimeout(() => reject(new Error('DevTools connect timeout')), 5000) + ws.onopen = () => { clearTimeout(t); resolve() } + ws.onerror = e => { clearTimeout(t); reject(e) } + }) let id = 0 + let closed = false const pending = new Map() const logs = [] + // a dead socket used to leave every later call waiting forever: fail them at once + ws.onclose = () => { + closed = true + for (const { reject } of pending.values()) reject(new Error('DevTools socket closed')) + pending.clear() + } ws.onmessage = ev => { const msg = JSON.parse(ev.data) if (msg.id && pending.has(msg.id)) { @@ -24,9 +47,11 @@ export async function connectWebView(port = 9333) { logs.push('EXCEPTION ' + (d.exception?.description || d.text).slice(0, 400)) } } - const send = (method, params = {}) => new Promise((resolve, reject) => { + const send = (method, params = {}, timeoutMs = 20_000) => new Promise((resolve, reject) => { + if (closed) return reject(new Error('DevTools socket closed')) const msgId = ++id - pending.set(msgId, { resolve, reject }) + const t = setTimeout(() => { pending.delete(msgId); reject(new Error(`DevTools ${method} timed out`)) }, timeoutMs) + pending.set(msgId, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } }) ws.send(JSON.stringify({ id: msgId, method, params })) }) await send('Runtime.enable') @@ -34,8 +59,12 @@ export async function connectWebView(port = 9333) { const evaluate = async expression => { const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }) - if (r.exceptionDetails) throw new Error('eval failed: ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text)) + if (r.exceptionDetails) { + const e = new Error('eval failed: ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text)) + e.pageError = true + throw e + } return r.result.value } - return { send, evaluate, logs, close: () => ws.close() } + return { targetId: target.id, send, evaluate, logs, isClosed: () => closed, close: () => { closed = true; ws.close() } } }