/** * `pnpm test:android` — the BUILT app on a real Android device over USB, by real touch. * * Needs: the device on USB debugging, the app built (`pnpm build`), and `vite preview` serving * apps/rosea/dist on 127.0.0.1:4173 (`pnpm --filter @rosea/app exec vite preview --port 4173`). * `ROSEA_ADB` names adb (default: on PATH); `ROSEA_ANDROID_SERIAL` names the device (default: * the only one attached). Screenshots go to the folder given as the first argument. * * `adb reverse` maps the device's own localhost:4173 to this computer's 127.0.0.1:4173, so nothing * listens on the network (CLAUDE.md §5.7), and Chrome treats localhost as secure, so the service * worker runs as it will on the real host. Chrome is driven through its DevTools socket, as * chrome://inspect does; every tap is Chrome's own touch input, so the gestures are a finger's. * Offline is real: the mapping is removed, so the device cannot reach the server at all. * * It leaves the device as it found it, as the author asks: everything stored for * http://localhost:4173 is deleted, the tab is closed, **Chrome is stopped**, the mappings removed. */ import { chromium, expect, type Browser, type Locator, type Page } from '@playwright/test'; import { en } from '@rosea/ui/copy'; import { execFileSync } from 'node:child_process'; import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; const ADB = process.env['ROSEA_ADB'] ?? 'adb'; const SERIAL = process.env['ROSEA_ANDROID_SERIAL']; const URL = 'http://localhost:4173/Rosea/'; const OUT = process.argv[2] ?? 'android-shots'; mkdirSync(OUT, { recursive: true }); const adb = (...args: string[]): string => execFileSync(ADB, [...(SERIAL ? ['-s', SERIAL] : []), ...args], { encoding: 'utf8' }).trim(); const results: string[] = []; async function step(name: string, run: () => Promise): Promise { const t = Date.now(); try { await run(); results.push(`PASS ${name} (${((Date.now() - t) / 1000).toFixed(1)} s)`); } catch (error) { results.push(`FAIL ${name}: ${String(error).split('\n')[0]}`); throw error; } } const shot = (page: Page, name: string): Promise => page.screenshot({ path: join(OUT, `${name}.png`) }); /** A finger: touch down on the middle of `target`, move by (dx, dy) in `steps`, hold, lift. */ async function finger(page: Page, target: Locator, o: { dx?: number; dy?: number; holdMs?: number; steps?: number; moveMs?: number } = {}): Promise { await target.scrollIntoViewIfNeeded(); const box = await target.boundingBox(); if (!box) throw new Error('nothing to touch'); const cdp = await page.context().newCDPSession(page); const x = box.x + box.width / 2, y = box.y + box.height / 2; const { dx = 0, dy = 0, holdMs = 60, steps = 0, moveMs = 0 } = o; await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); for (let i = 1; i <= steps; i++) { if (moveMs) await page.waitForTimeout(moveMs / steps); await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: x + (dx * i) / steps, y: y + (dy * i) / steps }] }); } await page.waitForTimeout(holdMs); await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); await cdp.detach(); } console.log(`device: ${adb('shell', 'getprop', 'ro.product.model')} (${adb('get-serialno')})`); let browser: Browser | undefined; let page: Page | undefined; /** Chrome's DevTools socket comes up a moment after Chrome starts: try for half a minute. */ async function connect(): Promise { for (let i = 0; ; i++) { try { return await chromium.connectOverCDP('http://127.0.0.1:9222'); } catch (error) { if (i >= 30) throw error; await new Promise((r) => setTimeout(r, 1000)); } } } // Everything from the first mapping on is inside try, so the clean-up below always runs. try { adb('reverse', 'tcp:4173', 'tcp:4173'); adb('forward', 'tcp:9222', 'localabstract:chrome_devtools_remote'); adb('shell', 'am', 'start', '-a', 'android.intent.action.VIEW', '-d', URL, 'com.android.chrome'); browser = await connect(); const context = browser.contexts()[0]; if (!context) throw new Error('Chrome on the device has no context'); for (let i = 0; i < 30 && !page; i++) { page = context.pages().find((p) => p.url().startsWith(URL)); if (!page) await new Promise((r) => setTimeout(r, 1000)); } if (!page) throw new Error(`Chrome did not open ${URL}`); const tab: Page = page; await step('opens the built app under /Rosea/; the service worker takes control', async () => { await expect(tab.getByRole('heading', { level: 1 })).toHaveText('Rosea Domi', { timeout: 30_000 }); await tab.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 30_000 }); await tab.waitForFunction(() => navigator.serviceWorker.controller !== null, null, { timeout: 30_000 }); }); await step('Who tends her? A boy, by touch, then This is me', async () => { await expect(tab.getByRole('heading', { level: 2, name: en.gardener.question })).toBeVisible({ timeout: 15_000 }); await shot(tab, '1-who-tends-her'); await finger(tab, tab.getByText(en.gardener.values.presentation.boy, { exact: true })); await finger(tab, tab.getByText(en.gardener.values.hat.cap, { exact: true })); await finger(tab, tab.getByRole('button', { name: en.gardener.done })); await expect(tab.getByRole('group', { name: en.scene.planet })).toBeVisible(); }); await step('chooses Brno: the line names the next sunrise or sunset', async () => { await tab.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno'); await finger(tab, tab.getByRole('button', { name: /^Brno/ }).first()); await expect(tab.locator('.sun p').first()).toHaveText(/(rises|sets) at .* in Brno\.$/); await shot(tab, '2-planet'); }); await step('a tap on her opens the ring of care; Close closes it', async () => { await finger(tab, tab.getByRole('button', { name: en.rose.care })); await expect(tab.getByRole('group', { name: en.scene.ring })).toBeVisible(); await shot(tab, '3-ring'); await finger(tab, tab.getByRole('button', { name: en.scene.close })); await expect(tab.getByRole('group', { name: en.scene.ring })).toHaveCount(0); }); await step('pressing the can and tilting it by finger pours: she thanks the player', async () => { await finger(tab, tab.getByRole('img', { name: en.scene.can }), { dx: 90, steps: 6, moveMs: 300, holdMs: 1300 }); await expect(tab.getByText(en.rose.says.thanks)).toBeVisible(); await shot(tab, '4-watered'); }); await step('a slow stroke across her petals touches her', async () => { await tab.waitForTimeout(400); await finger(tab, tab.getByRole('button', { name: en.rose.care }), { dx: 30, dy: -20, steps: 6, moveMs: 500 }); await expect(tab.locator('.bubble')).toHaveText(en.rose.touch.fond[0]!); }); await step('OFFLINE: with the server unreachable, a reload brings back the planet, the gardener, her care and the town', async () => { adb('reverse', '--remove', 'tcp:4173'); await tab.reload(); await expect(tab.getByRole('group', { name: en.scene.planet })).toBeVisible({ timeout: 30_000 }); await expect(tab.getByRole('heading', { name: en.gardener.question })).toHaveCount(0); await expect(tab.locator('.sun p').first()).toHaveText(/in Brno\.$/); await finger(tab, tab.getByRole('button', { name: en.rose.numbers })); await expect(tab.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`); await shot(tab, '5-offline'); }); } finally { // Leave the device as it was: nothing of this origin stays behind, and Chrome is stopped. if (page) try { await page.evaluate(async () => { for (const r of await navigator.serviceWorker.getRegistrations()) await r.unregister(); for (const k of await caches.keys()) await caches.delete(k); await new Promise((resolve) => { const req = indexedDB.deleteDatabase('rosea'); req.onsuccess = req.onerror = req.onblocked = () => resolve(); }); }); results.push(' cleaned: service worker, caches and the rosea database for localhost:4173'); } catch (error) { results.push(`WARN cleanup failed: ${String(error).split('\n')[0]}`); } await page?.close().catch((error: unknown) => results.push(`WARN could not close the tab: ${String(error)}`)); await browser?.close().catch((error: unknown) => results.push(`WARN could not disconnect: ${String(error)}`)); for (const args of [['shell', 'am', 'force-stop', 'com.android.chrome'], ['reverse', '--remove', 'tcp:4173'], ['forward', '--remove', 'tcp:9222']]) { try { adb(...args); } catch (error) { results.push(` ${args.join(' ')}: ${String(error).split('\n')[0]} (already done)`); } } results.push(' stopped: Chrome on the device; adb mappings removed'); console.log(results.join('\n')); }