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:
+72
-10
@@ -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()
|
||||
|
||||
+36
-7
@@ -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_<pid>`).
|
||||
// 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() } }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user