- 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>
71 lines
3.4 KiB
JavaScript
71 lines
3.4 KiB
JavaScript
// 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 target = await liveTarget(port)
|
|
if (!target) throw new Error('no WebView page target')
|
|
const ws = new WebSocket(target.webSocketDebuggerUrl)
|
|
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)) {
|
|
const { resolve, reject } = pending.get(msg.id)
|
|
pending.delete(msg.id)
|
|
msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result)
|
|
} else if (msg.method === 'Runtime.consoleAPICalled') {
|
|
logs.push(`[${msg.params.type}] ` + msg.params.args.map(a => a.value ?? a.description ?? '').join(' ').slice(0, 300))
|
|
} else if (msg.method === 'Runtime.exceptionThrown') {
|
|
const d = msg.params.exceptionDetails
|
|
logs.push('EXCEPTION ' + (d.exception?.description || d.text).slice(0, 400))
|
|
}
|
|
}
|
|
const send = (method, params = {}, timeoutMs = 20_000) => new Promise((resolve, reject) => {
|
|
if (closed) return reject(new Error('DevTools socket closed'))
|
|
const msgId = ++id
|
|
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')
|
|
await send('Page.enable')
|
|
|
|
const evaluate = async expression => {
|
|
const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true })
|
|
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 { targetId: target.id, send, evaluate, logs, isClosed: () => closed, close: () => { closed = true; ws.close() } }
|
|
}
|