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>
This commit is contained in:
2026-11-17 03:35:02 +02:00
co-authored by Claude Opus 5.5
parent 8abe4d92d3
commit bcf91bf6e9
3 changed files with 120 additions and 19 deletions
+72 -10
View File
@@ -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=<name>')
}
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=<name>`)
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()