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:
+12
-2
@@ -184,7 +184,13 @@ async function rediscovery() {
|
|||||||
return false
|
return false
|
||||||
} catch { v = await attach().catch(() => v); return false }
|
} catch { v = await attach().catch(() => v); return false }
|
||||||
}, ms, 500)
|
}, 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
|
return ok
|
||||||
}
|
}
|
||||||
r.check('setup: paired and logged in', !!(await onScreen(async vv => (await vv.evaluate('location.pathname')) === '/tables', 45_000)))
|
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)
|
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)
|
r.check('bundles: pairing venue 2 → venue 2 bundle', !!s)
|
||||||
const switchTo = async (label, site, want) => {
|
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)
|
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)
|
await switchTo(`${H}:18443`, 'test-site-1', manifest.version)
|
||||||
|
|||||||
+72
-10
@@ -4,7 +4,7 @@ import { execFileSync, spawn } from 'node:child_process'
|
|||||||
import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
import { existsSync, readdirSync, statSync, writeFileSync } from 'node:fs'
|
||||||
import os from 'node:os'
|
import os from 'node:os'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { connectWebView } from './cdp.mjs'
|
import { connectWebView, liveTarget } from './cdp.mjs'
|
||||||
import { OUT, WAITER, sleep } from './env.mjs'
|
import { OUT, WAITER, sleep } from './env.mjs'
|
||||||
|
|
||||||
export const APP_ID = 'gr.bonamin.xenia'
|
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'] })
|
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() {
|
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'
|
const avd = process.env.AVD || 'Xenia_Test_Phone'
|
||||||
console.log(` booting emulator ${avd} (headless)…`)
|
console.log(` booting emulator ${avd} (headless)…`)
|
||||||
spawn(exe('emulator/emulator'), ['-avd', avd, '-no-window', '-no-audio', '-no-boot-anim', '-gpu', 'swiftshader_indirect', '-no-snapshot'],
|
spawn(exe('emulator/emulator'), ['-avd', avd, '-no-window', '-no-audio', '-no-boot-anim', '-gpu', 'swiftshader_indirect', '-no-snapshot'],
|
||||||
{ detached: true, stdio: 'ignore' }).unref()
|
{ 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++) {
|
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)
|
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). */
|
/** 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 focusedWindow = () => adb('shell', 'dumpsys', 'window').match(/mCurrentFocus=[^}]*\}/)?.[0] || ''
|
||||||
export const shot = name => writeFileSync(path.join(OUT, `${name}.png`), execFileSync(ADB, ['exec-out', 'screencap', '-p']))
|
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). */
|
/** The running app process's DevTools socket. It is named after the pid, and an old
|
||||||
export async function attach() {
|
* 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++) {
|
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) {
|
if (sock) {
|
||||||
adb('forward', 'tcp:9333', `localabstract:${sock}`)
|
try {
|
||||||
try { return await connectWebView() } catch {}
|
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)
|
await sleep(750)
|
||||||
}
|
}
|
||||||
throw new Error('could not attach to the app WebView (is this a debug build?)')
|
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() {
|
export async function relaunch() {
|
||||||
adb('shell', 'am', 'force-stop', APP_ID)
|
adb('shell', 'am', 'force-stop', APP_ID)
|
||||||
launch()
|
launch()
|
||||||
|
|||||||
+36
-7
@@ -1,16 +1,39 @@
|
|||||||
// Minimal Chrome DevTools Protocol client for the app's Android WebView
|
// Minimal Chrome DevTools Protocol client for the app's Android WebView
|
||||||
// (exposed with `adb forward tcp:9333 localabstract:webview_devtools_remote_<pid>`).
|
// (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.
|
// 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) {
|
export async function connectWebView(port = 9333) {
|
||||||
const targets = await fetch(`http://127.0.0.1:${port}/json`).then(r => r.json())
|
const target = await liveTarget(port)
|
||||||
const target = targets.find(t => t.type === 'page')
|
|
||||||
if (!target) throw new Error('no WebView page target')
|
if (!target) throw new Error('no WebView page target')
|
||||||
const ws = new WebSocket(target.webSocketDebuggerUrl)
|
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 id = 0
|
||||||
|
let closed = false
|
||||||
const pending = new Map()
|
const pending = new Map()
|
||||||
const logs = []
|
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 => {
|
ws.onmessage = ev => {
|
||||||
const msg = JSON.parse(ev.data)
|
const msg = JSON.parse(ev.data)
|
||||||
if (msg.id && pending.has(msg.id)) {
|
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))
|
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
|
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 }))
|
ws.send(JSON.stringify({ id: msgId, method, params }))
|
||||||
})
|
})
|
||||||
await send('Runtime.enable')
|
await send('Runtime.enable')
|
||||||
@@ -34,8 +59,12 @@ export async function connectWebView(port = 9333) {
|
|||||||
|
|
||||||
const evaluate = async expression => {
|
const evaluate = async expression => {
|
||||||
const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
|
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 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