Files
xenia-pos-local/tests/e2e/lib/android.mjs
T
bonaminandClaude Opus 5.5 f85894a72e refactor(connect): one live connection, no token in any address (SSE removed)
Plan step 4.0. Owner (2026-11-17): no phone in use needs to keep working, so no
compatibility path.
- Removed the SSE channel: routers/sse.py (/api/sse/stream, which still accepted a JWT whose
  session had ended — a signed-out phone could keep listening), services/sse_bus.py (every
  backend module now calls services/ws_bus.broadcast_sync directly), waiter useSSE.js.
- Credentials only in the first frame: the waiter's useWebSocket and the manager's
  LiveProvider send {token} there like the terminal; routers/ws.py no longer reads ?token=
  (a token in a URL ends up in proxy and server logs).
- Waiter: SSEContext → LiveContext (LiveProvider, useLiveContext, liveAlive, the
  'live-event' / 'live-reconnected' window events), dead SSE compat code removed.
- Tests: a token in the address is refused, /api/sse/stream is 404; e2e browser (3 delivery
  modes) and manager assert no token in the live connection's address. Android taps now
  wait for their element (the fixed sleeps made the suite flaky, KI-009).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:49:21 +02:00

132 lines
6.5 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 } 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. */
export async function ensureDevice() {
if (/\tdevice$/m.test(adb('devices'))) return
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()
for (let i = 0; i < 90; i++) {
try { if (adb('shell', 'getprop', 'sys.boot_completed').trim() === '1') return } catch {}
await sleep(3000)
}
throw new Error(`emulator ${avd} did not boot — create it in Android Studio or set AVD=<name>`)
}
/** 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']))
/** Attach to the app's WebView over DevTools (the socket changes when the process restarts). */
export async function attach() {
for (let i = 0; i < 40; i++) {
const sock = adb('shell', 'cat', '/proc/net/unix').match(/webview_devtools_remote_\d+/)?.[0]
if (sock) {
adb('forward', 'tcp:9333', `localabstract:${sock}`)
try { return await connectWebView() } catch {}
}
await sleep(750)
}
throw new Error('could not attach to the app WebView (is this a debug build?)')
}
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'))"