diff --git a/docs/agent-guide.md b/docs/agent-guide.md index 554e0bc..fd76ad9 100644 --- a/docs/agent-guide.md +++ b/docs/agent-guide.md @@ -36,7 +36,7 @@ Concretely: - **Get it right the first time.** The owner should never have to ask you to remove something you added or to fix how it looks or feels. Before you publish, read `miakapp docs design` and follow it to the letter, check the - app on a phone (§5, "Check it on a phone"), and remove anything the guides + app for real (§5, "Check it for real"), and remove anything the guides tell you not to add (a connection banner, your own bottom bar, a value nobody asked for). - **You need nothing from the platform's source.** This guide and the published @@ -450,85 +450,30 @@ world does not have a rollback. Surface it, let the next state snapshot settle it, and let the person decide. The same principle has a CLI counterpart: exit code 7. -### Check it on a phone - -Residents use the app on a phone, installed on the home screen. Look at every -page at phone size, with touch, before you tell the owner it is done: the home -screen fits without scrolling, nothing overflows, held actions fill and fire, -and a swipe from the left edge goes back. - -Use the browser you already have; **never install one** (`playwright -install`, Chromium, a headless shell): on Molted and on most agent machines it -is forbidden, and it is never needed. `playwright-core` is the client alone and -downloads no browser; on a Molted machine it drives the cloud browser through -`$AGENT_BROWSER_BASIC_CDP`. - -**Do not trust viewport emulation.** A remote or shared browser often ignores -it: on Molted's cloud browser, `newContext({ viewport, isMobile })`, -`Emulation.setDeviceMetricsOverride` and `agent-browser set viewport` all leave -the page at desktop width. Get the phone size from a frame instead, and measure -`innerWidth` inside the app before you trust a screenshot. - -1. Build, then serve a local preview next to `dist/`: `phone.html` holds the - app in a 390 × 844 frame, `frame.html` stands in for Miakapp's bridge with - the real values you read from the house. - - ```html - -
- - - - - - ``` - - Serve it where the browser can reach it (on Molted: a port exposed with a - public URL). A preview call never reaches the house. - -2. Drive it with touch. Taps work with `page.touchscreen.tap`; a swipe is a - sequence of CDP touch events: - - ```js - import { chromium } from 'playwright-core'; // npm i playwright-core, in a scratch directory +### Check it for real - const browser = await chromium.connectOverCDP(process.env.AGENT_BROWSER_BASIC_CDP); - const context = await browser.newContext({ hasTouch: true }); - const page = await context.newPage(); - await page.goto(PREVIEW_URL + '/phone.html', { waitUntil: 'commit' }); - const app = page.frameLocator('iframe'); - await app.locator('.mk-entry').first().waitFor(); - console.log(await page.frames()[1].evaluate(() => innerWidth)); // must print 390 - await page.screenshot({ path: 'home.png', clip: { x: 0, y: 0, width: 390, height: 844 } }); +Never check against a bridge you wrote yourself: it hides what breaks on a +phone (sandbox refusals, late answers, refused calls, rate limits). Run the app +against the real home: - const cdp = await context.newCDPSession(page); - const touch = (type, x, y) => cdp.send('Input.dispatchTouchEvent', - { type, touchPoints: type === 'touchEnd' ? [] : [{ x, y }] }); - await touch('touchStart', 6, 400); // the left edge - for (let x = 46; x <= 286; x += 40) await touch('touchMove', x, 400); - await touch('touchEnd', 286, 400); // should go back one page - - await page.close(); // your page only, never browser.close() - ``` +```bash +bun run build +miakapp preview --as member # your build, not activated: prints a link +miakapp taps --as member # taps every control there, reports what is wrong +``` - Remote control adds latency between touch events, so a "flick" sent this - way arrives slowly; test speed with a long swipe, not a flick. +`preview` (your build) and `open` (the live release) print a link, valid up to +an hour, that opens the home at phone size (390 × 844) as the test member +`test:`: your app reads `home.link.params.invite` (kept through sign-in). |
+| Testing as each role | `miakapp open --as ` (also `preview`, `taps`) opens the home as `test:`, with no e-mail: give that id the role's rights in your member list (never owner), and nothing else. |
Anyone signed in can open any home's address and load its app (the bundle holds
no household data: §5 of `docs start`). A person you have not admitted must get
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 83106d9..08513f3 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@miakapp/cli",
- "version": "4.6.1",
+ "version": "4.7.0",
"description": "Agent-first Miakapp command line: check, build, publish, activate and roll back home interfaces",
"type": "module",
"engines": {
diff --git a/packages/cli/src/control-plane.ts b/packages/cli/src/control-plane.ts
index 23009a1..8cc5776 100644
--- a/packages/cli/src/control-plane.ts
+++ b/packages/cli/src/control-plane.ts
@@ -255,3 +255,64 @@ export async function sendNotification(
}
return typeof document.delivered === 'number' ? document.delivered : 0;
}
+
+export interface TestSession {
+ readonly homeId: string;
+ readonly role: string;
+ readonly principalId: string;
+ readonly release: string | null;
+ readonly expiresAtMs: number;
+ /** Opens the home at phone size (390 × 844), as `test:`. */
+ readonly url: string;
+}
+
+/**
+ * Opens a test session: a link that opens the home as the stand-in member
+ * `test:`, for at most an hour, with no account. `release` previews a
+ * finalized digest that is not live. Needs a key that may run the coordinator.
+ */
+export async function openTestSession(
+ discovery: Discovery,
+ homeKey: string,
+ request: { readonly role: string; readonly release?: string; readonly minutes?: number },
+ options: { readonly fetch?: FetchLike } = {},
+): Promise {
+ const fetcher = options.fetch ?? globalThis.fetch;
+ const response = await fetcher(`${discovery.issuer}/v1/test-sessions`, {
+ method: 'POST',
+ headers: {
+ accept: 'application/json',
+ authorization: `Bearer ${homeKey}`,
+ 'content-type': 'application/json',
+ },
+ body: requestBody(request),
+ credentials: 'omit',
+ redirect: 'error',
+ referrerPolicy: 'no-referrer',
+ });
+ const document = parseJson(await readBoundedBody(response, 16_384)) as Record & {
+ readonly error?: { readonly code?: unknown };
+ };
+ if (response.status !== 201) {
+ const code = String(document.error?.code ?? response.status);
+ throw authorizationError(
+ `Test session refused: ${code}`,
+ code === 'invalid_request' && response.status === 404
+ ? 'This control plane has no test sessions yet.'
+ : 'The key must be active and able to run the coordinator; --as takes a lowercase role '
+ + '(member, admin, guest…), --minutes 1..60.',
+ );
+ }
+ if (document.schema !== 'miakapp.test-session/1' || typeof document.url !== 'string'
+ || typeof document.home_id !== 'string' || typeof document.expires_at_ms !== 'number') {
+ throw contractError('Test session response does not match miakapp.test-session/1');
+ }
+ return Object.freeze({
+ homeId: document.home_id,
+ role: String(document.role),
+ principalId: String(document.principal_id),
+ release: typeof document.release === 'string' ? document.release : null,
+ expiresAtMs: document.expires_at_ms,
+ url: document.url,
+ });
+}
diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts
index 3ec69c8..2027ab3 100644
--- a/packages/cli/src/main.ts
+++ b/packages/cli/src/main.ts
@@ -18,7 +18,16 @@ import { homedir, hostname } from 'node:os';
import { installPack } from './agent-pack.js';
import { CLI_VERSION } from './version.js';
import { prepareArtifact, type Artifact } from './artifact.js';
-import { exchangePublisherToken, fetchDiscovery, homeKeyId, homeUrl, sendNotification } from './control-plane.js';
+import {
+ exchangePublisherToken,
+ fetchDiscovery,
+ homeKeyId,
+ homeUrl,
+ openTestSession,
+ sendNotification,
+ type TestSession,
+} from './control-plane.js';
+import { runTaps, type TapReport } from './taps.js';
import {
configDirectory,
contextNameError,
@@ -59,6 +68,7 @@ import { PROJECT_FILE, PROJECT_SCHEMA, findProjectFile, parseProject, type Proje
import {
activateRelease,
publish,
+ stage,
readPointer,
readRelease,
readUpload,
@@ -156,6 +166,9 @@ Commands
check Validate the project and the artifact offline
status Read the live generation and release of the home
notify Notify the people you name (--to user IDs) on the devices where they turned notifications on
+ open Link that opens the live home at phone size as test: (--as member)
+ preview Same, running the built artifact without activating it
+ taps Tap every control of the app (preview by default) and report dead ones
publish Upload, finalize and activate the built artifact
activate Activate an already finalized digest at a new generation
rollback Alias of activate, for returning to a known-good digest
@@ -190,6 +203,20 @@ activate / rollback options
--expected-generation Generation the pointer holds (default: read live)
--generation Generation to publish (default: expected + 1)
+open / preview options
+ --as Test identity test: (default: member); your
+ coordinator gives it that role's rights
+ --minutes Lifetime of the link, 1..60 (default: 30)
+
+taps options
+ --as As above (default: member)
+ --send Functions a tap may really call (default: none;
+ every other call a tap makes is held, not sent)
+ --url Check this link (from open) instead of a preview
+ --cdp Browser to drive (default: $MIAKAPP_CDP or
+ $AGENT_BROWSER_BASIC_CDP)
+ --max Stop after n taps (default: 120)
+
discover options
--flows Node-RED flows export to read (required)
@@ -244,6 +271,9 @@ export const COMMAND_OPTIONS: Record = {
check: [],
status: ['context'],
notify: ['to', 'title', 'body', 'context'],
+ open: ['as', 'minutes', 'context'],
+ preview: ['as', 'minutes', 'release', 'context'],
+ taps: ['as', 'send', 'url', 'cdp', 'max', 'context'],
publish: ['expected-generation', 'generation', 'release', 'context'],
activate: ['sha256', 'expected-generation', 'generation', 'context'],
rollback: ['sha256', 'expected-generation', 'generation', 'context'],
@@ -1168,6 +1198,168 @@ async function runNotify(host: CliHost, invocation: Invocation): Promise {
+ let project: Project | undefined;
+ try {
+ project = await loadProject(host, invocation);
+ } catch (error) {
+ if (!(error instanceof CliError) || error.kind !== 'project') throw error;
+ }
+ if (project !== undefined) {
+ const credential = await resolveCredential(host, invocation, project);
+ return { issuer: project.issuer, homeKey: credential.homeKey, project };
+ }
+ const directory = storeDirectory(host);
+ const name = explicitContext(host, invocation) ?? (await readContexts(directory)).current ?? undefined;
+ if (name === undefined) throw usageError('No context: run miakapp pair first, or pass --context ');
+ const { context, homeKey } = await readCredential(directory, name);
+ return { issuer: context.issuer, homeKey, project: undefined };
+}
+
+function testRole(invocation: Invocation): string {
+ const role = invocation.options.get('as') ?? 'member';
+ if (!/^[a-z][a-z0-9-]{0,31}$/.test(role)) {
+ throw usageError('--as takes a lowercase role: member, admin, guest…');
+ }
+ return role;
+}
+
+function testMinutes(invocation: Invocation): number | undefined {
+ const raw = invocation.options.get('minutes');
+ if (raw === undefined) return undefined;
+ const minutes = Number(raw);
+ if (!Number.isSafeInteger(minutes) || minutes < 1 || minutes > 60) throw usageError('--minutes must be 1..60');
+ return minutes;
+}
+
+function testSessionResult(summary: string, session: TestSession): CommandResult {
+ return {
+ summary,
+ fields: [
+ ['url', session.url],
+ ['as', session.principalId],
+ ['release', session.release ?? 'live'],
+ ['expires_at', new Date(session.expiresAtMs).toISOString()],
+ ],
+ json: {
+ home_id: session.homeId,
+ url: session.url,
+ principal_id: session.principalId,
+ release: session.release,
+ expires_at_ms: session.expiresAtMs,
+ },
+ };
+}
+
+async function runOpen(host: CliHost, invocation: Invocation): Promise {
+ const { issuer, homeKey } = await homeAccess(host, invocation);
+ const options = host.fetch === undefined ? {} : { fetch: host.fetch };
+ const discovery = await fetchDiscovery({ issuer, ...options });
+ const minutes = testMinutes(invocation);
+ const session = await openTestSession(discovery, homeKey, {
+ role: testRole(invocation),
+ ...(minutes === undefined ? {} : { minutes }),
+ }, options);
+ return testSessionResult(
+ `Open this link in your browser: ${session.homeId} at phone size, as ${session.principalId} (live release)`,
+ session,
+ );
+}
+
+/** Uploads the built artifact without activating it, then opens it as a test member. */
+async function previewSession(host: CliHost, invocation: Invocation): Promise {
+ const project = await loadProject(host, invocation);
+ const release = invocation.options.get('release') ?? project.release;
+ if (!isRelease(release)) {
+ throw usageError('--release must be 1..64 UTF-8 bytes without control characters');
+ }
+ const artifact = await loadArtifact(host, project);
+ const { target, credential } = await publicationTarget(host, invocation, project);
+ await stage(target, artifact, { release, abi: project.abi, requires: project.requires });
+ const options = host.fetch === undefined ? {} : { fetch: host.fetch };
+ const discovery = await fetchDiscovery({ issuer: project.issuer, ...options });
+ const minutes = testMinutes(invocation);
+ return await openTestSession(discovery, credential.homeKey, {
+ role: testRole(invocation),
+ release: artifact.sha256,
+ ...(minutes === undefined ? {} : { minutes }),
+ }, options);
+}
+
+async function runPreview(host: CliHost, invocation: Invocation): Promise {
+ const session = await previewSession(host, invocation);
+ return testSessionResult(
+ `Open this link in your browser: your build of ${session.homeId}, not activated, at phone size, as ${session.principalId}`,
+ session,
+ );
+}
+
+async function runTapsCommand(host: CliHost, invocation: Invocation): Promise {
+ const cdp = invocation.options.get('cdp') ?? host.env('MIAKAPP_CDP') ?? host.env('AGENT_BROWSER_BASIC_CDP');
+ if (cdp === undefined || cdp === '') {
+ throw usageError(
+ 'taps needs a browser to drive',
+ 'Pass --cdp (Chrome DevTools). On Molted it is $AGENT_BROWSER_BASIC_CDP. Never install a browser for this.',
+ );
+ }
+ const max = invocation.options.get('max');
+ if (max !== undefined && !/^[1-9][0-9]{0,3}$/.test(max)) throw usageError('--max must be 1..9999');
+ const url = invocation.options.get('url') ?? (await previewSession(host, invocation)).url;
+ const send = (invocation.options.get('send') ?? '').split(',').map((name) => name.trim()).filter((name) => name !== '');
+ const report = await runTaps({
+ url,
+ cdp,
+ send,
+ ...(max === undefined ? {} : { maxTaps: Number(max) }),
+ log: (line) => host.writeError(`${line}\n`),
+ });
+ return tapsResult(report, send);
+}
+
+function tapsResult(report: TapReport, send: readonly string[]): CommandResult {
+ const dead = report.taps.filter((tap) => tap.effect === 'nothing');
+ const failed = report.taps.flatMap((tap) => tap.calls
+ .filter((call) => call.outcome === 'error')
+ .map((call) => `${tap.page} › ${tap.element}: ${call.name} → ${call.error ?? 'failed'}`));
+ const held = report.taps.flatMap((tap) => tap.calls
+ .filter((call) => call.outcome === 'held')
+ .map((call) => `${tap.page} › ${tap.element}: ${call.name}`));
+ const startupProblems = report.startupCalls
+ .filter((call) => call.outcome === 'error' || (call.ms ?? 0) > 1_500)
+ .map((call) => `${call.name}: ${call.outcome === 'error' ? call.error ?? 'failed' : 'ok'} in ${call.ms ?? '?'} ms`);
+ const tapErrors = report.taps.flatMap((tap) => tap.errors.map((error) => `${tap.page} › ${tap.element}: ${error}`));
+ const problems = dead.length + failed.length + startupProblems.length + report.errors.length
+ + (report.width === 390 ? 0 : 1);
+ return {
+ summary: problems === 0
+ ? `No dead control: ${report.taps.length} taps on ${report.pages} pages`
+ : `${problems} problem${problems === 1 ? '' : 's'} in ${report.taps.length} taps on ${report.pages} pages`,
+ fields: [
+ ['width', report.width],
+ ['dead', dead.map((tap) => `${tap.page} › ${tap.element}`)],
+ ['call_errors', failed],
+ ['startup_calls', report.startupCalls.map((call) => `${call.name} ${call.outcome} ${call.ms ?? '?'} ms`)],
+ ['slow_or_failed_at_start', startupProblems],
+ ['app_errors', [...new Set([...report.errors, ...tapErrors])]],
+ ['held_not_sent', held],
+ ['sent', send.length === 0 ? 'none' : send],
+ ['screenshots', report.screenshots],
+ ],
+ json: {
+ width: report.width,
+ pages: report.pages,
+ taps: report.taps,
+ startup_calls: report.startupCalls,
+ app_errors: report.errors,
+ screenshots: report.screenshots,
+ },
+ };
+}
+
function defaultLabel(host: CliHost): string {
const machine = (host.hostname?.() ?? hostname()).replace(/[^A-Za-z0-9._-]/g, '-');
return `miakapp-cli@${machine === '' ? 'unknown' : machine}`.slice(0, 64);
@@ -1465,6 +1657,12 @@ export async function dispatch(host: CliHost, invocation: Invocation): Promise, with no account: the real shell, '
+ + 'sandbox, relay and coordinator. Your coordinator decides what test: sees and does. '
+ + 'Open it in the browser you drive; give it to nobody.',
+ args: [
+ { name: 'as', type: 'string', required: false, description: 'Role of the test member (default member).' },
+ { name: 'minutes', type: 'integer', required: false, description: 'Lifetime of the link, 1..60 (default 30).' },
+ PROJECT_ARGUMENT,
+ CONTEXT_ARGUMENT,
+ ],
+ readOnly: true,
+ guarded: false,
+ },
+ {
+ name: 'miakapp_preview',
+ title: 'Preview the built app on the real home',
+ command: 'preview',
+ description:
+ 'Upload the built artifact without activating it, and return a test link that runs it '
+ + 'against the real home, as miakapp_open does. Residents keep the live release.',
+ args: [
+ { name: 'as', type: 'string', required: false, description: 'Role of the test member (default member).' },
+ { name: 'minutes', type: 'integer', required: false, description: 'Lifetime of the link, 1..60 (default 30).' },
+ { name: 'release', type: 'string', required: false, description: 'Release label (default app.release).' },
+ PROJECT_ARGUMENT,
+ CONTEXT_ARGUMENT,
+ ],
+ readOnly: false,
+ guarded: false,
+ },
+ {
+ name: 'miakapp_taps',
+ title: 'Tap every control and report dead ones',
+ command: 'taps',
+ description:
+ 'Preview the built app (or check url), tap every interactive element in a real browser at '
+ + 'phone size, and report the ones with no call, no navigation and no visible change, the '
+ + 'calls that failed, slow start-up calls and the errors the app threw. A call a tap makes '
+ + 'is held, never sent, unless its function is listed in send.',
+ args: [
+ { name: 'as', type: 'string', required: false, description: 'Role of the test member (default member).' },
+ { name: 'send', type: 'string', required: false, description: 'Functions a tap may really call, comma-separated, prefix* allowed. Default none.' },
+ { name: 'url', type: 'string', required: false, description: 'A test link from miakapp_open, instead of a preview.' },
+ { name: 'cdp', type: 'string', required: false, description: 'Chrome DevTools endpoint (default $MIAKAPP_CDP or $AGENT_BROWSER_BASIC_CDP).' },
+ { name: 'max', type: 'integer', required: false, description: 'Stop after this many taps (default 120).' },
+ PROJECT_ARGUMENT,
+ CONTEXT_ARGUMENT,
+ ],
+ readOnly: false,
+ guarded: false,
+ },
{
name: 'miakapp_discover',
title: 'Inventory an existing Node-RED house',
diff --git a/packages/cli/src/publication.ts b/packages/cli/src/publication.ts
index 0d05904..a74f269 100644
--- a/packages/cli/src/publication.ts
+++ b/packages/cli/src/publication.ts
@@ -577,6 +577,31 @@ export async function publish(
readonly generation: number;
},
): Promise<{ readonly release: ComponentRelease; readonly pointer: ComponentPointer }> {
+ const requires = canonicalRequirements(request.requires);
+ const abi = request.abi ?? COMPONENT_ABI;
+ const release = await stage(target, artifact, request);
+ const pointer = await activateRelease(target, {
+ sha256: artifact.sha256,
+ expectedGeneration: request.expectedGeneration,
+ generation: request.generation,
+ });
+ if (pointer.sha256 !== artifact.sha256
+ || pointer.abi !== abi
+ || !sameRequirements(pointer.requires, requires)) {
+ throw contractError('Activated pointer does not match the published release');
+ }
+ return { release, pointer };
+}
+
+/**
+ * Uploads and finalizes one artifact without activating it: what a preview
+ * runs. Residents keep the live release.
+ */
+export async function stage(
+ target: PublicationTarget,
+ artifact: Artifact,
+ request: UploadRequest,
+): Promise {
const requires = canonicalRequirements(request.requires);
const abi = request.abi ?? COMPONENT_ABI;
const capability = await requestUpload(target, artifact, { release: request.release, abi, requires });
@@ -601,17 +626,7 @@ export async function publish(
if (release.sha256 !== artifact.sha256 || release.size !== artifact.size || release.abi !== abi) {
throw contractError('Finalized release does not match the delivered artifact');
}
- const pointer = await activateRelease(target, {
- sha256: artifact.sha256,
- expectedGeneration: request.expectedGeneration,
- generation: request.generation,
- });
- if (pointer.sha256 !== artifact.sha256
- || pointer.abi !== abi
- || !sameRequirements(pointer.requires, requires)) {
- throw contractError('Activated pointer does not match the published release');
- }
- return { release, pointer };
+ return release;
}
async function requireRelease(
diff --git a/packages/cli/src/taps.ts b/packages/cli/src/taps.ts
new file mode 100644
index 0000000..8701383
--- /dev/null
+++ b/packages/cli/src/taps.ts
@@ -0,0 +1,425 @@
+/**
+ * `miakapp taps`: open a test session in a real browser (Chrome DevTools
+ * Protocol), tap every interactive element of the home's app at phone size,
+ * and report the ones that do nothing — no call, no navigation, no visible
+ * change — plus the calls that failed or answered late and the errors the app
+ * threw.
+ *
+ * Nothing a tap would send reaches the house unless its function is listed in
+ * `send`: the shell of a test session holds those calls and records them
+ * (`window.miakappTest`). Calls the app makes on its own (start-up, timers)
+ * do go through, so the report shows their real latency and errors.
+ */
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export interface TapOptions {
+ readonly url: string;
+ readonly cdp: string;
+ /** Function names (or `prefix*`) whose calls a tap may really send. */
+ readonly send: readonly string[];
+ readonly maxTaps?: number;
+ readonly log?: (line: string) => void;
+}
+
+export interface TapResult {
+ readonly page: string;
+ readonly element: string;
+ readonly effect: 'call' | 'navigation' | 'change' | 'nothing' | 'disabled';
+ readonly calls: readonly { name: string; outcome: string; error?: string }[];
+ readonly errors: readonly string[];
+}
+
+export interface CallReport {
+ readonly name: string;
+ readonly outcome: string;
+ readonly error?: string;
+ readonly ms?: number;
+}
+
+export interface TapReport {
+ readonly pages: number;
+ readonly taps: readonly TapResult[];
+ readonly startupCalls: readonly CallReport[];
+ readonly errors: readonly string[];
+ readonly screenshots: string;
+ readonly width: number;
+}
+
+interface CdpMessage {
+ id?: number;
+ method?: string;
+ params?: Record;
+ result?: Record;
+ error?: { message: string };
+ sessionId?: string;
+}
+
+class Cdp {
+ readonly #socket: WebSocket;
+ #next = 1;
+ readonly #pending = new Map) => void; reject: (error: Error) => void }>();
+ readonly #listeners = new Set<(message: CdpMessage) => void>();
+
+ private constructor(socket: WebSocket) {
+ this.#socket = socket;
+ socket.addEventListener('message', (event) => {
+ const message = JSON.parse(String(event.data)) as CdpMessage;
+ if (message.id !== undefined) {
+ const pending = this.#pending.get(message.id);
+ this.#pending.delete(message.id);
+ if (message.error !== undefined) pending?.reject(new Error(message.error.message));
+ else pending?.resolve(message.result ?? {});
+ return;
+ }
+ for (const listener of this.#listeners) listener(message);
+ });
+ }
+
+ static async connect(endpoint: string): Promise {
+ let url = endpoint;
+ if (/^https?:/u.test(url)) {
+ const version = await (await fetch(`${url.replace(/\/+$/u, '')}/json/version`)).json() as { webSocketDebuggerUrl: string };
+ url = version.webSocketDebuggerUrl;
+ }
+ const socket = new WebSocket(url);
+ await new Promise((resolve, reject) => {
+ socket.addEventListener('open', () => resolve(), { once: true });
+ socket.addEventListener('error', () => reject(new Error('Cannot reach the browser (CDP)')), { once: true });
+ });
+ return new Cdp(socket);
+ }
+
+ send(method: string, params: Record = {}, sessionId?: string): Promise> {
+ const id = this.#next++;
+ return new Promise((resolve, reject) => {
+ this.#pending.set(id, { resolve, reject });
+ this.#socket.send(JSON.stringify({ id, method, params, ...(sessionId === undefined ? {} : { sessionId }) }));
+ setTimeout(() => {
+ if (this.#pending.delete(id)) reject(new Error(`${method} timed out`));
+ }, 30_000);
+ });
+ }
+
+ on(listener: (message: CdpMessage) => void): () => void {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ }
+
+ close(): void {
+ this.#socket.close();
+ }
+}
+
+const sleep = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Runs in the app frame: the visible interactive elements, outermost first. */
+const LIST_ELEMENTS = `(() => {
+ const SEMANTIC = 'button, a[href], [role=button], [role=tab], [role=switch], [role=link], [role=menuitem], [role=checkbox], [role=radio], input:not([type=hidden]), select, textarea, summary, label[for], [onclick]';
+ const path = (el) => {
+ const parts = [];
+ for (let node = el; node && node !== document.body; node = node.parentElement) {
+ let index = 1;
+ for (let sibling = node.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
+ if (sibling.tagName === node.tagName) index += 1;
+ }
+ parts.unshift(node.tagName.toLowerCase() + ':nth-of-type(' + index + ')');
+ }
+ return 'body > ' + parts.join(' > ');
+ };
+ const label = (el) => {
+ const text = (el.getAttribute('aria-label') || el.innerText || el.value || el.title || el.getAttribute('placeholder') || '').replace(/\\s+/g, ' ').trim();
+ const name = el.tagName.toLowerCase() + (el.classList.length ? '.' + [...el.classList].slice(0, 2).join('.') : '');
+ return text === '' ? name : name + ' "' + text.slice(0, 40) + '"';
+ };
+ const out = [];
+ const taken = [];
+ for (const el of document.querySelectorAll('body *')) {
+ const style = getComputedStyle(el);
+ const parentPointer = el.parentElement && getComputedStyle(el.parentElement).cursor === 'pointer';
+ const semantic = el.matches(SEMANTIC);
+ const pointer = style.cursor === 'pointer' && !parentPointer;
+ if (!semantic && !pointer) continue;
+ if (taken.some((outer) => outer.contains(el))) continue;
+ const r = el.getBoundingClientRect();
+ if (r.width < 4 || r.height < 4 || style.visibility === 'hidden' || Number(style.opacity) === 0) continue;
+ if (r.bottom <= 0 || r.right <= 0 || r.top >= innerHeight || r.left >= innerWidth) continue;
+ const x = Math.min(Math.max(r.left + r.width / 2, 1), innerWidth - 1);
+ const y = Math.min(Math.max(r.top + r.height / 2, 1), innerHeight - 1);
+ const hit = document.elementFromPoint(x, y);
+ if (!hit || !(hit === el || el.contains(hit))) continue;
+ taken.push(el);
+ out.push({
+ path: path(el), label: label(el), x, y,
+ disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true',
+ });
+ }
+ return out;
+})()`;
+
+/** Runs in the app frame: what a tap could have changed. */
+const SIGNATURE = `(() => {
+ let classes = '';
+ for (const el of document.querySelectorAll('body *')) classes += el.getAttribute('class') || '';
+ const heading = document.querySelector('h1, h2, [role=heading]');
+ const active = document.activeElement;
+ return {
+ focus: active && active !== document.body ? active.tagName + (active.getAttribute('name') || active.getAttribute('placeholder') || '') : '',
+ href: location.href,
+ history: history.length,
+ title: heading ? heading.textContent.trim().slice(0, 60) : '',
+ dom: document.body.innerText + '|' + document.querySelectorAll('body *').length + '|' + classes,
+ };
+})()`;
+
+interface Element {
+ readonly path: string;
+ readonly label: string;
+ readonly x: number;
+ readonly y: number;
+ readonly disabled: boolean;
+}
+
+interface Signature {
+ readonly focus: string;
+ readonly href: string;
+ readonly history: number;
+ readonly title: string;
+ readonly dom: string;
+}
+
+interface CallRecord {
+ readonly name: string;
+ readonly outcome: string;
+ readonly error?: string;
+ readonly ms?: number;
+}
+
+function matches(patterns: readonly string[], name: string): boolean {
+ return patterns.some((pattern) => (pattern.endsWith('*') ? name.startsWith(pattern.slice(0, -1)) : name === pattern));
+}
+
+export async function runTaps(options: TapOptions): Promise {
+ const log = options.log ?? (() => undefined);
+ const maxTaps = options.maxTaps ?? 120;
+ const cdp = await Cdp.connect(options.cdp);
+ const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' }) as { targetId: string };
+ const shots = join(tmpdir(), `miakapp-taps-${Date.now()}`);
+ mkdirSync(shots, { recursive: true });
+ try {
+ const { sessionId: page } = await cdp.send('Target.attachToTarget', { targetId, flatten: true }) as { sessionId: string };
+ // Every frame of the page, including the app's isolated frame (a target of its own).
+ const sessions = new Set([page]);
+ const contexts = new Map>();
+ const errors: string[] = [];
+ cdp.on((message) => {
+ if (message.method === 'Target.attachedToTarget') {
+ const child = (message.params as { sessionId: string }).sessionId;
+ sessions.add(child);
+ void cdp.send('Runtime.enable', {}, child).catch(() => undefined);
+ void cdp.send('Runtime.runIfWaitingForDebugger', {}, child).catch(() => undefined);
+ } else if (message.method === 'Runtime.executionContextCreated' && message.sessionId !== undefined) {
+ const context = (message.params as { context: { id: number; auxData?: { isDefault?: boolean } } }).context;
+ if (context.auxData?.isDefault !== true) return;
+ const set = contexts.get(message.sessionId) ?? new Set();
+ set.add(context.id);
+ contexts.set(message.sessionId, set);
+ } else if (message.method === 'Runtime.executionContextsCleared' && message.sessionId !== undefined) {
+ contexts.delete(message.sessionId);
+ } else if (message.method === 'Runtime.exceptionThrown') {
+ const details = (message.params as { exceptionDetails: { text: string; exception?: { description?: string } } }).exceptionDetails;
+ errors.push((details.exception?.description ?? details.text).split('\n')[0] ?? 'error');
+ } else if (message.method === 'Runtime.consoleAPICalled') {
+ const call = message.params as { type: string; args: { value?: unknown; description?: string }[] };
+ if (call.type === 'error') {
+ errors.push(call.args.map((arg) => String(arg.value ?? arg.description ?? '')).join(' ').slice(0, 200));
+ }
+ }
+ });
+ await cdp.send('Target.setAutoAttach', { autoAttach: true, waitForDebuggerOnStart: false, flatten: true }, page);
+ await cdp.send('Runtime.enable', {}, page);
+ await cdp.send('Page.enable', {}, page);
+ await cdp.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 }, page);
+
+ const evaluate = async (sessionId: string, expression: string, contextId?: number): Promise => {
+ const response = await cdp.send('Runtime.evaluate', {
+ expression, returnByValue: true, awaitPromise: true,
+ ...(contextId === undefined ? {} : { contextId }),
+ }, sessionId) as { result: { value?: T }; exceptionDetails?: { text: string } };
+ if (response.exceptionDetails !== undefined) throw new Error(response.exceptionDetails.text);
+ return response.result.value as T;
+ };
+
+ /** The app's frame: the default context where the bridge lives. */
+ const findApp = async (): Promise<{ session: string; context: number } | undefined> => {
+ for (const [session, ids] of contexts) {
+ for (const context of ids) {
+ try {
+ if (await evaluate(session, "typeof window.miakapp === 'object' && window.miakapp !== null && typeof window.miakapp.call === 'function'", context)) {
+ return { session, context };
+ }
+ } catch {
+ ids.delete(context);
+ }
+ }
+ }
+ return undefined;
+ };
+
+ const shell = (expression: string) => evaluate(page, expression);
+
+ const load = async (): Promise<{ session: string; context: number }> => {
+ const deadline = Date.now() + 30_000;
+ for (;;) {
+ const app = await findApp();
+ if (app !== undefined) {
+ // Ready: the shell says nothing about the connection, the app drew, and it holds still.
+ const ready = await shell("!document.querySelector('.house-bar__status')").catch(() => false);
+ const drawn = await evaluate(app.session, 'document.body.innerText.length', app.context).catch(() => 0);
+ if (ready && drawn > 0) {
+ let last = await evaluate(app.session, SIGNATURE, app.context);
+ for (let stable = 0; stable < 2 && Date.now() < deadline;) {
+ await sleep(500);
+ const next = await evaluate(app.session, SIGNATURE, app.context);
+ stable = next.dom === last.dom ? stable + 1 : 0;
+ last = next;
+ }
+ return app;
+ }
+ }
+ if (Date.now() > deadline) {
+ const status = await shell("document.querySelector('.house-bar__status')?.textContent ?? document.body.innerText.slice(0, 200)").catch(() => '');
+ throw new Error(`The home's app did not open within 30 s (${String(status).trim() || 'no app frame'})`);
+ }
+ await sleep(400);
+ }
+ };
+
+ const navigate = async (url: string): Promise => {
+ contexts.clear();
+ await cdp.send('Page.navigate', { url }, page);
+ };
+
+ log('opening the home…');
+ await navigate(options.url);
+ let app = await load();
+ const width = await evaluate(app.session, 'innerWidth', app.context);
+ const startupCalls = await shell('JSON.stringify(window.miakappTest?.calls ?? [])')
+ .then((raw) => (JSON.parse(String(raw)) as CallRecord[]).map(({ name, outcome, error, ms }) => ({
+ name, outcome, ...(error === undefined ? {} : { error }), ...(ms === undefined ? {} : { ms }),
+ })));
+ // Reloads keep the ticket (this tab's session storage), not the fragment.
+ const homeUrl = String(await shell('location.href'));
+
+ // Where the app's frame is on screen, and how much a test session shrank
+ // the phone to fit the window (the app itself stays 390 × 844).
+ const frameOffset = async (): Promise<{ x: number; y: number; scale: number }> => await shell(`(() => {
+ const frame = [...document.querySelectorAll('iframe')].find((f) => /app\\.html/.test(f.src)) ?? document.querySelector('iframe');
+ if (!frame) return { x: 0, y: 0, scale: 1 };
+ const r = frame.getBoundingClientRect();
+ const scale = frame.offsetWidth > 0 ? r.width / frame.offsetWidth : 1;
+ return { x: r.left + frame.clientLeft * scale, y: r.top + frame.clientTop * scale, scale };
+ })()`) as { x: number; y: number; scale: number };
+
+ const tapAt = async (x: number, y: number): Promise => {
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }, page);
+ await sleep(60);
+ await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }, page);
+ };
+
+ const tap = async (element: Element): Promise => {
+ const offset = await frameOffset();
+ await tapAt(offset.x + element.x * offset.scale, offset.y + element.y * offset.scale);
+ };
+
+ const screenshot = async (name: string): Promise => {
+ const scale = Number(await shell("Number(getComputedStyle(document.documentElement).getPropertyValue('--miakapp-test-scale')) || 1"));
+ const { data } = await cdp.send('Page.captureScreenshot', {
+ format: 'png', clip: { x: 0, y: 0, width: 390 * scale, height: 844 * scale, scale: 1 / scale },
+ }, page) as { data: string };
+ writeFileSync(join(shots, `${name}.png`), Buffer.from(data, 'base64'));
+ };
+
+ /** Back to a page: reload the home, then replay the taps that led there. */
+ const reach = async (path: readonly Element[]): Promise => {
+ await navigate(homeUrl);
+ app = await load();
+ for (const step of path) {
+ const found = await evaluate(app.session, LIST_ELEMENTS, app.context);
+ const element = found.find((candidate) => candidate.path === step.path) ?? found.find((candidate) => candidate.label === step.label);
+ if (element === undefined) throw new Error(`cannot find ${step.label} again`);
+ await tap(element);
+ await sleep(900);
+ app = (await findApp()) ?? app;
+ }
+ };
+
+ const taps: TapResult[] = [];
+ const queue: { name: string; path: Element[] }[] = [{ name: 'home', path: [] }];
+ const seenPages = new Set();
+ let pageCount = 0;
+
+ while (queue.length > 0 && taps.length < maxTaps) {
+ const current = queue.shift() as { name: string; path: Element[] };
+ if (current.path.length > 0) await reach(current.path);
+ const signature = await evaluate(app.session, SIGNATURE, app.context);
+ const pageKey = `${signature.href}|${signature.title}`;
+ if (seenPages.has(pageKey)) continue;
+ seenPages.add(pageKey);
+ pageCount += 1;
+ await screenshot(`page-${pageCount}`);
+ const elements = await evaluate(app.session, LIST_ELEMENTS, app.context);
+ log(`page ${pageCount} (${current.name}): ${elements.length} elements`);
+ let dirty = false;
+ for (const element of elements) {
+ if (taps.length >= maxTaps) break;
+ if (element.disabled) {
+ taps.push({ page: current.name, element: element.label, effect: 'disabled', calls: [], errors: [] });
+ continue;
+ }
+ if (dirty) {
+ await reach(current.path);
+ dirty = false;
+ }
+ const before = await evaluate(app.session, SIGNATURE, app.context);
+ const callsBefore = Number(await shell('window.miakappTest?.calls.length ?? 0'));
+ const errorsBefore = errors.length;
+ // The shell holds a call unless its name is in the list given to hold.
+ await shell(`window.miakappTest && (window.miakappTest.hold = (name) => !${JSON.stringify(options.send)}.some((p) => p.endsWith('*') ? name.startsWith(p.slice(0, -1)) : name === p))`);
+ await tap(element);
+ await sleep(900);
+ await shell('window.miakappTest && (window.miakappTest.hold = false)');
+ const frame = (await findApp()) ?? app;
+ app = frame;
+ const after = await evaluate(app.session, SIGNATURE, app.context).catch(() => before);
+ const newCalls = (JSON.parse(String(await shell(`JSON.stringify((window.miakappTest?.calls ?? []).slice(${callsBefore}))`))) as CallRecord[])
+ .map(({ name, outcome, error }) => ({ name, outcome, ...(error === undefined ? {} : { error }) }));
+ const navigated = after.href !== before.href || after.history !== before.history;
+ const changed = after.dom !== before.dom || (after.focus !== before.focus && after.focus !== '');
+ const effect: TapResult['effect'] = newCalls.length > 0 ? 'call' : navigated ? 'navigation' : changed ? 'change' : 'nothing';
+ taps.push({ page: current.name, element: element.label, effect, calls: newCalls, errors: errors.slice(errorsBefore) });
+ log(` ${effect.padEnd(10)} ${element.label}${newCalls.length > 0 ? ` → ${newCalls.map((call) => `${call.name} (${call.outcome})`).join(', ')}` : ''}`);
+ if (navigated && current.path.length < 3) {
+ queue.push({ name: `${current.name} › ${element.label}`, path: [...current.path, element] });
+ }
+ if (navigated || changed || newCalls.length > 0) dirty = true;
+ }
+ }
+
+ // A call the app sent by itself is reported with its real outcome.
+ return {
+ pages: pageCount,
+ taps,
+ startupCalls,
+ errors: [...new Set(errors)],
+ screenshots: shots,
+ width,
+ };
+ } finally {
+ await cdp.send('Target.closeTarget', { targetId }).catch(() => undefined);
+ cdp.close();
+ }
+}
+
+export { matches as matchesFunction };
diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.ts
index 0b7061e..37955b0 100644
--- a/packages/cli/src/version.ts
+++ b/packages/cli/src/version.ts
@@ -12,4 +12,4 @@
*/
export const PACKAGE_NAME = '@miakapp/cli';
-export const CLI_VERSION = '4.6.1';
+export const CLI_VERSION = '4.7.0';