Files
xenia-pos-local/tests/e2e/lib/android.mjs
T
bonaminandClaude Opus 5.5 bcf91bf6e9 test(android): self-healing WebView handle, fresh emulator, diagnostics (KI-015)
- lib/cdp.mjs: attach to the visible, non-empty page target (a replaced WebView can
  leave the old target listed first); a closed DevTools socket fails pending calls at
  once instead of hanging; every call has a timeout.
- lib/android.mjs: attach() follows the app's current process (socket named after its
  pid; an old one can linger) and re-attaches before a call when the process or the
  live page changed; a call cut off by the page going away is retried once.
  ensureDevice() reboots an emulator up longer than EMULATOR_MAX_UPTIME_MIN (30).
- android.mjs: switching venues waits until /venues lists them (the app may still be
  reloading into the last venue's bundle); a rediscovery timeout logs the page's DOM
  and console next to the screenshot.

Run alone: rediscovery 7/7, basics 3/3, stacks 21/21.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:35:02 +02:00

194 lines
8.9 KiB
JavaScript

// Driving the real app on an Android emulator: real taps/typing via adb,
// state via the debug build's WebView DevTools (lib/cdp.mjs).
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, liveTarget } from './cdp.mjs'
import { OUT, WAITER, sleep } from './env.mjs'
export const APP_ID = 'gr.bonamin.xenia'
const SDK = process.env.ANDROID_HOME || process.env.ANDROID_SDK_ROOT
|| (process.platform === 'win32' ? path.join(process.env.LOCALAPPDATA || '', 'Android', 'Sdk') : path.join(os.homedir(), 'Android', 'Sdk'))
const exe = name => path.join(SDK, ...name.split('/')) + (process.platform === 'win32' ? '.exe' : '')
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.
* 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'))) {
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=<name>')
}
async function waitForBoot(what, hint = '') {
for (let i = 0; i < 90; i++) {
try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') { await sleep(3000); return } } catch {}
await sleep(3000)
}
throw new Error(`${what} did not boot${hint}`)
}
/** Newest debug APK from `npm run apk:debug` (WebView debugging needs a debug build). */
export function debugApk() {
const dir = path.join(WAITER, 'releases')
const apks = existsSync(dir) ? readdirSync(dir).filter(f => f.endsWith('-debug.apk')) : []
if (!apks.length) throw new Error('no debug APK — run `npm run apk:debug` in waiter_pwa first')
return path.join(dir, apks.sort((a, b) => statSync(path.join(dir, b)).mtimeMs - statSync(path.join(dir, a)).mtimeMs)[0])
}
export function installApp({ fresh = true } = {}) {
if (fresh) { try { adb('uninstall', APP_ID) } catch {} }
adb('install', '-r', debugApk())
}
export const launch = () => adb('shell', 'monkey', '-p', APP_ID, '-c', 'android.intent.category.LAUNCHER', '1')
export const home = () => adb('shell', 'input', 'keyevent', 'KEYCODE_HOME')
export const back = () => adb('shell', 'input', 'keyevent', 'KEYCODE_BACK')
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']))
/** 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 = appSocket()
if (sock) {
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()
await sleep(4000)
return attach()
}
/** Reload inside the running app (a force-stop right after a localStorage write can lose it). */
export async function reloadApp(v, target = '/') {
await v.evaluate(`setTimeout(() => location.replace(${JSON.stringify(target)}), 300)`)
v.close()
await sleep(3500)
return attach()
}
const statusBar = () => Number(adb('shell', 'dumpsys', 'window').match(/statusBars.*?frame=\[0,0\]\[\d+,(\d+)\]/s)?.[1] || 0)
/** Real tap on the element matching a CSS selector (and containing `text`). */
export async function tap(v, selector, text = '', { last = false, timeout = 10_000 } = {}) {
// waits for the element (a relaunch or a route change on the emulator can take a few
// seconds; fixed sleeps made the suite flaky, KI-009) instead of failing at once
const find = () => v.evaluate(`(() => {
const els = [...document.querySelectorAll(${JSON.stringify(selector)})].filter(e => e.textContent.includes(${JSON.stringify(text)}))
const b = els[${last ? 'els.length - 1' : '0'}]?.getBoundingClientRect()
return b && b.width > 0 ? { x: b.x + b.width / 2, y: b.y + b.height / 2, dpr: devicePixelRatio } : null
})()`).catch(() => null)
let r = await find()
for (const until = Date.now() + timeout; !r && Date.now() < until;) {
await new Promise(res => setTimeout(res, 300))
r = await find()
}
if (!r) throw new Error(`nothing to tap: ${selector} "${text}"`)
adb('shell', 'input', 'tap', String(Math.round(r.x * r.dpr)), String(Math.round(r.y * r.dpr + statusBar())))
}
/** Replace the first input's content by real typing. */
export async function typeInto(v, text) {
await tap(v, 'input')
await sleep(300)
await v.evaluate("document.querySelector('input').select()")
adb('shell', 'input', 'keyevent', 'KEYCODE_DEL')
adb('shell', `input text '${text}'`) // quoted for the device shell (& in URLs)
}
/** Tap a system dialog button (e.g. the camera permission prompt) by its label. */
export function tapDialogButton(label) {
adb('shell', 'uiautomator', 'dump', '/sdcard/ui.xml')
const xml = adb('shell', 'cat', '/sdcard/ui.xml')
const m = xml.match(new RegExp(`text="${label}"[^>]*bounds="\\[(\\d+),(\\d+)\\]\\[(\\d+),(\\d+)\\]"`))
if (!m) throw new Error(`dialog button not found: ${label}`)
adb('shell', 'input', 'tap', String((+m[1] + +m[3]) >> 1), String((+m[2] + +m[4]) >> 1))
}
/** Navigate inside the app without a reload. */
export const goTo = (v, p) => v.evaluate(`history.pushState({}, '', ${JSON.stringify(p)}); dispatchEvent(new PopStateEvent('popstate'))`)
export const venuesState = async v => JSON.parse(await v.evaluate("localStorage.getItem('xenia.venues')"))
export async function setVenues(v, state) {
await v.evaluate(`localStorage.setItem('xenia.venues', ${JSON.stringify(JSON.stringify(state))})`)
await sleep(1200)
}
export const GREEN = 'rgb(34, 197, 94)'
export const connectivityColor = v => v.evaluate("document.querySelector('.connectivity-bar') ? getComputedStyle(document.querySelector('.connectivity-bar')).backgroundColor : 'none'")
// @capgo/capacitor-updater from inside the page
export const UPD = "(window.Capacitor.Plugins.CapacitorUpdater || window.Capacitor.registerPlugin('CapacitorUpdater'))"