Skip to content
TypeScript

feat(mobile): run the chrome e2e across poses on the device pool

Julius Marminged171a88fc4fa
diff --git a/scripts/mobile-e2e.ts b/scripts/mobile-e2e.ts
index 4d1c023d2d8..dc9af4a5e3b 100644
--- a/scripts/mobile-e2e.ts
+++ b/scripts/mobile-e2e.ts
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side simulator automation uses Node subprocess and timing APIs directly.
+// @effect-diagnostics nodeBuiltinImport:off globalDate:off - Host-side device automation uses Node subprocess and filesystem APIs directly.
import * as NodeChildProcess from "node:child_process";
import * as NodeFSP from "node:fs/promises";
@@ -8,630 +8,74 @@ import * as NodePath from "node:path";
import * as NodeProcess from "node:process";
import * as NodeURL from "node:url";
-import { startShowcaseEnvironments, stopProcess, waitForPort } from "./mobile-showcase.ts";
+import { Device, type Pool, run } from "./mobile-e2e/device.ts";
+import { runJourney, type StepResult } from "./mobile-e2e/journey.ts";
+import { POSES, type Pose } from "./mobile-e2e/poses.ts";
+import { failedChecks, poseFailed, type PoseResult, renderReport } from "./mobile-e2e/report.ts";
+import { reviewPose } from "./mobile-e2e/review.ts";
+import {
+ reserveAvailablePort,
+ startShowcaseEnvironments,
+ stopProcess,
+ waitForPort,
+} from "./mobile-showcase.ts";
import { SHOWCASE_ENVIRONMENTS } from "./mobile-showcase-environment.ts";
const REPO_ROOT = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
-const AGENT_DEVICE = NodePath.join(
- REPO_ROOT,
- "scripts/node_modules/agent-device/bin/agent-device.mjs",
-);
-const BUNDLE_ID = "com.t3tools.t3code.dev";
-const METRO_PORT = 8081;
-const AGENT_DEVICE_VERSION = (
- JSON.parse(
- await NodeFSP.readFile(
- NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/package.json"),
- "utf8",
- ),
- ) as { version: string }
-).version;
-// Persistent so the XCTest runner agent-device builds per simulator survives between runs;
-// per version because a daemon refuses clients of another version.
-const AGENT_DEVICE_STATE = NodePath.join(
- NodeOS.homedir(),
- ".cache/t3code/mobile-e2e",
- `agent-device-${AGENT_DEVICE_VERSION}`,
-);
-export interface E2eDevice {
- readonly id: string;
- readonly platform: "ios";
- readonly deviceType: string;
- readonly runtime: string;
-}
-
-const ios = (id: string, deviceType: string): E2eDevice => ({
- id,
- platform: "ios",
- deviceType: `com.apple.CoreSimulator.SimDeviceType.${deviceType}`,
- runtime: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",
-});
-
-export const DEVICES: ReadonlyArray<E2eDevice> = [
- ios("iphone-se", "iPhone-SE-3rd-generation"),
- ios("iphone-13-mini", "iPhone-13-mini"),
- ios("iphone-17", "iPhone-17"),
- ios("iphone-17-pro", "iPhone-17-Pro"),
- ios("iphone-17-pro-max", "iPhone-17-Pro-Max"),
- ios("iphone-air", "iPhone-Air"),
-];
-
-interface Rect {
- readonly x: number;
- readonly y: number;
- readonly width: number;
- readonly height: number;
-}
-
-export interface SnapshotNode {
- readonly type?: string;
- readonly role?: string;
- readonly identifier?: string;
- readonly label?: string;
- readonly rect?: Rect;
-}
-
-export interface Snapshot {
- readonly nodes: ReadonlyArray<SnapshotNode>;
- readonly viewport: { readonly width: number; readonly height: number };
-}
-
-export interface Check {
- readonly name: string;
- readonly pass: boolean;
- readonly detail: string;
-}
-
-interface StepResult {
- readonly name: string;
- readonly checks: ReadonlyArray<Check>;
- readonly screenshot?: string | undefined;
- readonly video?: string | undefined;
- readonly contactSheet?: string | undefined;
- readonly lagFrame?: string | undefined;
- readonly samples: number;
-}
-
-interface DeviceResult {
- readonly device: E2eDevice;
- readonly label: string;
- readonly steps: ReadonlyArray<StepResult>;
- readonly error?: string;
-}
-
-const onScreen = (node: SnapshotNode, snapshot: Snapshot) =>
- node.rect !== undefined &&
- node.rect.width > 0 &&
- node.rect.height > 0 &&
- node.rect.x < snapshot.viewport.width &&
- node.rect.y < snapshot.viewport.height &&
- node.rect.x + node.rect.width > 0 &&
- node.rect.y + node.rect.height > 0;
-
-const find = (snapshot: Snapshot, match: (node: SnapshotNode) => boolean) =>
- snapshot.nodes.filter((node) => match(node) && onScreen(node, snapshot));
-
-export const chrome = (snapshot: Snapshot) => ({
- tabBar: find(snapshot, (node) => node.type === "TabBar")[0],
- navigationBar: find(snapshot, (node) => node.type === "NavigationBar")[0],
- backButton: find(snapshot, (node) => node.identifier === "BackButton")[0],
- send: find(snapshot, (node) => node.type === "Button" && node.label === "Send")[0],
- newChat: find(snapshot, (node) => node.type === "Button" && node.label === "New chat")[0],
- // Thread rows are full-width context-menu wrappers; the filter pills are narrow ones.
- threadRows: find(
- snapshot,
- (node) =>
- node.role === "MenuView" &&
- Boolean(node.label) &&
- (node.rect?.width ?? 0) >= snapshot.viewport.width * 0.9,
- ),
-});
-
-const check = (name: string, pass: boolean, detail: string): Check => ({ name, pass, detail });
-const describeRect = (rect: Rect | undefined) =>
- rect
- ? `${Math.round(rect.x)},${Math.round(rect.y)} ${Math.round(rect.width)}×${Math.round(rect.height)}`
- : "absent";
-const inside = (rect: Rect, snapshot: Snapshot) =>
- rect.x >= 0 &&
- rect.y >= 0 &&
- rect.x + rect.width <= snapshot.viewport.width + 0.5 &&
- rect.y + rect.height <= snapshot.viewport.height + 0.5;
-
-export function homeChecks(snapshot: Snapshot): Check[] {
- const { tabBar, newChat } = chrome(snapshot);
- return [
- check("tab bar visible", tabBar !== undefined, describeRect(tabBar?.rect)),
- check(
- "tab bar inside the screen",
- tabBar?.rect !== undefined && inside(tabBar.rect, snapshot),
- describeRect(tabBar?.rect),
- ),
- check("new chat button visible", newChat !== undefined, describeRect(newChat?.rect)),
- ];
-}
-
-export function threadChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
- const { tabBar, backButton, send } = chrome(snapshot);
- const overlapping = samples.filter((sample) => {
- const state = chrome(sample);
- return state.backButton !== undefined && state.tabBar !== undefined;
- }).length;
- return [
- check("tab bar hidden", tabBar === undefined, describeRect(tabBar?.rect)),
- check("back button visible", backButton !== undefined, describeRect(backButton?.rect)),
- check(
- "composer inside the screen",
- send?.rect !== undefined && inside(send.rect, snapshot),
- describeRect(send?.rect),
- ),
- check(
- "no tabs over the entering thread",
- overlapping === 0,
- `${overlapping} of ${samples.length} transition samples showed tabs with a Back button`,
- ),
- ];
-}
-
-export function backChecks(snapshot: Snapshot, samples: ReadonlyArray<Snapshot>): Check[] {
- const listWithoutTabs = samples.filter((sample) => {
- const state = chrome(sample);
- return (
- state.backButton === undefined && state.newChat !== undefined && state.tabBar === undefined
- );
- }).length;
- return [
- ...homeChecks(snapshot),
- check(
- "tabs return with the list",
- listWithoutTabs === 0,
- `${listWithoutTabs} of ${samples.length} transition samples showed the list without tabs`,
- ),
- ];
-}
-
-/** Downsampled grayscale crops of one region, one per video frame (or one for a PNG). */
-async function grayFrames(input: string, region: Rect, scale: number): Promise<Uint8Array[]> {
- const even = (value: number) => Math.max(2, Math.floor(value / 2) * 2);
- const [x, y, width, height] = [
- Math.round(region.x * scale),
- Math.round(region.y * scale),
- even(region.width * scale),
- even(region.height * scale),
- ];
- const [outWidth, outHeight] = [even(width / 6), even(height / 6)];
- const bytes = await new Promise<Buffer>((resolve, reject) => {
- const child = NodeChildProcess.spawn(
- "ffmpeg",
- [
- "-v",
- "error",
- "-i",
- input,
- // One output frame per recorded frame, so indices match select=eq(n,…) for evidence.
- "-fps_mode",
- "passthrough",
- "-vf",
- `crop=${width}:${height}:${x}:${y},scale=${outWidth}:${outHeight},format=gray`,
- "-f",
- "rawvideo",
- "-",
- ],
- { stdio: ["ignore", "pipe", "pipe"] },
- );
- const chunks: Buffer[] = [];
- let stderr = "";
- child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
- child.stderr.on("data", (chunk) => (stderr += chunk));
- child.on("error", reject);
- child.on("close", (code) =>
- code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`ffmpeg failed: ${stderr}`)),
- );
- });
- const size = outWidth * outHeight;
- return Array.from({ length: Math.floor(bytes.length / size) }, (_, index) =>
- bytes.subarray(index * size, (index + 1) * size),
- );
-}
-
-const distance = (a: Uint8Array, b: Uint8Array) => {
- let sum = 0;
- for (let index = 0; index < a.length; index++) sum += Math.abs(a[index]! - b[index]!);
- return sum / a.length;
-};
-
-/** How far a region has moved from its origin toward its destination look, 0 to 1. */
-export interface FrameProgress {
- readonly nav: number;
- readonly chrome: number;
-}
-
-/**
- * A frame lags when the navigation bar is well into the transition while the tab bar region
- * still looks like the origin: tabs lingering over an entering thread, or a returned list drawn
- * before its tabs.
- */
-export const chromeLags = (frame: FrameProgress) => frame.nav > 0.3 && frame.chrome < 0.4;
-// One lagging frame is capture jitter; a regression lasts several.
-const LAG_FRAME_LIMIT = 2;
-
-const progress = (origin: number, destination: number) =>
- origin + destination === 0 ? 0 : origin / (origin + destination);
-
-async function chromeLagFrames(input: {
- readonly video: string;
- readonly origin: string;
- readonly destination: string;
- readonly nav: Rect;
- readonly chrome: Rect;
- readonly scale: number;
-}) {
- const [
- navFrames,
- chromeFrames,
- [navOrigin],
- [navDestination],
- [chromeOrigin],
- [chromeDestination],
- ] = await Promise.all([
- grayFrames(input.video, input.nav, input.scale),
- grayFrames(input.video, input.chrome, input.scale),
- grayFrames(input.origin, input.nav, input.scale),
- grayFrames(input.destination, input.nav, input.scale),
- grayFrames(input.origin, input.chrome, input.scale),
- grayFrames(input.destination, input.chrome, input.scale),
- ]);
- if (!navOrigin || !navDestination || !chromeOrigin || !chromeDestination)
- throw new Error("Could not read the reference screenshots.");
- const verdicts = navFrames.map((nav, index) => {
- const chrome = chromeFrames[index]!;
- return {
- nav: progress(distance(nav, navOrigin), distance(nav, navDestination)),
- chrome: progress(distance(chrome, chromeOrigin), distance(chrome, chromeDestination)),
- };
- });
- return verdicts.flatMap((verdict, index) => (chromeLags(verdict) ? [index] : []));
-}
-
-async function saveFrame(video: string, index: number, path: string) {
- await run("ffmpeg", [
- "-v",
- "error",
- "-y",
- "-i",
- video,
- "-vf",
- `select=eq(n\\,${index})`,
- "-frames:v",
- "1",
- path,
- ]);
-}
-
-async function lagCheck(
- name: string,
- input: Parameters<typeof chromeLagFrames>[0],
- evidence: string,
-): Promise<{ check: Check; frame?: string }> {
- const lagging = await chromeLagFrames(input);
- if (lagging.length < LAG_FRAME_LIMIT)
- return { check: check(name, true, `${lagging.length} lagging video frames`) };
- await saveFrame(input.video, lagging[0]!, evidence);
- return {
- check: check(name, false, `${lagging.length} video frames (first #${lagging[0]})`),
- frame: evidence,
- };
-}
-
-function run(
- command: string,
- args: ReadonlyArray<string>,
- options: { readonly env?: NodeJS.ProcessEnv; readonly allowFailure?: boolean } = {},
-): Promise<{ readonly code: number; readonly stdout: string; readonly stderr: string }> {
- return new Promise((resolve, reject) => {
- const child = NodeChildProcess.spawn(command, args, {
- cwd: REPO_ROOT,
- env: options.env ?? NodeProcess.env,
- stdio: ["ignore", "pipe", "pipe"],
- });
- let stdout = "";
- let stderr = "";
- child.stdout.on("data", (chunk) => (stdout += chunk));
- child.stderr.on("data", (chunk) => (stderr += chunk));
- child.on("error", reject);
- child.on("close", (code) => {
- if (code !== 0 && !options.allowFailure)
- reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${stderr || stdout}`));
- else resolve({ code: code ?? 1, stdout, stderr });
- });
- });
-}
-
-const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
-
-class Device {
- readonly spec: E2eDevice;
- readonly udid: string;
-
- constructor(spec: E2eDevice, udid: string) {
- this.spec = spec;
- this.udid = udid;
- }
-
- async agent(args: ReadonlyArray<string>): Promise<Record<string, unknown>> {
- const { stdout } = await run(
- NodeProcess.execPath,
- [
- AGENT_DEVICE,
- ...args,
- "--platform",
- "ios",
- "--udid",
- this.udid,
- "--session",
- `t3-e2e-${this.spec.id}`,
- "--json",
- ],
- {
- env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
- allowFailure: true,
- },
- );
- const parsed = JSON.parse(stdout) as {
- success: boolean;
- data?: Record<string, unknown>;
- error?: { message: string };
- };
- if (!parsed.success) throw new Error(`agent-device ${args[0]}: ${parsed.error?.message}`);
- return parsed.data ?? {};
- }
-
- async snapshot(): Promise<Snapshot> {
- return (await this.agent(["snapshot"])) as unknown as Snapshot;
- }
-
- async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
- const deadline = Date.now() + timeoutMs;
- let last: Snapshot | null = null;
- while (Date.now() < deadline) {
- last = await this.snapshot().catch(() => null);
- if (last && predicate(last)) return last;
- await delay(500);
- }
- throw new Error(`${this.spec.id}: timed out waiting for ${label}`);
- }
-
- /** Open a URL the way a user would; iOS asks before opening a custom scheme from another app. */
- async openUrl(url: string) {
- await run("xcrun", ["simctl", "openurl", this.udid, url]);
- await delay(1_500);
- await this.agent(["alert", "accept"]).catch(() => undefined);
- }
-
- async screenshot(path: string) {
- await run("xcrun", ["simctl", "io", this.udid, "screenshot", path]);
- }
-
- /** Run an action while recording and sampling the accessibility tree until the screen settles. */
- async transition(directory: string, name: string, action: () => Promise<unknown>) {
- const video = NodePath.join(directory, `${name}.mp4`);
- await this.agent(["record", "start", video, "--hide-touches"]);
- const samples: Snapshot[] = [];
- const sampling = { active: true };
- const sampler = (async () => {
- while (sampling.active) {
- const sample = await this.snapshot().catch(() => null);
- if (sample) samples.push(sample);
- }
- })();
- try {
- await action();
- await delay(2_000);
- } finally {
- sampling.active = false;
- await sampler;
- await this.agent(["record", "stop"]).catch(() => undefined);
- }
- const contactSheet = NodePath.join(directory, `${name}-frames.png`);
- const sheet = await run(
- NodeProcess.execPath,
- [AGENT_DEVICE, "record", "contact-sheet", video, "--out", contactSheet],
- {
- env: { ...NodeProcess.env, AGENT_DEVICE_STATE_DIR: AGENT_DEVICE_STATE },
- allowFailure: true,
- },
- );
- return { samples, video, contactSheet: sheet.code === 0 ? contactSheet : undefined };
- }
-}
-
-/** Screenshot pixels per snapshot point (3 on most iPhones). */
-async function screenshotScale(path: string, snapshot: Snapshot): Promise<number> {
- const { stdout } = await run("ffprobe", [
- "-v",
- "error",
- "-select_streams",
- "v:0",
- "-show_entries",
- "stream=width",
- "-of",
- "csv=p=0",
- path,
- ]);
- return Number(stdout.trim()) / snapshot.viewport.width;
-}
-
-async function ensureSimulator(spec: E2eDevice): Promise<string> {
- const name = `T3 E2E ${spec.id}`;
- const listing = JSON.parse(
- (await run("xcrun", ["simctl", "list", "devices", "available", "-j"])).stdout,
- ) as { devices: Record<string, ReadonlyArray<{ udid: string; name: string; state: string }>> };
- const existing = (listing.devices[spec.runtime] ?? []).find((device) => device.name === name);
- const udid =
- existing?.udid ??
- (await run("xcrun", ["simctl", "create", name, spec.deviceType, spec.runtime])).stdout.trim();
- if (existing?.state !== "Booted")
- await run("xcrun", ["simctl", "boot", udid], { allowFailure: true });
- await run("xcrun", ["simctl", "bootstatus", udid, "-b"]);
- await run("xcrun", ["simctl", "ui", udid, "appearance", "light"]);
- await run("xcrun", [
- "simctl",
- "status_bar",
- udid,
- "override",
- "--time",
- "9:41",
- "--batteryState",
- "charged",
- "--batteryLevel",
- "100",
- ]);
- return udid;
-}
+const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
-function lanAddress(): string {
+/** This machine's Tailscale address (100.64.0.0/10), which pool devices reach it on. */
+function tailnetAddress(): string {
for (const addresses of Object.values(NodeOS.networkInterfaces())) {
for (const address of addresses ?? []) {
- if (address.family === "IPv4" && !address.internal && !address.address.startsWith("169.254."))
+ const [first, second] = address.address.split(".").map(Number);
+ if (address.family === "IPv4" && first === 100 && second! >= 64 && second! < 128)
return address.address;
}
}
- throw new Error("No LAN IPv4 address for the simulator to reach Metro.");
+ throw new Error("No Tailscale IPv4 address: pool devices reach Metro and the fixture over it.");
}
-async function runDevice(
- spec: E2eDevice,
- outputDirectory: string,
- environment: { readonly baseDir: string; readonly port: number },
- metroHost: string,
-): Promise<DeviceResult> {
- const steps: StepResult[] = [];
- const directory = NodePath.join(outputDirectory, spec.id);
- await NodeFSP.mkdir(directory, { recursive: true });
- try {
- const udid = await ensureSimulator(spec);
- const device = new Device(spec, udid);
- // A fresh install drops connections paired by earlier runs; the cached client reinstalls in seconds.
- await run("xcrun", ["simctl", "uninstall", udid, BUNDLE_ID], { allowFailure: true });
- log(spec.id, "installing the dev client");
- await run(NodeProcess.execPath, ["scripts/mobile-native-client.ts", "ensure", "ios", udid], {
- env: { ...NodeProcess.env, T3_NATIVE_CLIENT_CACHE: NodeProcess.env.T3_NATIVE_CLIENT_CACHE },
- });
- const metroUrl = encodeURIComponent(`http://${metroHost}:${METRO_PORT}`);
- await device.openUrl(
- `t3code-dev://expo-development-client/?url=${metroUrl}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
- );
- // Snapshots read through an agent-device app session; open attaches one to the running app.
- await device.agent(["open", BUNDLE_ID]);
- // The app ignores the pairing link until its JS has loaded and shown the workspace.
- await device.waitFor(
- (snapshot) => chrome(snapshot).newChat !== undefined,
- "the app to load",
- 120_000,
- );
- const paired = (snapshot: Snapshot) =>
- chrome(snapshot).tabBar !== undefined && chrome(snapshot).threadRows.length > 0;
- let home: Snapshot | null = null;
- for (let attempt = 1; attempt <= 2 && !home; attempt++) {
- log(spec.id, attempt === 1 ? "pairing" : "pairing again");
- const pairing = new URLSearchParams({
- pairingUrl: await issuePairUrl(environment),
- autoConnect: "1",
- });
- await device.openUrl(`t3code-dev://connections/new?${pairing}`);
- home = await device.waitFor(paired, "the paired thread list", 45_000).catch(() => null);
- }
- if (!home) throw new Error("The app did not show the fixture threads after pairing.");
- await delay(1_000);
- const homeShot = NodePath.join(directory, "home.png");
- await device.screenshot(homeShot);
- steps.push({ name: "home", checks: homeChecks(home), screenshot: homeShot, samples: 0 });
-
- log(spec.id, "opening a thread");
- const row = chrome(home).threadRows[0];
- if (!row?.label) throw new Error("No thread row to open.");
- const opened = await device.transition(directory, "open-thread", () =>
- device.agent(["press", `label=${JSON.stringify(row.label)}`]),
- );
- const thread = await device.waitFor(
- (snapshot) => chrome(snapshot).backButton !== undefined,
- "the thread screen",
- );
- const threadShot = NodePath.join(directory, "thread.png");
- await device.screenshot(threadShot);
- const { tabBar, navigationBar } = chrome(home);
- const scale = await screenshotScale(homeShot, home);
- const regions =
- tabBar?.rect && navigationBar?.rect ? { nav: navigationBar.rect, chrome: tabBar.rect } : null;
- const openLag = regions
- ? await lagCheck(
- "no tabs over the entering thread (video)",
- { video: opened.video, origin: homeShot, destination: threadShot, scale, ...regions },
- NodePath.join(directory, "open-thread-lag.png"),
- )
- : null;
- steps.push({
- name: "open thread",
- checks: [...threadChecks(thread, opened.samples), ...(openLag ? [openLag.check] : [])],
- lagFrame: openLag?.frame,
- screenshot: threadShot,
- video: opened.video,
- contactSheet: opened.contactSheet,
- samples: opened.samples.length,
- });
-
- log(spec.id, "going back");
- const back = await device.transition(directory, "back", () =>
- device.agent(["press", "id=BackButton"]),
- );
- const list = await device.waitFor(
- (snapshot) => chrome(snapshot).backButton === undefined,
- "the thread list",
- );
- const backShot = NodePath.join(directory, "back.png");
- await device.screenshot(backShot);
- const backLag = regions
- ? await lagCheck(
- "tabs return with the list (video)",
- { video: back.video, origin: threadShot, destination: backShot, scale, ...regions },
- NodePath.join(directory, "back-lag.png"),
- )
- : null;
- steps.push({
- name: "back",
- checks: [...backChecks(list, back.samples), ...(backLag ? [backLag.check] : [])],
- lagFrame: backLag?.frame,
- screenshot: backShot,
- video: back.video,
- contactSheet: back.contactSheet,
- samples: back.samples.length,
- });
- return { device: spec, label: spec.id, steps };
- } catch (error) {
- return {
- device: spec,
- label: spec.id,
- steps,
- error: error instanceof Error ? error.message : String(error),
- };
- }
+async function mapConcurrent<T, R>(
+ items: ReadonlyArray<T>,
+ limit: number,
+ task: (item: T) => Promise<R>,
+): Promise<R[]> {
+ const results: R[] = Array.from({ length: items.length });
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (next < items.length) {
+ const index = next++;
+ results[index] = await task(items[index]!);
+ }
+ }),
+ );
+ return results;
}
-async function issuePairUrl(environment: { readonly baseDir: string; readonly port: number }) {
- const { stdout } = await run(NodeProcess.execPath, [
- "apps/server/src/bin.ts",
- "auth",
- "pairing",
- "create",
- "--base-dir",
- environment.baseDir,
- "--base-url",
- `http://127.0.0.1:${environment.port}`,
- "--ttl",
- "15m",
- "--json",
- ]);
+async function issuePairUrl(
+ environment: { readonly baseDir: string; readonly port: number },
+ host: string,
+) {
+ const { stdout } = await run(
+ NodeProcess.execPath,
+ [
+ "apps/server/src/bin.ts",
+ "auth",
+ "pairing",
+ "create",
+ "--base-dir",
+ environment.baseDir,
+ "--base-url",
+ `http://${host}:${environment.port}`,
+ "--ttl",
+ "15m",
+ "--json",
+ ],
+ { cwd: REPO_ROOT },
+ );
const { pairUrl } = JSON.parse(
stdout.slice(stdout.indexOf("{"), stdout.lastIndexOf("}") + 1),
) as {
@@ -641,71 +85,109 @@ async function issuePairUrl(environment: { readonly baseDir: string; readonly po
return pairUrl;
}
-const log = (scope: string, message: string) => NodeProcess.stderr.write(`[${scope}] ${message}\n`);
-
-const escapeHtml = (value: string) =>
- value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
-
-function renderReport(results: ReadonlyArray<DeviceResult>, outputDirectory: string): string {
- const relative = (path: string | undefined) =>
- path ? escapeHtml(NodePath.relative(outputDirectory, path)) : "";
- const rows = results
- .map((result) => {
- const steps = result.steps
- .map((step) => {
- const checks = step.checks
- .map(
- (item) =>
- `<li class="${item.pass ? "pass" : "fail"}">${item.pass ? "✓" : "✗"} ${escapeHtml(item.name)} <small>${escapeHtml(item.detail)}</small></li>`,
- )
- .join("");
- const media = [
- step.screenshot
- ? `<a href="${relative(step.screenshot)}"><img src="${relative(step.screenshot)}"></a>`
- : "",
- step.lagFrame
- ? `<a href="${relative(step.lagFrame)}"><img class="lag" src="${relative(step.lagFrame)}"></a>`
- : "",
- step.contactSheet
- ? `<a href="${relative(step.contactSheet)}">transition frames</a>`
- : "",
- step.video ? `<a href="${relative(step.video)}">video</a>` : "",
- ].join(" ");
- return `<td><h3>${escapeHtml(step.name)}</h3><ul>${checks}</ul>${media}</td>`;
- })
- .join("");
- const error = result.error ? `<td class="fail">${escapeHtml(result.error)}</td>` : "";
- return `<tr><th>${escapeHtml(result.label)}</th>${steps}${error}</tr>`;
- })
- .join("");
- const failures = results.filter(
- (result) => result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
- ).length;
- return `<!doctype html><meta charset="utf-8"><title>Mobile E2E</title>
-<style>body{font:14px system-ui;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:8px;vertical-align:top}img{width:180px;display:block;margin:6px 0}img.lag{outline:3px solid #b42318}.pass{color:#16794a}.fail{color:#b42318}ul{padding-left:16px;margin:4px 0}small{color:#666}</style>
-<h1>Mobile E2E · ${failures === 0 ? "all devices passed" : `${failures} device(s) failed`}</h1>
-<table>${rows}</table>`;
+async function runPose(
+ pose: Pose,
+ pool: Pool,
+ runId: string,
+ outputDirectory: string,
+ metroUrl: string,
+ pair: () => Promise<string>,
+): Promise<PoseResult> {
+ const directory = NodePath.join(outputDirectory, pose.id);
+ await NodeFSP.mkdir(directory, { recursive: true });
+ const steps: StepResult[] = [];
+ let device: Device | null = null;
+ try {
+ log(pose.id, `leasing ${pose.device}`);
+ device = await Device.lease(pose, pool, runId);
+ log(pose.id, "installing the dev client");
+ await device.install();
+ await device.prepare();
+ await device.launch(metroUrl);
+ log(pose.id, "pairing and walking the app");
+ await runJourney(device, directory, pair, steps);
+ return { pose, steps };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!device) return { pose, steps, error: message };
+ // What the device showed when the journey stopped is usually the whole diagnosis.
+ const stopped = NodePath.join(directory, "stopped.png");
+ const shot = await device.screenshot(stopped).then(
+ () => stopped,
+ () => undefined,
+ );
+ const labels = await device.snapshot().then(
+ (snapshot) =>
+ snapshot.nodes
+ .map((node) => node.label)
+ .filter(Boolean)
+ .slice(0, 12)
+ .join(" | "),
+ () => "",
+ );
+ return {
+ pose,
+ steps,
+ error: labels ? `${message} (screen: ${labels})` : message,
+ ...(shot ? { stopped: shot } : {}),
+ };
+ } finally {
+ await device?.release();
+ }
}
async function main() {
const args = NodeProcess.argv.slice(2);
if (args.includes("--list")) {
- for (const device of DEVICES) NodeProcess.stdout.write(`${device.id}\n`);
+ for (const pose of POSES) NodeProcess.stdout.write(`${pose.id}\t${pose.device}\n`);
return;
}
- const selected = args.flatMap((arg, index) => (args[index - 1] === "--device" ? [arg] : []));
- const devices = selected.length
- ? DEVICES.filter((device) => selected.includes(device.id))
- : DEVICES;
- const unknown = selected.filter((id) => !DEVICES.some((device) => device.id === id));
- if (unknown.length) throw new Error(`Unknown device ${unknown.join(", ")}. Run with --list.`);
- const concurrencyArg = args[args.indexOf("--concurrency") + 1];
- const concurrency = args.includes("--concurrency") ? Number(concurrencyArg) : 3;
+ const values = (flag: string) =>
+ args.flatMap((arg, index) => (args[index - 1] === flag ? [arg] : []));
+ const selected = values("--pose");
+ const unknown = selected.filter((id) => !POSES.some((pose) => pose.id === id));
+ if (unknown.length) throw new Error(`Unknown pose ${unknown.join(", ")}. Run with --list.`);
+ const platforms = values("--platform");
+ const poses = POSES.filter(
+ (pose) =>
+ (selected.length === 0 || selected.includes(pose.id)) &&
+ (platforms.length === 0 || platforms.includes(pose.platform)),
+ );
+ const concurrencyFlag = values("--concurrency")[0];
+ const concurrency = concurrencyFlag ? Number(concurrencyFlag) : undefined;
+ const review = !args.includes("--no-review");
+
+ const agentDeviceUrl = NodeProcess.env.SIMLOCK_AGENT_DEVICE_URL;
+ const token = NodeProcess.env.AGENT_DEVICE_DAEMON_AUTH_TOKEN;
+ if (!agentDeviceUrl || !token)
+ throw new Error(
+ "Set SIMLOCK_AGENT_DEVICE_URL (<gateway>/v1/agent-device) and AGENT_DEVICE_DAEMON_AUTH_TOKEN (a Simlock agent token) to run on the device pool.",
+ );
+ const host = tailnetAddress();
- const stamp = new Date().toISOString().replaceAll(":", "-");
- const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", stamp);
+ const runId = new Date().toISOString().replaceAll(/[:.]/g, "-");
+ const outputDirectory = NodePath.join(REPO_ROOT, "artifacts/mobile-e2e", runId);
await NodeFSP.mkdir(outputDirectory, { recursive: true });
const rootDir = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-mobile-e2e-"));
+ const workspace = await NodeFSP.realpath(outputDirectory);
+ const config = NodePath.join(rootDir, "agent-device.json");
+ await NodeFSP.writeFile(
+ config,
+ JSON.stringify({
+ daemonBaseUrl: agentDeviceUrl,
+ daemonAuthToken: token,
+ stateDir: NodePath.join(rootDir, "agent-device"),
+ }),
+ { mode: 0o600 },
+ );
+ const pool: Pool = {
+ repoRoot: REPO_ROOT,
+ agentDevice: NodePath.join(REPO_ROOT, "scripts/node_modules/agent-device/bin/agent-device.mjs"),
+ agentDeviceUrl,
+ workspace,
+ env: { ...NodeProcess.env, AGENT_DEVICE_CONFIG: config, PWD: workspace },
+ };
+
const servers: NodeChildProcess.ChildProcess[] = [];
let metro: NodeChildProcess.ChildProcess | null = null;
try {
@@ -716,7 +198,7 @@ async function main() {
SHOWCASE_ENVIRONMENTS.slice(0, 1),
);
if (!environment) throw new Error("The fixture server did not start.");
- const metroHost = lanAddress();
+ const metroPort = await reserveAvailablePort();
metro = NodeChildProcess.spawn(
"vp",
[
@@ -728,7 +210,7 @@ async function main() {
"t3code-dev",
"--lan",
"--port",
- String(METRO_PORT),
+ String(metroPort),
],
{
cwd: NodePath.join(REPO_ROOT, "apps/mobile"),
@@ -738,53 +220,83 @@ async function main() {
detached: true,
},
);
- await waitForPort(METRO_PORT, "Metro", 120_000);
- await run("curl", [
- "-sf",
- "-o",
- "/dev/null",
- `http://127.0.0.1:${METRO_PORT}/apps/mobile/index.bundle?platform=ios&dev=true&minify=false`,
- ]);
+ await waitForPort(metroPort, "Metro", 120_000);
+ // Warm each platform's bundle once, instead of on every device at once.
+ for (const platform of new Set(poses.map((pose) => pose.platform))) {
+ log("e2e", `bundling for ${platform}`);
+ await run("curl", [
+ "-sf",
+ "-o",
+ "/dev/null",
+ `http://127.0.0.1:${metroPort}/apps/mobile/index.bundle?platform=${platform}&dev=true&minify=false`,
+ ]);
+ }
- // The first install may build; later ones reuse its artifact.
- const results: DeviceResult[] = [];
- const [first, ...rest] = devices;
- if (first) results.push(await runDevice(first, outputDirectory, environment, metroHost));
- for (let index = 0; index < rest.length; index += concurrency) {
- results.push(
- ...(await Promise.all(
- rest
- .slice(index, index + concurrency)
- .map((device) => runDevice(device, outputDirectory, environment, metroHost)),
- )),
+ const attempt = (pose: Pose, session: string) =>
+ runPose(pose, pool, session, outputDirectory, `http://${host}:${metroPort}`, () =>
+ issuePairUrl(environment, host),
);
- }
+ const runOne = async (pose: Pose) => {
+ const first = await attempt(pose, runId);
+ // A pose that failed before its first screen usually met the pool, not the app.
+ if (!first.error || first.steps.length > 0) return first;
+ log(pose.id, `retrying after: ${first.error.split("\n")[0]}`);
+ return attempt(pose, `${runId}-retry`);
+ };
+ // Each platform has its own workers, so each gets its own limit; one Mac runs every
+ // iOS simulator, and recording several at once on a shared pool times it out.
+ const byPlatform = await Promise.all(
+ (["ios", "android"] as const).map((platform) =>
+ mapConcurrent(
+ poses.filter((pose) => pose.platform === platform),
+ concurrency ?? (platform === "ios" ? 2 : 3),
+ runOne,
+ ),
+ ),
+ );
+ const results = poses.map((pose) => byPlatform.flat().find((result) => result.pose === pose)!);
+
+ const reviewed = review
+ ? await mapConcurrent(results, 4, async (result) => {
+ log(result.pose.id, "agent review");
+ const findings = await reviewPose(result, outputDirectory).catch((error) => {
+ log(result.pose.id, `review failed: ${error instanceof Error ? error.message : error}`);
+ return [];
+ });
+ return { ...result, findings };
+ })
+ : results;
+
const report = NodePath.join(outputDirectory, "index.html");
- await NodeFSP.writeFile(report, renderReport(results, outputDirectory));
+ await NodeFSP.writeFile(report, renderReport(reviewed, outputDirectory));
await NodeFSP.writeFile(
NodePath.join(outputDirectory, "report.json"),
- JSON.stringify(results, null, 2),
+ JSON.stringify(reviewed, null, 2),
);
- const failed = results.filter(
- (result) =>
- result.error || result.steps.some((step) => step.checks.some((item) => !item.pass)),
- );
- for (const result of results) {
- const failures = result.steps.flatMap((step) =>
- step.checks
- .filter((item) => !item.pass)
- .map((item) => `${step.name}: ${item.name} (${item.detail})`),
+ for (const result of reviewed) {
+ const failures = failedChecks(result).map(
+ (item) => `${item.step}: ${item.name} (${item.detail})`,
+ );
+ log(
+ result.pose.id,
+ [result.error, ...failures].filter(Boolean).join("; ") ||
+ `passed${result.findings?.length ? `, ${result.findings.length} review findings` : ""}`,
);
- log(result.label, result.error ?? (failures.length ? failures.join("; ") : "passed"));
}
+ const failed = reviewed.filter(poseFailed).length;
NodeProcess.stdout.write(
- `${JSON.stringify({ report, devices: results.length, failed: failed.length })}\n`,
+ `${JSON.stringify({
+ report,
+ poses: reviewed.length,
+ failed,
+ findings: reviewed.reduce((count, result) => count + (result.findings?.length ?? 0), 0),
+ })}\n`,
);
- process.exitCode = failed.length ? 1 : 0;
+ process.exitCode = failed ? 1 : 0;
} finally {
if (metro?.pid) {
try {
- process.kill(-metro.pid, "SIGTERM");
+ NodeProcess.kill(-metro.pid, "SIGTERM");
} catch {}
await stopProcess(metro);
}
diff --git a/scripts/mobile-e2e/checks.test.ts b/scripts/mobile-e2e/checks.test.ts
new file mode 100644
index 00000000000..8d8a756e922
--- /dev/null
+++ b/scripts/mobile-e2e/checks.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from "@effect/vitest";
+
+import { layoutChecks, type Snapshot, type SnapshotNode } from "./checks.ts";
+
+const APP = "com.t3tools.t3code.dev";
+const node = (index: number, fields: Omit<SnapshotNode, "index">): SnapshotNode => ({
+ index,
+ hittable: true,
+ kind: "button",
+ ...fields,
+});
+
+const failing = (snapshot: Snapshot) =>
+ Object.fromEntries(
+ layoutChecks(snapshot, APP)
+ .filter((item) => !item.pass)
+ .map((item) => [item.name, item.detail]),
+ );
+
+describe("layoutChecks", () => {
+ it("flags broken chrome but not scrolled content, nested controls or duplicates", () => {
+ const snapshot: Snapshot = {
+ appBundleId: APP,
+ viewport: { width: 400, height: 800 },
+ nodes: [
+ node(0, {
+ kind: "application",
+ hittable: false,
+ rect: { x: 0, y: 0, width: 400, height: 800 },
+ }),
+ node(1, {
+ kind: "scroll-area",
+ parentIndex: 0,
+ rect: { x: 0, y: 0, width: 400, height: 700 },
+ }),
+ node(2, {
+ label: "Row past the edge",
+ parentIndex: 1,
+ rect: { x: 0, y: 680, width: 400, height: 60 },
+ }),
+ node(3, { label: "Send", parentIndex: 0, rect: { x: 340, y: 770, width: 80, height: 40 } }),
+ node(4, {
+ label: "Card",
+ parentIndex: 0,
+ rect: { x: 10, y: 100, width: 200, height: 100 },
+ }),
+ node(5, { label: "Inner", parentIndex: 4, rect: { x: 20, y: 110, width: 50, height: 40 } }),
+ node(6, { label: "Twin", parentIndex: 0, rect: { x: 10, y: 300, width: 80, height: 40 } }),
+ node(7, { label: "Twin", parentIndex: 0, rect: { x: 10, y: 300, width: 80, height: 40 } }),
+ node(8, {
+ label: "Plan",
+ parentIndex: 0,
+ rect: { x: 100, y: 400, width: 100, height: 40 },
+ }),
+ node(9, {
+ label: "Stop",
+ parentIndex: 0,
+ rect: { x: 120, y: 405, width: 100, height: 40 },
+ }),
+ node(10, {
+ kind: "text-field",
+ label: "Message",
+ parentIndex: 0,
+ rect: { x: 0, y: 600, width: 300, height: 40 },
+ }),
+ node(12, {
+ label: "Row of a covered screen",
+ parentIndex: 1,
+ rect: { x: 100, y: 400, width: 100, height: 40 },
+ }),
+ node(11, {
+ kind: "keyboard",
+ hittable: false,
+ rect: { x: 0, y: 500, width: 400, height: 300 },
+ }),
+ ],
+ };
+
+ expect(failing(snapshot)).toEqual({
+ "no control cut off by the screen edge": '"Send" at 340,770 80×40',
+ "no controls stacked on each other": '"Plan" and "Stop"',
+ "no input under the keyboard": '"Message" at 0,600 300×40',
+ });
+ });
+
+ it("flags an error screen and controls under Android system bars", () => {
+ const snapshot: Snapshot = {
+ appBundleId: APP,
+ viewport: { width: 1080, height: 2400 },
+ nodes: [
+ node(0, {
+ kind: "text",
+ label: "Render Error",
+ rect: { x: 0, y: 200, width: 600, height: 60 },
+ }),
+ node(1, {
+ kind: "text",
+ systemBar: "status",
+ bundleId: "com.android.systemui",
+ rect: { x: 0, y: 0, width: 1080, height: 60 },
+ }),
+ node(2, {
+ label: "Search",
+ bundleId: APP,
+ rect: { x: 900, y: 10, width: 120, height: 80 },
+ }),
+ ],
+ };
+
+ expect(Object.keys(failing(snapshot))).toEqual([
+ "no error screen",
+ "no control under a system bar",
+ ]);
+ });
+});
diff --git a/scripts/mobile-e2e/checks.ts b/scripts/mobile-e2e/checks.ts
new file mode 100644
index 00000000000..adaaacddc52
--- /dev/null
+++ b/scripts/mobile-e2e/checks.ts
@@ -0,0 +1,203 @@
+export interface Rect {
+ readonly x: number;
+ readonly y: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+/** One node of an agent-device `snapshot --json`, on iOS or Android. */
+export interface SnapshotNode {
+ readonly index: number;
+ readonly parentIndex?: number;
+ /** Valid for commands until the next snapshot. */
+ readonly ref?: string;
+ readonly kind?: string;
+ readonly type?: string;
+ readonly label?: string;
+ readonly identifier?: string;
+ readonly rect?: Rect;
+ readonly hittable?: boolean;
+ readonly editable?: boolean;
+ readonly bundleId?: string;
+ readonly systemBar?: string;
+}
+
+export interface Snapshot {
+ readonly nodes: ReadonlyArray<SnapshotNode>;
+ readonly viewport: { readonly width: number; readonly height: number };
+ readonly appBundleId?: string;
+ readonly keyboard?: { readonly kind?: string; readonly rect?: Rect };
+}
+
+export interface Check {
+ readonly name: string;
+ readonly pass: boolean;
+ readonly detail: string;
+}
+
+export const check = (name: string, pass: boolean, detail: string): Check => ({
+ name,
+ pass,
+ detail,
+});
+
+// Kinds that are never controls a person taps; iOS also marks plain text hittable.
+const NOT_CONTROLS = new Set([
+ "application",
+ "text",
+ "image",
+ "scroll-area",
+ "other",
+ "toolbar",
+ "tab-bar",
+ "activity-indicator",
+ "composeview",
+ "keyboard",
+]);
+
+const area = (rect: Rect) => Math.max(0, rect.width) * Math.max(0, rect.height);
+
+const intersection = (a: Rect, b: Rect) =>
+ Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) *
+ Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y));
+
+export const describeRect = (rect: Rect | undefined) =>
+ rect
+ ? `${Math.round(rect.x)},${Math.round(rect.y)} ${Math.round(rect.width)}×${Math.round(rect.height)}`
+ : "absent";
+
+const name = (node: SnapshotNode) => node.label || node.identifier || node.type || "unlabelled";
+
+const appOwned = (node: SnapshotNode, snapshot: Snapshot) =>
+ !node.systemBar && (node.bundleId === undefined || node.bundleId === snapshot.appBundleId);
+
+const isControl = (node: SnapshotNode, snapshot: Snapshot) =>
+ node.hittable === true &&
+ node.rect !== undefined &&
+ area(node.rect) > 0 &&
+ !NOT_CONTROLS.has(node.kind ?? "") &&
+ appOwned(node, snapshot);
+
+function ancestors(node: SnapshotNode, snapshot: Snapshot): SnapshotNode[] {
+ const byIndex = new Map(snapshot.nodes.map((candidate) => [candidate.index, candidate]));
+ const chain: SnapshotNode[] = [];
+ for (let parent = node.parentIndex; parent !== undefined;) {
+ const next = byIndex.get(parent);
+ if (!next || chain.includes(next)) break;
+ chain.push(next);
+ parent = next.parentIndex;
+ }
+ return chain;
+}
+
+const viewportRect = (snapshot: Snapshot): Rect => ({ x: 0, y: 0, ...snapshot.viewport });
+
+export function keyboardRect(snapshot: Snapshot): Rect | undefined {
+ if (snapshot.keyboard?.rect) return snapshot.keyboard.rect;
+ return snapshot.nodes.find((node) => node.type === "Keyboard" || node.kind === "keyboard")?.rect;
+}
+
+const TAB_LABELS = new Set(["Chats", "Pulls", "Usage", "Settings"]);
+
+/** The bottom tab bar, as a native tab bar node or the union of its tab buttons. */
+export function tabBarRect(snapshot: Snapshot): Rect | undefined {
+ const native = snapshot.nodes.find((node) => node.kind === "tab-bar" && node.rect)?.rect;
+ if (native) return native;
+ const tabs = snapshot.nodes.filter(
+ (node) =>
+ node.rect &&
+ TAB_LABELS.has(node.label ?? "") &&
+ node.rect.y > snapshot.viewport.height * 0.7 &&
+ appOwned(node, snapshot),
+ );
+ if (tabs.length < 2) return undefined;
+ const left = Math.min(...tabs.map((tab) => tab.rect!.x));
+ const top = Math.min(...tabs.map((tab) => tab.rect!.y));
+ const right = Math.max(...tabs.map((tab) => tab.rect!.x + tab.rect!.width));
+ const bottom = Math.max(...tabs.map((tab) => tab.rect!.y + tab.rect!.height));
+ return { x: left, y: top, width: right - left, height: bottom - top };
+}
+
+const ERROR_TEXT =
+ /\b(Render Error|Uncaught Error|Unhandled JS Exception|Syntax Error|keeps stopping|isn't responding)\b/i;
+
+/**
+ * Checks every screen should pass, whatever it shows: the app is in front without an error
+ * screen, and no control is clipped by the screen edge, stacked on another control, under a
+ * system bar, or an input under the keyboard.
+ */
+export function layoutChecks(snapshot: Snapshot, bundleId: string): Check[] {
+ const viewport = viewportRect(snapshot);
+ const controls = snapshot.nodes.filter((node) => isControl(node, snapshot));
+ const errors = snapshot.nodes.filter((node) => ERROR_TEXT.test(node.label ?? ""));
+
+ const clipped = controls.filter((node) => {
+ const visible = intersection(node.rect!, viewport);
+ if (visible === 0 || visible >= area(node.rect!) * 0.98) return false;
+ // Content scrolled past the edge is expected; fixed chrome cut off by it is not.
+ return !ancestors(node, snapshot).some((parent) => parent.kind === "scroll-area");
+ });
+
+ // Only siblings: a screen covered by another stays in the tree, so cousins overlap
+ // legitimately. Native tab items report overlapping frames.
+ const siblings = controls.filter(
+ (node) => !ancestors(node, snapshot).some((parent) => parent.kind === "tab-bar"),
+ );
+ const stacked: string[] = [];
+ for (const [index, a] of siblings.entries()) {
+ for (const b of siblings.slice(index + 1)) {
+ if (a.parentIndex !== b.parentIndex) continue;
+ const shared = intersection(a.rect!, b.rect!);
+ if (shared < Math.min(area(a.rect!), area(b.rect!)) * 0.25) continue;
+ // iOS exposes some elements twice, at the same frame.
+ const same =
+ describeRect(a.rect) === describeRect(b.rect) &&
+ (!a.label || !b.label || a.label === b.label);
+ if (!same) stacked.push(`"${name(a)}" and "${name(b)}"`);
+ }
+ }
+
+ const bars = snapshot.nodes.filter((node) => node.systemBar && node.rect);
+ const underBars = controls.filter((node) =>
+ bars.some((bar) => intersection(node.rect!, bar.rect!) > area(node.rect!) * 0.3),
+ );
+
+ const keyboard = keyboardRect(snapshot);
+ const coveredInputs = keyboard
+ ? snapshot.nodes.filter(
+ (node) =>
+ (node.kind === "text-field" || node.editable === true) &&
+ node.rect &&
+ appOwned(node, snapshot) &&
+ intersection(node.rect, keyboard) > area(node.rect) * 0.3,
+ )
+ : [];
+
+ const list = (nodes: ReadonlyArray<SnapshotNode>) =>
+ nodes.map((node) => `"${name(node)}" at ${describeRect(node.rect)}`).join(", ");
+ return [
+ check(
+ "app in front",
+ snapshot.appBundleId === undefined || snapshot.appBundleId === bundleId,
+ snapshot.appBundleId ?? "unknown",
+ ),
+ check("no error screen", errors.length === 0, errors.map(name).join(", ") || "none"),
+ check("no control cut off by the screen edge", clipped.length === 0, list(clipped) || "none"),
+ check("no controls stacked on each other", stacked.length === 0, stacked.join("; ") || "none"),
+ check("no control under a system bar", underBars.length === 0, list(underBars) || "none"),
+ check(
+ "no input under the keyboard",
+ coveredInputs.length === 0,
+ keyboard ? list(coveredInputs) || "none" : "no keyboard",
+ ),
+ ];
+}
+
+export const findLabel = (snapshot: Snapshot, pattern: RegExp) =>
+ snapshot.nodes.find(
+ (node) =>
+ node.rect &&
+ pattern.test(node.label ?? "") &&
+ intersection(node.rect, viewportRect(snapshot)) > 0 &&
+ appOwned(node, snapshot),
+ );
diff --git a/scripts/mobile-e2e/device.ts b/scripts/mobile-e2e/device.ts
new file mode 100644
index 00000000000..9397d739a3c
--- /dev/null
+++ b/scripts/mobile-e2e/device.ts
@@ -0,0 +1,229 @@
+// @effect-diagnostics nodeBuiltinImport:off globalTimers:off globalDate:off - Host-side device automation uses Node subprocess and timing APIs directly.
+
+import * as NodeChildProcess from "node:child_process";
+import * as NodePath from "node:path";
+import * as NodeProcess from "node:process";
+
+import type { Snapshot } from "./checks.ts";
+import type { Pose } from "./poses.ts";
+
+export const BUNDLE_ID = "com.t3tools.t3code.dev";
+
+export interface RunResult {
+ readonly code: number;
+ readonly stdout: string;
+ readonly stderr: string;
+}
+
+export function run(
+ command: string,
+ args: ReadonlyArray<string>,
+ options: {
+ readonly cwd?: string;
+ readonly env?: NodeJS.ProcessEnv;
+ readonly allowFailure?: boolean;
+ readonly timeoutMs?: number;
+ } = {},
+): Promise<RunResult> {
+ return new Promise((resolve, reject) => {
+ const child = NodeChildProcess.spawn(command, args, {
+ ...(options.cwd ? { cwd: options.cwd } : {}),
+ env: options.env ?? NodeProcess.env,
+ stdio: ["ignore", "pipe", "pipe"],
+ ...(options.timeoutMs ? { timeout: options.timeoutMs } : {}),
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => (stdout += chunk));
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ child.on("error", reject);
+ child.on("close", (code) => {
+ if (code !== 0 && !options.allowFailure)
+ reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${stderr || stdout}`));
+ else resolve({ code: code ?? 1, stdout, stderr });
+ });
+ });
+}
+
+export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** How this run reaches the pool: one agent-device config, from one workspace. */
+export interface Pool {
+ readonly repoRoot: string;
+ readonly agentDevice: string;
+ /** The gateway's agent-device front, `<gateway>/v1/agent-device`. */
+ readonly agentDeviceUrl: string;
+ /**
+ * agent-device ties a lease to the workspace it was opened from and reads it from both the
+ * real cwd and $PWD, so every command runs from this real path with a matching PWD.
+ */
+ readonly workspace: string;
+ readonly env: NodeJS.ProcessEnv;
+}
+
+export class AgentDeviceError extends Error {}
+
+// A shared pool's workers drop off the gateway and stall under load for seconds at a time.
+const TRANSIENT =
+ /Remote daemon is unavailable|not connected to the gateway|still finishing a previous command|Invalid daemon response|Daemon request timed out/i;
+
+export class Device {
+ readonly pose: Pose;
+ readonly session: string;
+ readonly pool: Pool;
+
+ private constructor(pose: Pose, session: string, pool: Pool) {
+ this.pose = pose;
+ this.session = session;
+ this.pool = pool;
+ }
+
+ /** Leases a device for the pose; `open` waits in the pool's queue while every match is busy. */
+ static async lease(pose: Pose, pool: Pool, runId: string): Promise<Device> {
+ const device = new Device(pose, `t3-e2e-${runId}-${pose.id}`, pool);
+ await device.agent(["connect", "proxy", "--daemon-base-url", pool.agentDeviceUrl]);
+ await device.agent(
+ [
+ "open",
+ "--platform",
+ pose.platform,
+ "--device",
+ pose.device,
+ // A real keyboard, so the layout under it is what people see.
+ ...(pose.platform === "android" ? ["--no-test-ime"] : []),
+ ],
+ { timeoutMs: 420_000 },
+ );
+ return device;
+ }
+
+ async agent(
+ args: ReadonlyArray<string>,
+ options: { readonly timeoutMs?: number } = {},
+ ): Promise<Record<string, unknown>> {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ return await this.agentOnce(args, options);
+ } catch (error) {
+ if (attempt >= 3 || !(error instanceof AgentDeviceError) || !TRANSIENT.test(error.message))
+ throw error;
+ await delay(3_000 * attempt);
+ }
+ }
+ }
+
+ private async agentOnce(
+ args: ReadonlyArray<string>,
+ options: { readonly timeoutMs?: number },
+ ): Promise<Record<string, unknown>> {
+ const { stdout, stderr } = await run(
+ NodeProcess.execPath,
+ [this.pool.agentDevice, ...args, "--session", this.session, "--json"],
+ {
+ cwd: this.pool.workspace,
+ env: this.pool.env,
+ allowFailure: true,
+ timeoutMs: options.timeoutMs ?? 120_000,
+ },
+ );
+ let parsed: { success: boolean; data?: Record<string, unknown>; error?: { message: string } };
+ try {
+ parsed = JSON.parse(stdout);
+ } catch {
+ throw new AgentDeviceError(`agent-device ${args[0]}: ${(stderr || stdout).slice(-400)}`);
+ }
+ if (!parsed.success)
+ throw new AgentDeviceError(`agent-device ${args.join(" ")}: ${parsed.error?.message}`);
+ return parsed.data ?? {};
+ }
+
+ /** The shared-cache dev client for this checkout; the worker downloads it itself. */
+ async install() {
+ await run(
+ NodeProcess.execPath,
+ [
+ NodePath.join(this.pool.repoRoot, "scripts/mobile-native-client.ts"),
+ "ensure",
+ this.pose.platform,
+ "--session",
+ this.session,
+ ],
+ { cwd: this.pool.workspace, env: this.pool.env, timeoutMs: 600_000 },
+ );
+ }
+
+ /** Device settings that must be in place before the app starts. */
+ async prepare() {
+ await this.agent(["settings", "appearance", this.pose.appearance]);
+ if (this.pose.textSize) await this.agent(["settings", "text-size", this.pose.textSize]);
+ if (this.pose.fold) await this.agent(["fold", this.pose.fold]);
+ }
+
+ async launch(metroUrl: string) {
+ const url = encodeURIComponent(metroUrl);
+ await this.agent(
+ [
+ "open",
+ BUNDLE_ID,
+ `t3code-dev://expo-development-client/?url=${url}&disableOnboarding=1&disableFab=1&disableAutoLaunch=1`,
+ // A real keyboard, so the layout under it is what people see.
+ ...(this.pose.platform === "android" ? ["--no-test-ime"] : []),
+ ],
+ { timeoutMs: 180_000 },
+ );
+ await this.acceptOpenPrompt();
+ if (this.pose.landscape) await this.agent(["orientation", "landscape-left"]);
+ }
+
+ async openUrl(url: string) {
+ await this.agent(["open", BUNDLE_ID, url]);
+ await this.acceptOpenPrompt();
+ }
+
+ /** iOS asks before another app opens a custom scheme, and agent-device does not always answer. */
+ private async acceptOpenPrompt() {
+ if (this.pose.platform !== "ios") return;
+ await delay(1_500);
+ await this.agent(["alert", "accept"]).catch(() => undefined);
+ }
+
+ async snapshot(): Promise<Snapshot> {
+ return (await this.agent(["snapshot"])) as unknown as Snapshot;
+ }
+
+ async waitFor(predicate: (snapshot: Snapshot) => boolean, label: string, timeoutMs = 60_000) {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const snapshot = await this.snapshot().catch(() => null);
+ if (snapshot && predicate(snapshot)) return snapshot;
+ await delay(750);
+ }
+ throw new Error(`timed out waiting for ${label}`);
+ }
+
+ async screenshot(path: string) {
+ // iOS defaults to 1x points, too coarse for anyone reviewing the screenshot.
+ await this.agent([
+ "screenshot",
+ path,
+ ...(this.pose.platform === "ios" ? ["--pixel-density", "2"] : []),
+ ]);
+ }
+
+ /** Runs an action while recording, so transitions can be checked frame by frame. */
+ async recorded(directory: string, name: string, action: () => Promise<unknown>) {
+ const video = NodePath.join(directory, `${name}.mp4`);
+ await this.agent(["record", "start", video, "--hide-touches"]);
+ try {
+ await action();
+ await delay(2_000);
+ } finally {
+ await this.agent(["record", "stop"], { timeoutMs: 180_000 }).catch(() => undefined);
+ }
+ return video;
+ }
+
+ async release() {
+ await this.agent(["close"]).catch(() => undefined);
+ }
+}
diff --git a/scripts/mobile-e2e/journey.ts b/scripts/mobile-e2e/journey.ts
new file mode 100644
index 00000000000..70198aaca73
--- /dev/null
+++ b/scripts/mobile-e2e/journey.ts
@@ -0,0 +1,264 @@
+// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - Host-side device automation.
+
+import * as NodePath from "node:path";
+
+import {
+ check,
+ type Check,
+ describeRect,
+ findLabel,
+ keyboardRect,
+ layoutChecks,
+ type Rect,
+ type Snapshot,
+ type SnapshotNode,
+ tabBarRect,
+} from "./checks.ts";
+import { BUNDLE_ID, delay, type Device } from "./device.ts";
+import { lagCheck } from "./video.ts";
+
+export interface StepResult {
+ readonly name: string;
+ readonly checks: ReadonlyArray<Check>;
+ readonly screenshot?: string;
+ readonly video?: string;
+ readonly lagFrame?: string;
+}
+
+// Threads of the fixture's first environment (scripts/mobile-showcase-environment.ts).
+const THREAD_TITLE =
+ /Make remote coding feel local|Put the command center in your pocket|Tune the handoff haptics/;
+const BACK = /^(Back|Navigate up|Go back)$/i;
+
+const backButton = (snapshot: Snapshot) =>
+ snapshot.nodes.find((node) => node.identifier === "BackButton") ?? findLabel(snapshot, BACK);
+const composer = (snapshot: Snapshot) =>
+ snapshot.nodes
+ .filter(
+ (node) =>
+ (node.kind === "text-field" || node.kind === "text-view" || node.editable === true) &&
+ node.rect &&
+ node.rect.y < snapshot.viewport.height &&
+ node.bundleId !== "com.android.systemui",
+ )
+ .toSorted((a, b) => b.rect!.y - a.rect!.y)[0];
+const threadRow = (snapshot: Snapshot) => findLabel(snapshot, THREAD_TITLE);
+
+const inside = (rect: Rect | undefined, snapshot: Snapshot) =>
+ rect !== undefined &&
+ rect.x >= 0 &&
+ rect.y >= 0 &&
+ rect.x + rect.width <= snapshot.viewport.width + 1 &&
+ rect.y + rect.height <= snapshot.viewport.height + 1;
+
+const topBand = (snapshot: Snapshot): Rect => ({
+ x: 0,
+ y: 0,
+ width: snapshot.viewport.width,
+ height: snapshot.viewport.height * 0.12,
+});
+
+/**
+ * Walks one device through the app like a person would: thread list, a thread, scrolling,
+ * typing, back, settings, then the pose's own change (rotation or fold). Every screen gets
+ * the generic layout checks plus what that screen must show. Steps land in `steps` as they
+ * finish, so a journey that stops early still reports what it saw.
+ */
+export async function runJourney(
+ device: Device,
+ directory: string,
+ pair: () => Promise<string>,
+ steps: StepResult[],
+): Promise<void> {
+ const phone = device.pose.form === "phone";
+ const tap = (node: SnapshotNode | undefined, label: string) => {
+ if (!node?.ref) throw new Error(`no ${label} to tap`);
+ return device.agent(["press", `@${node.ref}`]);
+ };
+
+ /** Screenshot and check the settled screen, and record it as a step. */
+ const capture = async (
+ name: string,
+ snapshot: Snapshot,
+ expectations: ReadonlyArray<Check> = [],
+ extra: Partial<StepResult> = {},
+ ) => {
+ const screenshot = NodePath.join(directory, `${steps.length + 1}-${name}.png`);
+ await device.screenshot(screenshot);
+ const step = {
+ name,
+ checks: [...layoutChecks(snapshot, BUNDLE_ID), ...expectations],
+ screenshot,
+ ...extra,
+ };
+ steps.push(step);
+ return step;
+ };
+
+ // The app ignores the pairing link until its JS has loaded and shown the workspace. An
+ // error dialog on the way is a finding: record it, dismiss it, and keep going.
+ const loaded = (snapshot: Snapshot) =>
+ findLabel(snapshot, /Add environment|New (chat|thread)/i) !== undefined;
+ const errorDialog = (snapshot: Snapshot) =>
+ findLabel(snapshot, /^(Dismiss|OK|Close)$/) !== undefined
+ ? findLabel(snapshot, /^Could not|failed|went wrong/i)
+ : undefined;
+ for (let dialogs = 0; ; dialogs++) {
+ const launch = await device.waitFor(
+ (snapshot) => loaded(snapshot) || errorDialog(snapshot) !== undefined,
+ "the app to load",
+ 180_000,
+ );
+ const dialog = errorDialog(launch);
+ if (!dialog || dialogs >= 3) break;
+ await capture("launch error", launch, [
+ check("no error dialog on launch", false, dialog.label ?? "error dialog"),
+ ]);
+ await device.agent(["press", `label="${findLabel(launch, /^(Dismiss|OK|Close)$/)!.label}"`]);
+ await delay(1_000);
+ }
+ let threads: Snapshot | null = null;
+ for (let attempt = 1; attempt <= 2 && !threads; attempt++) {
+ const pairing = new URLSearchParams({ pairingUrl: await pair(), autoConnect: "1" });
+ await device.openUrl(`t3code-dev://connections/new?${pairing}`);
+ threads = await device
+ .waitFor((snapshot) => threadRow(snapshot) !== undefined, "the paired thread list", 60_000)
+ .catch(() => null);
+ }
+ if (!threads) throw new Error("the app did not show the fixture threads after pairing");
+ await delay(1_000);
+ threads = await device.snapshot();
+ const tabs = tabBarRect(threads);
+ await capture("threads", threads, [
+ check("thread list visible", threadRow(threads) !== undefined, "fixture threads"),
+ ...(phone ? [check("tab bar visible", inside(tabs, threads), describeRect(tabs))] : []),
+ ]);
+
+ const opening = await device.recorded(directory, "open-thread", () =>
+ tap(threadRow(threads!), "thread row"),
+ );
+ const thread = await device.waitFor(
+ (snapshot) => composer(snapshot) !== undefined && threadRow(snapshot) !== undefined,
+ "the thread screen",
+ );
+ const threadShot = NodePath.join(directory, `${steps.length + 1}-thread.png`);
+ await device.screenshot(threadShot);
+ const openLag =
+ phone && tabs
+ ? await lagCheck(
+ "no tabs over the entering thread (video)",
+ {
+ video: opening,
+ nav: topBand(threads),
+ chrome: tabs,
+ viewportWidth: threads.viewport.width,
+ },
+ NodePath.join(directory, "open-thread-lag.png"),
+ )
+ : null;
+ steps.push({
+ name: "thread",
+ screenshot: threadShot,
+ video: opening,
+ ...(openLag?.frame ? { lagFrame: openLag.frame } : {}),
+ checks: [
+ ...layoutChecks(thread, BUNDLE_ID),
+ check(
+ "composer inside the screen",
+ inside(composer(thread)?.rect, thread),
+ describeRect(composer(thread)?.rect),
+ ),
+ ...(phone
+ ? [
+ check("back button visible", backButton(thread) !== undefined, "back"),
+ check(
+ "tab bar hidden",
+ tabBarRect(thread) === undefined,
+ describeRect(tabBarRect(thread)),
+ ),
+ ]
+ : []),
+ ...(openLag ? [openLag.check] : []),
+ ],
+ });
+
+ await device.agent(["scroll", "up"]).catch(() => undefined);
+ await delay(800);
+ await capture("scrolled up", await device.snapshot());
+ await device.agent(["scroll", "down"]).catch(() => undefined);
+ await delay(800);
+
+ await tap(composer(await device.snapshot()), "composer");
+ await device.agent(["type", "Checking the composer above the keyboard"]);
+ await delay(1_200);
+ const typing = await device.snapshot();
+ await capture("typing", typing, [
+ check(
+ "composer visible while typing",
+ inside(composer(typing)?.rect, typing),
+ describeRect(composer(typing)?.rect),
+ ),
+ check(
+ "composer above the keyboard",
+ keyboardRect(typing) === undefined ||
+ (composer(typing)?.rect?.y ?? Infinity) < keyboardRect(typing)!.y,
+ `composer ${describeRect(composer(typing)?.rect)}, keyboard ${describeRect(keyboardRect(typing))}`,
+ ),
+ ]);
+ await device.agent(["keyboard", "dismiss"]).catch(() => undefined);
+ await delay(800);
+
+ if (phone) {
+ const back = await device.recorded(directory, "back", async () => {
+ const current = await device.snapshot();
+ const button = backButton(current);
+ if (button) await tap(button, "back button");
+ else await device.agent(["back"]);
+ });
+ const list = await device.waitFor(
+ (snapshot) => backButton(snapshot) === undefined && threadRow(snapshot) !== undefined,
+ "the thread list",
+ );
+ const listShot = NodePath.join(directory, `${steps.length + 1}-back.png`);
+ await device.screenshot(listShot);
+ const backLag = tabs
+ ? await lagCheck(
+ "tabs return with the list (video)",
+ {
+ video: back,
+ nav: topBand(list),
+ chrome: tabs,
+ viewportWidth: list.viewport.width,
+ },
+ NodePath.join(directory, "back-lag.png"),
+ )
+ : null;
+ steps.push({
+ name: "back",
+ screenshot: listShot,
+ video: back,
+ ...(backLag?.frame ? { lagFrame: backLag.frame } : {}),
+ checks: [
+ ...layoutChecks(list, BUNDLE_ID),
+ check("tab bar back", inside(tabBarRect(list), list), describeRect(tabBarRect(list))),
+ ...(backLag ? [backLag.check] : []),
+ ],
+ });
+ }
+
+ // The labelled tab is not always the hittable node; agent-device resolves the press.
+ await device.agent(["press", 'label="Settings"']);
+ await delay(1_500);
+ await capture("settings", await device.snapshot());
+
+ if (device.pose.form === "tablet" && !device.pose.fold) {
+ await device.agent(["orientation", device.pose.landscape ? "portrait" : "landscape-left"]);
+ await delay(2_000);
+ await capture("rotated", await device.snapshot());
+ }
+ if (device.pose.fold) {
+ await device.agent(["fold", device.pose.fold === "open" ? "closed" : "open"]);
+ await delay(2_500);
+ await capture(device.pose.fold === "open" ? "folded" : "unfolded", await device.snapshot());
+ }
+}
diff --git a/scripts/mobile-e2e/poses.ts b/scripts/mobile-e2e/poses.ts
new file mode 100644
index 00000000000..a1714cd5e10
--- /dev/null
+++ b/scripts/mobile-e2e/poses.ts
@@ -0,0 +1,107 @@
+export interface Pose {
+ readonly id: string;
+ readonly platform: "ios" | "android";
+ /** A model name from the pool's catalog (`GET /v1/catalog`). */
+ readonly device: string;
+ readonly form: "phone" | "tablet";
+ readonly appearance: "light" | "dark";
+ /** Phones are portrait-only; tablets also run rotated. */
+ readonly landscape?: boolean;
+ readonly fold?: "closed" | "open";
+ readonly textSize?: "accessibility-large";
+}
+
+const pose = (value: Pose) => value;
+
+export const POSES: ReadonlyArray<Pose> = [
+ pose({
+ id: "iphone-se",
+ platform: "ios",
+ device: "iPhone SE (3rd generation)",
+ form: "phone",
+ appearance: "light",
+ }),
+ pose({
+ id: "iphone-13-mini-dark",
+ platform: "ios",
+ device: "iPhone 13 mini",
+ form: "phone",
+ appearance: "dark",
+ }),
+ pose({
+ id: "iphone-17-pro",
+ platform: "ios",
+ device: "iPhone 17 Pro",
+ form: "phone",
+ appearance: "light",
+ }),
+ pose({
+ id: "iphone-17-pro-max-large-text",
+ platform: "ios",
+ device: "iPhone 17 Pro Max",
+ form: "phone",
+ appearance: "dark",
+ textSize: "accessibility-large",
+ }),
+ pose({
+ id: "ipad-mini",
+ platform: "ios",
+ device: "iPad mini (A17 Pro)",
+ form: "tablet",
+ appearance: "light",
+ }),
+ pose({
+ id: "ipad-pro-13-landscape",
+ platform: "ios",
+ device: "iPad Pro 13-inch (M5)",
+ form: "tablet",
+ appearance: "dark",
+ landscape: true,
+ }),
+ pose({
+ id: "pixel-9",
+ platform: "android",
+ device: "Pixel 9",
+ form: "phone",
+ appearance: "light",
+ }),
+ pose({
+ id: "small-phone-dark",
+ platform: "android",
+ device: "Small Phone",
+ form: "phone",
+ appearance: "dark",
+ }),
+ pose({
+ id: "pixel-9-large-text",
+ platform: "android",
+ device: "Pixel 9",
+ form: "phone",
+ appearance: "light",
+ textSize: "accessibility-large",
+ }),
+ pose({
+ id: "pixel-fold-closed",
+ platform: "android",
+ device: "Pixel 9 Pro Fold",
+ form: "phone",
+ appearance: "light",
+ fold: "closed",
+ }),
+ pose({
+ id: "pixel-fold-open",
+ platform: "android",
+ device: "Pixel 9 Pro Fold",
+ form: "tablet",
+ appearance: "dark",
+ fold: "open",
+ }),
+ pose({
+ id: "pixel-tablet-landscape",
+ platform: "android",
+ device: "Pixel Tablet",
+ form: "tablet",
+ appearance: "light",
+ landscape: true,
+ }),
+];
diff --git a/scripts/mobile-e2e/report.ts b/scripts/mobile-e2e/report.ts
new file mode 100644
index 00000000000..177255fb62a
--- /dev/null
+++ b/scripts/mobile-e2e/report.ts
@@ -0,0 +1,90 @@
+// @effect-diagnostics nodeBuiltinImport:off - Writes a static HTML report.
+
+import * as NodePath from "node:path";
+
+import type { StepResult } from "./journey.ts";
+import type { Pose } from "./poses.ts";
+
+export interface Finding {
+ readonly step: string;
+ readonly issue: string;
+ readonly severity: "high" | "medium" | "low";
+}
+
+export interface PoseResult {
+ readonly pose: Pose;
+ readonly steps: ReadonlyArray<StepResult>;
+ readonly error?: string;
+ /** Screenshot taken when the journey stopped early. */
+ readonly stopped?: string;
+ readonly findings?: ReadonlyArray<Finding>;
+}
+
+export const failedChecks = (result: PoseResult) =>
+ result.steps.flatMap((step) =>
+ step.checks.filter((item) => !item.pass).map((item) => ({ step: step.name, ...item })),
+ );
+
+export const poseFailed = (result: PoseResult) =>
+ result.error !== undefined || failedChecks(result).length > 0;
+
+const escapeHtml = (value: string) =>
+ value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
+
+const describePose = (pose: Pose) =>
+ [
+ pose.device,
+ pose.appearance,
+ pose.landscape ? "landscape" : "",
+ pose.fold ? `fold ${pose.fold}` : "",
+ pose.textSize ? "large text" : "",
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
+export function renderReport(results: ReadonlyArray<PoseResult>, outputDirectory: string): string {
+ const relative = (path: string | undefined) =>
+ path ? escapeHtml(NodePath.relative(outputDirectory, path)) : "";
+ const rows = results
+ .map((result) => {
+ const cells = result.steps
+ .map((step) => {
+ const failed = step.checks.filter((item) => !item.pass);
+ const findings = (result.findings ?? []).filter((finding) => finding.step === step.name);
+ const notes = [
+ ...failed.map(
+ (item) =>
+ `<li class="fail">✗ ${escapeHtml(item.name)} <small>${escapeHtml(item.detail)}</small></li>`,
+ ),
+ ...findings.map(
+ (finding) =>
+ `<li class="review ${finding.severity}">◆ ${escapeHtml(finding.issue)}</li>`,
+ ),
+ ].join("");
+ const passed = step.checks.length - failed.length;
+ const media = [
+ step.screenshot
+ ? `<a href="${relative(step.screenshot)}"><img src="${relative(step.screenshot)}"></a>`
+ : "",
+ step.lagFrame
+ ? `<a href="${relative(step.lagFrame)}"><img class="lag" src="${relative(step.lagFrame)}"></a>`
+ : "",
+ step.video ? `<a href="${relative(step.video)}">video</a>` : "",
+ ].join("");
+ return `<td class="${failed.length ? "bad" : ""}"><h3>${escapeHtml(step.name)}</h3>${media}<small class="pass">${passed}/${step.checks.length} checks</small><ul>${notes}</ul></td>`;
+ })
+ .join("");
+ const error = result.error
+ ? `<td class="bad"><h3>stopped</h3>${result.stopped ? `<a href="${relative(result.stopped)}"><img src="${relative(result.stopped)}"></a>` : ""}<p class="fail">${escapeHtml(result.error)}</p></td>`
+ : "";
+ return `<tr><th>${escapeHtml(result.pose.id)}<br><small>${escapeHtml(describePose(result.pose))}</small></th>${cells}${error}</tr>`;
+ })
+ .join("");
+ const failed = results.filter(poseFailed).length;
+ const findings = results.reduce((count, result) => count + (result.findings?.length ?? 0), 0);
+ return `<!doctype html><meta charset="utf-8"><title>Mobile E2E</title>
+<style>body{font:14px system-ui;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:8px;vertical-align:top;text-align:left}td{width:190px}td.bad{background:#fff5f4}h3{margin:0 0 6px;font-size:13px}img{width:180px;display:block;margin:0 0 6px}img.lag{outline:3px solid #b42318}.pass{color:#16794a}.fail{color:#b42318}.review{color:#7a4b00}.review.high{color:#b42318}ul{padding-left:16px;margin:4px 0}small{color:#666}</style>
+<h1>Mobile E2E · ${results.length} poses · ${failed === 0 ? "all checks passed" : `${failed} with failing checks`} · ${findings} review findings</h1>
+<p><span class="fail">✗</span> failed check <span class="review">◆</span> agent review finding</p>
+<table>${rows}</table>`;
+}
diff --git a/scripts/mobile-e2e/review.ts b/scripts/mobile-e2e/review.ts
new file mode 100644
index 00000000000..148e8ef0b95
--- /dev/null
+++ b/scripts/mobile-e2e/review.ts
@@ -0,0 +1,68 @@
+// @effect-diagnostics nodeBuiltinImport:off - Runs the Claude Code CLI as a reviewer.
+
+import * as NodeProcess from "node:process";
+
+import { run } from "./device.ts";
+import type { Finding, PoseResult } from "./report.ts";
+
+const SCHEMA = {
+ type: "object",
+ properties: {
+ findings: {
+ type: "array",
+ items: {
+ type: "object",
+ properties: {
+ step: { type: "string" },
+ issue: { type: "string" },
+ severity: { type: "string", enum: ["high", "medium", "low"] },
+ },
+ required: ["step", "issue", "severity"],
+ },
+ },
+ },
+ required: ["findings"],
+};
+
+/**
+ * Asks an agent to look at one pose's screenshots for what the generic checks cannot see:
+ * clipped or overlapping text, wrong colours for the appearance, odd gaps, unreadable
+ * contrast. It reads the images itself and returns structured findings.
+ */
+export async function reviewPose(result: PoseResult, outputDirectory: string): Promise<Finding[]> {
+ const shots = result.steps.filter((step) => step.screenshot);
+ if (shots.length === 0) return [];
+ const { pose } = result;
+ const prompt = [
+ `You are reviewing screenshots of the T3 Code mobile app (a client for coding agents) for visual bugs.`,
+ `Device: ${pose.device} (${pose.platform}, ${pose.form}), ${pose.appearance} appearance${pose.landscape ? ", landscape" : ""}${pose.fold ? `, fold ${pose.fold}` : ""}${pose.textSize ? ", largest accessibility text size" : ""}.`,
+ `Read each screenshot below with the Read tool. Each is one step of the same session:`,
+ ...shots.map((step) => `- step "${step.name}": ${step.screenshot}`),
+ ``,
+ `Report only real defects a user would notice: text clipped, truncated mid-word where it should wrap, or overlapping other content; controls overlapping, cut off, or under the status bar, notch, home indicator, or keyboard; content hidden behind navigation chrome; colours wrong for the ${pose.appearance} appearance or unreadable contrast; large unexplained empty areas or misaligned layout; error banners or red error screens.`,
+ `Ignore: the fixture content itself, the status bar clock, a development-build badge, and anything that is plainly a deliberate design choice. Prefer no finding to a speculative one.`,
+ `Use the exact step names above. Severity: high = broken or unusable, medium = clearly wrong, low = polish.`,
+ ].join("\n");
+ const { stdout } = await run(
+ "claude",
+ [
+ "-p",
+ prompt,
+ "--output-format",
+ "json",
+ "--json-schema",
+ JSON.stringify(SCHEMA),
+ "--allowedTools",
+ "Read",
+ "--add-dir",
+ outputDirectory,
+ "--no-session-persistence",
+ ...(NodeProcess.env.T3_E2E_REVIEW_MODEL
+ ? ["--model", NodeProcess.env.T3_E2E_REVIEW_MODEL]
+ : []),
+ ],
+ { cwd: outputDirectory, timeoutMs: 600_000 },
+ );
+ const output = JSON.parse(stdout) as { structured_output?: { findings?: Finding[] } };
+ return output.structured_output?.findings ?? [];
+}
diff --git a/scripts/mobile-e2e/video.ts b/scripts/mobile-e2e/video.ts
new file mode 100644
index 00000000000..788f0ab12fd
--- /dev/null
+++ b/scripts/mobile-e2e/video.ts
@@ -0,0 +1,148 @@
+// @effect-diagnostics nodeBuiltinImport:off - Host-side video analysis shells out to ffmpeg.
+
+import * as NodeChildProcess from "node:child_process";
+import * as NodeFSP from "node:fs/promises";
+
+import { check, type Check, type Rect } from "./checks.ts";
+import { run } from "./device.ts";
+
+/** Pixel width of an image or video, to map snapshot coordinates onto its frames. */
+export async function pixelWidth(path: string): Promise<number> {
+ const { stdout } = await run("ffprobe", [
+ "-v",
+ "error",
+ "-select_streams",
+ "v:0",
+ "-show_entries",
+ "stream=width",
+ "-of",
+ "csv=p=0",
+ path,
+ ]);
+ return Number(stdout.trim());
+}
+
+/** Downsampled grayscale crops of one region, one per video frame (or one for a PNG). */
+async function grayFrames(input: string, region: Rect, scale: number): Promise<Uint8Array[]> {
+ const even = (value: number) => Math.max(2, Math.floor(value / 2) * 2);
+ const [x, y, width, height] = [
+ Math.round(region.x * scale),
+ Math.round(region.y * scale),
+ even(region.width * scale),
+ even(region.height * scale),
+ ];
+ const [outWidth, outHeight] = [even(region.width / 3), even(region.height / 3)];
+ const bytes = await new Promise<Buffer>((resolve, reject) => {
+ const child = NodeChildProcess.spawn(
+ "ffmpeg",
+ [
+ "-v",
+ "error",
+ "-i",
+ input,
+ // One output frame per recorded frame, so indices match select=eq(n,…) for evidence.
+ "-fps_mode",
+ "passthrough",
+ "-vf",
+ `crop=${width}:${height}:${x}:${y},scale=${outWidth}:${outHeight},format=gray`,
+ "-f",
+ "rawvideo",
+ "-",
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const chunks: Buffer[] = [];
+ let stderr = "";
+ child.stdout.on("data", (chunk: Buffer) => chunks.push(chunk));
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ child.on("error", reject);
+ child.on("close", (code) =>
+ code === 0 ? resolve(Buffer.concat(chunks)) : reject(new Error(`ffmpeg failed: ${stderr}`)),
+ );
+ });
+ const size = outWidth * outHeight;
+ return Array.from({ length: Math.floor(bytes.length / size) }, (_, index) =>
+ bytes.subarray(index * size, (index + 1) * size),
+ );
+}
+
+const distance = (a: Uint8Array, b: Uint8Array) => {
+ let sum = 0;
+ for (let index = 0; index < a.length; index++) sum += Math.abs(a[index]! - b[index]!);
+ return sum / a.length;
+};
+
+/** How far a region has moved from its origin toward its destination look, 0 to 1. */
+export interface FrameProgress {
+ readonly nav: number;
+ readonly chrome: number;
+}
+
+/**
+ * A frame lags when the top of the screen is well into the transition while the tab bar
+ * region still looks like the origin: tabs lingering over an entering thread, or a returned
+ * list drawn before its tabs.
+ */
+export const chromeLags = (frame: FrameProgress) => frame.nav > 0.3 && frame.chrome < 0.4;
+// One lagging frame is capture jitter; a regression lasts several.
+const LAG_FRAME_LIMIT = 2;
+
+const progress = (origin: number, destination: number) =>
+ origin + destination === 0 ? 0 : origin / (origin + destination);
+
+/**
+ * Checks that the tab bar moves with the screen during a recorded transition. The first and
+ * last frames are the before and after looks, so nothing is compared across capture sources.
+ */
+export async function lagCheck(
+ name: string,
+ input: {
+ readonly video: string;
+ readonly nav: Rect;
+ readonly chrome: Rect;
+ /** Snapshot units across the screen, to scale regions onto the video's pixels. */
+ readonly viewportWidth: number;
+ },
+ evidence: string,
+): Promise<{ check: Check; frame?: string }> {
+ // A recording the device failed to export is a gap in evidence, not a lag.
+ if (!(await NodeFSP.stat(input.video).catch(() => null)))
+ return { check: check(name, true, "no recording; not checked") };
+ const scale = (await pixelWidth(input.video)) / input.viewportWidth;
+ const [navFrames, chromeFrames] = await Promise.all([
+ grayFrames(input.video, input.nav, scale),
+ grayFrames(input.video, input.chrome, scale),
+ ]);
+ const [navOrigin, navDestination] = [navFrames[0], navFrames.at(-1)];
+ const [chromeOrigin, chromeDestination] = [chromeFrames[0], chromeFrames.at(-1)];
+ if (!navOrigin || !navDestination || !chromeOrigin || !chromeDestination)
+ throw new Error(`Could not read frames of ${input.video}.`);
+ const lagging = navFrames.flatMap((nav, index) => {
+ const frame = {
+ nav: progress(distance(nav, navOrigin), distance(nav, navDestination)),
+ chrome: progress(
+ distance(chromeFrames[index]!, chromeOrigin),
+ distance(chromeFrames[index]!, chromeDestination),
+ ),
+ };
+ return chromeLags(frame) ? [index] : [];
+ });
+ if (lagging.length < LAG_FRAME_LIMIT)
+ return { check: check(name, true, `${lagging.length} lagging video frames`) };
+ await run("ffmpeg", [
+ "-v",
+ "error",
+ "-y",
+ "-i",
+ input.video,
+ "-vf",
+ `select=eq(n\\,${lagging[0]})`,
+ "-frames:v",
+ "1",
+ evidence,
+ ]);
+ return {
+ check: check(name, false, `${lagging.length} video frames (first #${lagging[0]})`),
+ frame: evidence,
+ };
+}
diff --git a/scripts/mobile-native-client.ts b/scripts/mobile-native-client.ts
index fc3074c3eaf..9af54e71eb7 100644
--- a/scripts/mobile-native-client.ts
+++ b/scripts/mobile-native-client.ts
@@ -453,6 +453,32 @@ const remoteCache = Effect.fn("nativeClient.remoteCache")(
Effect.orElseSucceed(() => null),
);
+const ReaderLogin = Schema.fromJsonString(
+ Schema.Struct({ name: Schema.String, token: Schema.String }),
+);
+
+/**
+ * A URL another machine can download `key` from. The header goes to that machine, so only a
+ * read-only login (`ci-reader`) is ever handed out, never a developer's writer token.
+ */
+const sharedSource = Effect.fn("nativeClient.sharedSource")(
+ function* (home: string, key: string) {
+ const remote = yield* remoteCache(home);
+ if (!remote) return null;
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const reader =
+ remote.name === "ci-reader"
+ ? remote
+ : yield* fs
+ .readFileString(path.join(home, ".config/t3-task-cache/ci-reader.json"))
+ .pipe(Effect.flatMap(Schema.decodeUnknownEffect(ReaderLogin)));
+ const basic = Buffer.from(`${reader.name}:${reader.token}`).toString("base64");
+ return { url: `${remote.url}/${key}`, header: `authorization:Basic ${basic}` };
+ },
+ Effect.orElseSucceed(() => null),
+);
+
const authorized = (remote: RemoteCache, request: HttpClientRequest.HttpClientRequest) =>
request.pipe(HttpClientRequest.basicAuth(remote.name, remote.token));
@@ -860,16 +886,48 @@ const installIntoSession = Effect.fn("nativeClient.installIntoSession")(function
const deviceAbi = platform === "android" ? abi : null;
const task = deviceAbi ? `native-client:android-${deviceAbi}` : `native-client:${platform}`;
const current = yield* fingerprint(platform);
- const artifact = yield* resolveArtifact(home, platform, deviceAbi, current, false).pipe(
- Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
- );
- yield* Console.error(`Installing into agent-device session ${session}...`);
- yield* command(
- node,
- [agentDevice, "install", bundleId, artifact.file, "--session", session],
- true,
- workspace,
- );
+ const key = `${platform}/${deviceAbi ? `development-${deviceAbi}` : "development"}/${current}`;
+ const source = yield* sharedSource(home, key);
+ // The session's host downloads the client itself; uploading a 166 MB APK through a
+ // gateway from here takes minutes and can outlast the remote install timeout.
+ const fetched = source
+ ? yield* command(
+ node,
+ [
+ agentDevice,
+ "install-from-source",
+ source.url,
+ "--header",
+ source.header,
+ "--session",
+ session,
+ ],
+ true,
+ workspace,
+ ).pipe(
+ Effect.as(true),
+ Effect.catch((error) =>
+ Console.error(`The device could not download ${key} (${describe(error)}).`).pipe(
+ Effect.as(false),
+ ),
+ ),
+ )
+ : false;
+ const artifact = fetched
+ ? { source: "remote" as const, buildMs: 0 }
+ : yield* Effect.gen(function* () {
+ const local = yield* resolveArtifact(home, platform, deviceAbi, current, false).pipe(
+ Effect.tapError(() => reportTelemetry(home, task, "failed", 0)),
+ );
+ yield* Console.error(`Installing into agent-device session ${session}...`);
+ yield* command(
+ node,
+ [agentDevice, "install", bundleId, local.file, "--session", session],
+ true,
+ workspace,
+ );
+ return local;
+ });
if (metro) {
const url = encodeURIComponent(metro);
yield* command(
diff --git a/scripts/mobile-showcase.ts b/scripts/mobile-showcase.ts
index db90eec52c3..17a609b9894 100644
--- a/scripts/mobile-showcase.ts
+++ b/scripts/mobile-showcase.ts
@@ -553,7 +553,7 @@ async function waitForFileContent(
throw new Error(`${label} was not written to ${filePath} within ${timeoutMs}ms.`);
}
-async function reserveAvailablePort(): Promise<number> {
+export async function reserveAvailablePort(): Promise<number> {
return await new Promise<number>((resolve, reject) => {
const server = NodeNet.createServer();
server.once("error", reject);