Files
Rosea/e2e/apps/check-garden.ts

334 lines
16 KiB
TypeScript

/**
* The garden in a BUILT app, on a real machine or device (tauri-platforms.md §5): it opens,
* she is watered, the app is closed and opened again, and she is still watered. Also measured
* on the way: the origin, that there is no service worker, what `persisted()` answers, that no
* request leaves the origin and no CSP violation is reported, and what *Save her to a file* does.
*
* tsx e2e/apps/check-garden.ts desktop [path-to-exe]
* tsx e2e/apps/check-garden.ts android [device-serial]
*
* Desktop: runs the release `.exe` with its WebView2 data in a fresh temporary folder (never the
* player's own) and its DevTools port on 127.0.0.1 only (CLAUDE.md §5.7), through WebView2's own
* environment variables. Those replace the app's `additionalBrowserArgs` for this run, so this
* check says nothing about WebView2's own traffic (G-T6).
* Android: the installed debug APK (`adb install -r`), driven through Playwright's Android support
* over adb; its data is cleared first with `pm clear` (it is the test app, not a player's).
* Every app it starts is stopped in `finally`.
*/
import { expect, _android as android, chromium, type Page } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy';
import { openRing, pastGardener } from '../garden.js';
import { spawn, spawnSync, type ChildProcess } from 'node:child_process';
import { existsSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { storedCare } from '../stored.js';
const PACKAGE_ID = 'cz.mareknovak.domi.rosea';
const report: Record<string, unknown> = {};
/** Requests that leave the game's origin, and CSP violations, from now on. */
function watch(page: Page): { outside: string[]; csp: string[]; errors: string[] } {
const seen = { outside: [] as string[], csp: [] as string[], errors: [] as string[] };
const origin = new URL(page.url()).origin;
page.on('request', (r) => {
const url = r.url();
if (!url.startsWith(origin + '/') && !url.startsWith('data:') && !url.startsWith('blob:')) seen.outside.push(url);
});
page.on('console', (m) => {
if (m.type() !== 'error') return;
if (/Content Security Policy/i.test(m.text())) seen.csp.push(m.text());
else seen.errors.push(m.text());
});
return seen;
}
async function garden(page: Page): Promise<void> {
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME, { timeout: 20_000 });
}
/** The first visit: the first gardener, skip the town (no town is the private choice), water her from the ring, wait for the write. */
async function firstVisit(page: Page): Promise<void> {
await garden(page);
const seen = watch(page);
await page.reload();
await garden(page);
report['origin'] = await page.evaluate(() => location.origin);
report['serviceWorkers'] = await page.evaluate(async () =>
'serviceWorker' in navigator ? (await navigator.serviceWorker.getRegistrations()).length : 'no API'
);
report['manifestLink'] = await page.evaluate(() => document.querySelector('link[rel="manifest"]') !== null);
report['cspMeta'] = await page.evaluate(() => document.querySelector('meta[http-equiv="Content-Security-Policy"]') !== null);
await pastGardener(page);
const skip = page.getByRole('button', { name: /^Not now/ });
if (await skip.isVisible().catch(() => false)) await skip.click();
await openRing(page);
const water = page.getByRole('button', { name: en.rose.water });
await expect(water).toBeVisible();
const box = await water.boundingBox();
if (!box) throw new Error('the Water button has no box');
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.mouse.down();
await page.waitForTimeout(1500);
await page.mouse.up();
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
await storedCare(page, 1);
report['persistedAfterCare'] = await page.evaluate(async () => (navigator.storage?.persisted ? navigator.storage.persisted() : 'no API'));
report['firstVisit'] = { outside: seen.outside, csp: seen.csp, errors: seen.errors };
}
/** After the app was closed and opened again: she is still watered. */
/** On a failure, what the screen showed: a picture in the temporary folder, its path in the report. */
let lastPage: Page | undefined;
async function secondVisit(page: Page): Promise<void> {
lastPage = page;
await garden(page);
// By keyboard: on the tablet a pointer click once waited 30 s for the button to stop moving
// while the garden animated (review). Enter is a real activation, as for a keyboard player.
// Her picture first: the garden's heading comes before her care is read back, and a press in
// that moment was lost twice on the desktop (keep-her-safe-apps review). Then press until the
// button says it is open: a press is only repeated while it still says closed.
await expect(page.getByRole('img', { name: /^The rose/ })).toBeVisible({ timeout: 20_000 });
const numbers = page.getByRole('button', { name: en.rose.numbers });
await expect(async () => {
if ((await numbers.getAttribute('aria-expanded')) !== 'true') await press(numbers);
await expect(numbers).toHaveAttribute('aria-expanded', 'true', { timeout: 1_000 });
}).toPass({ timeout: 15_000 });
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
await storedCare(page, 1);
report['afterRestart'] = 'still watered: 1 day of care, the care log kept';
}
/**
* Presses a button from the keyboard. On the tablet a pointer click waits for the button to stop
* moving, and the planet keeps it moving (review); Enter is a real activation, as for a keyboard player.
*/
async function press(button: ReturnType<Page['getByRole']>): Promise<void> {
await button.focus();
await button.press('Enter');
}
/** Opens *Keep her safe* and checks the app's own words (keep-her-safe-apps.md A1). */
async function openKeepSafe(page: Page): Promise<void> {
const title = page.getByRole('button', { name: en.rose.safe.title });
await expect(async () => {
if ((await title.getAttribute('aria-expanded')) !== 'true') await press(title);
await expect(title).toHaveAttribute('aria-expanded', 'true', { timeout: 1_000 });
}).toPass({ timeout: 15_000 });
await expect(page.getByText(en.rose.safe.app)).toBeVisible();
for (const browserWords of [en.rose.safe.mayClear, en.rose.safe.unknown, en.rose.safe.kept, en.rose.safe.ask]) {
await expect(page.getByText(browserWords)).toHaveCount(0);
}
report['keepHerSafeWords'] = en.rose.safe.app;
}
/** Desktop: *Save her to a file* starts a WebView2 download (cancelled by the check). */
async function desktopSave(page: Page): Promise<void> {
await openKeepSafe(page);
const download = page.waitForEvent('download', { timeout: 10_000 });
await press(page.getByRole('button', { name: en.rose.safe.save }));
const d = await download;
report['saveToFile'] = `a download started: ${d.suggestedFilename()} (cancelled by the check)`;
await d.cancel();
}
interface UiNode {
readonly text: string;
readonly desc: string;
readonly cx: number;
readonly cy: number;
}
/** The screen's accessibility nodes, through uiautomator, printed to stdout (no file left behind). */
function screenNodes(adb: (...args: string[]) => string): UiNode[] {
const xml = adb('exec-out', 'uiautomator', 'dump', '/dev/tty');
const nodes: UiNode[] = [];
for (const m of xml.matchAll(/<node [^>]*?text="([^"]*)"[^>]*?content-desc="([^"]*)"[^>]*?bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/g)) {
const [x1, y1, x2, y2] = [m[3], m[4], m[5], m[6]].map(Number) as [number, number, number, number];
nodes.push({ text: m[1] ?? '', desc: m[2] ?? '', cx: Math.round((x1 + x2) / 2), cy: Math.round((y1 + y2) / 2) });
}
return nodes;
}
/**
* Taps the first node on Android's own screen that matches, waiting up to `ms` for it. Only once
* it stands still: a system screen slides in, and a tap read from the first frame landed where the
* file had been a moment before (keep-her-safe-apps review).
*/
async function tapSystem(adb: (...args: string[]) => string, match: (n: UiNode) => boolean, what: string, ms = 20_000): Promise<void> {
const until = Date.now() + ms;
let last: UiNode | undefined;
while (Date.now() < until) {
const node = screenNodes(adb).find(match);
if (node && last && node.cx === last.cx && node.cy === last.cy) {
adb('shell', 'input', 'tap', String(node.cx), String(node.cy));
return;
}
last = node;
await new Promise((r) => setTimeout(r, 700));
}
throw new Error(`Android's screen never showed ${what}, still`);
}
/**
* Android: the round trip (keep-her-safe-apps.md §5). *Save her to a file* opens Android's save
* screen; the check presses its Save; the garden says she is in that file. Then *Bring her back
* from a file* opens the picker; the check chooses that file; the garden says everything in it is
* already here. The file is removed from the tablet afterwards if this run made it.
*/
async function androidRoundTrip(page: Page, adb: (...args: string[]) => string): Promise<void> {
await openKeepSafe(page);
const name = `rose-${await page.evaluate(() => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
})}.json`;
const before = adb('shell', 'ls', '/sdcard/Download/');
const existed = before.split(/\s+/).includes(name);
if (existed) throw new Error(`/sdcard/Download/${name} is already on the tablet; the check will not overwrite a file it did not make`);
try {
await press(page.getByRole('button', { name: en.rose.safe.save }));
await tapSystem(adb, (n) => /^save$/i.test(n.text), "the save screen's Save button");
await expect(page.locator('.safe [role="status"]')).toHaveText(en.rose.safe.saved, { timeout: 15_000 });
report['saveToFile'] = `Android's save screen; the garden said: ${en.rose.safe.saved}`;
await page.locator('input[type="file"]').click({ force: true });
// By its own text only: a card's preview button is described as "Preview the file …" and comes first.
await tapSystem(adb, (n) => n.text === name, `the file ${name} in the picker`);
// Read from Keep her safe's own status line: it may be below the fold on a small screen.
await expect(page.locator('.safe [role="status"]')).toHaveText(en.rose.safe.alreadyHere, { timeout: 15_000 });
report['bringBack'] = `chose ${name} in Android's picker; the garden said: ${en.rose.safe.alreadyHere}`;
} finally {
const after = adb('shell', 'ls', '/sdcard/Download/').split(/\s+/);
if (after.includes(name)) {
adb('shell', 'rm', `/sdcard/Download/${name}`);
report['cleanedUp'] = `/sdcard/Download/${name}`;
} else {
report['cleanedUp'] = `nothing at /sdcard/Download/${name} (saved elsewhere, or not saved)`;
}
}
}
async function desktop(exe: string): Promise<void> {
if (!existsSync(exe)) throw new Error(`no app at ${exe}; run pnpm tauri:build first`);
const data = mkdtempSync(join(tmpdir(), 'rosea-desktop-check-'));
const port = 9333;
const env = {
...process.env,
WEBVIEW2_USER_DATA_FOLDER: data,
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS: `--remote-debugging-port=${port} --remote-debugging-address=127.0.0.1`
};
const start = (): ChildProcess => spawn(exe, [], { env, stdio: 'ignore' });
const attach = async (): Promise<{ page: Page; close: () => Promise<void> }> => {
for (let i = 0; i < 60; i++) {
try {
const browser = await chromium.connectOverCDP(`http://127.0.0.1:${port}`);
for (let j = 0; j < 40; j++) {
const page = browser.contexts().flatMap((c) => c.pages())[0];
if (page) return { page, close: () => browser.close() };
await new Promise((r) => setTimeout(r, 250));
}
await browser.close();
} catch {
// Not listening yet: the app is still starting. Tried again below; a real failure ends in the throw.
}
await new Promise((r) => setTimeout(r, 500));
}
throw new Error('the app never opened a page on the debugging port');
};
let app: ChildProcess | undefined;
try {
app = start();
let session = await attach();
await firstVisit(session.page);
await session.close();
app.kill();
await new Promise((r) => setTimeout(r, 1500));
app = start();
session = await attach();
await secondVisit(session.page);
await desktopSave(session.page);
await session.close();
report['dataFolder'] = data;
} finally {
app?.kill();
await new Promise((r) => setTimeout(r, 1000));
rmSync(data, { recursive: true, force: true, maxRetries: 5, retryDelay: 500 });
}
}
async function androidDevice(serial: string | undefined): Promise<void> {
// The USB link to a real tablet drops now and then ("device offline"); a dropped link is waited
// for and the command tried again, up to three times. A command that fails for another reason
// fails the check at once.
const adb = (...args: string[]): string => {
const target = serial ? ['-s', serial] : [];
for (let attempt = 1; ; attempt++) {
const r = spawnSync('adb', [...target, ...args], { encoding: 'utf8' });
if (r.status === 0) return r.stdout;
const dropped = /offline|closed|not found|no devices/i.test(r.stderr);
if (!dropped || attempt === 3) throw new Error(`adb ${args.join(' ')} failed: ${r.stderr}`);
spawnSync('adb', [...target, 'wait-for-device'], { timeout: 30_000 });
}
};
// Playwright's handle to the device dies with the link, so it is found again for each visit.
const open = async (): Promise<{ page: Page; close: () => Promise<void> }> => {
adb('wait-for-device');
const devices = await android.devices();
const device = serial ? devices.find((d) => d.serial() === serial) : devices[0];
if (!device) throw new Error('no Android device over adb');
report['device'] = `${device.model()} (${device.serial()})`;
adb('shell', 'monkey', '-p', PACKAGE_ID, '-c', 'android.intent.category.LAUNCHER', '1');
const webView = await device.webView({ pkg: PACKAGE_ID }, { timeout: 30_000 });
return { page: await webView.page(), close: () => device.close() };
};
const dump = adb('shell', 'dumpsys', 'package', PACKAGE_ID);
if (!dump.includes(`Package [${PACKAGE_ID}]`)) throw new Error(`${PACKAGE_ID} is not installed; adb install -r <apk>`);
report['internetPermission'] = /android\.permission\.INTERNET/.test(dump);
report['allowBackupFlag'] = /flags=\[[^\]]*ALLOW_BACKUP/.test(dump);
let session: { page: Page; close: () => Promise<void> } | undefined;
try {
adb('shell', 'pm', 'clear', PACKAGE_ID);
session = await open();
await firstVisit(session.page);
await session.close();
adb('shell', 'am', 'force-stop', PACKAGE_ID);
await new Promise((r) => setTimeout(r, 1500));
session = await open();
await secondVisit(session.page);
await androidRoundTrip(session.page, adb);
} finally {
adb('shell', 'am', 'force-stop', PACKAGE_ID);
await session?.close().catch((error: unknown) => console.error('check-garden: closing the device handle failed', error));
}
}
const [target, arg] = process.argv.slice(2);
try {
if (target === 'desktop') {
await desktop(resolve(arg ?? 'apps/rosea-tauri/src-tauri/target/release/rosea-shell.exe'));
} else if (target === 'android') {
await androidDevice(arg);
} else {
throw new Error('usage: check-garden.ts desktop [exe] | android [serial]');
}
console.log(JSON.stringify(report, null, 2));
console.log(`check-garden ${target}: PASSED`);
} catch (error) {
if (lastPage) {
const shot = join(tmpdir(), `rosea-check-${target ?? 'unknown'}-failure.png`);
await lastPage.screenshot({ path: shot }).then(
() => (report['failureScreenshot'] = shot),
(e: unknown) => (report['failureScreenshot'] = `could not take one: ${String(e)}`)
);
}
console.log(JSON.stringify(report, null, 2));
console.error(`check-garden ${target}: FAILED — ${(error as Error).message}`);
process.exitCode = 1;
}