@rootnative/loupe 0.0.0-alpha.0 → 0.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ import { z } from 'zod';
2
+
3
+ declare const version: string;
4
+
5
+ /** Every loupe command. The CLI is made from this list. */
6
+ declare const registry: Registry;
7
+
8
+ interface ExecOptions {
9
+ /** Milliseconds before loupe stops the tool. Default: 30 000. */
10
+ timeout?: number;
11
+ }
12
+ interface ExecResult {
13
+ /** The exit code, or `null` when a signal stopped the tool. */
14
+ code: number | null;
15
+ /** Raw bytes, because a tool can write binary data, for example a PNG. */
16
+ stdout: Buffer;
17
+ stderr: Buffer;
18
+ }
19
+ /**
20
+ * Runs a tool with no shell, so no argument goes through shell parsing. It
21
+ * fails with `tool_missing` when the tool doesn't exist, and with `timeout`
22
+ * when the tool runs too long. A non-zero exit code isn't a failure here:
23
+ * the caller decides what it means.
24
+ */
25
+ type Exec = (file: string, args: readonly string[], options?: ExecOptions) => Promise<ExecResult>;
26
+
27
+ /** How far a long command is. `progress` grows with each update. */
28
+ interface ProgressUpdate {
29
+ progress: number;
30
+ total?: number;
31
+ message?: string;
32
+ }
33
+ /**
34
+ * Everything a command takes from the machine it runs on. A test passes a
35
+ * fake context that replays recorded tool output.
36
+ */
37
+ interface CommandContext {
38
+ exec: Exec;
39
+ env: Readonly<Record<string, string | undefined>>;
40
+ /**
41
+ * Aborts when the caller cancels the call: Ctrl-C in the CLI, or a
42
+ * cancel from the MCP client. A long command stops at its next safe
43
+ * point; a tool that runs isn't stopped.
44
+ */
45
+ signal?: AbortSignal;
46
+ /** Takes the progress of a long command, for the caller to show. */
47
+ progress?: (update: ProgressUpdate) => void;
48
+ }
49
+ /** The real context: child processes, and the environment of this process. */
50
+ declare function createContext(): CommandContext;
51
+
52
+ /**
53
+ * One command, defined once. The CLI and the MCP server are both made from
54
+ * this definition, so the two can't drift apart.
55
+ */
56
+ interface Command<I extends z.ZodObject = z.ZodObject, O extends z.ZodType = z.ZodType> {
57
+ /** Kebab case, for example `open-url`. */
58
+ name: string;
59
+ /** One line for the help text and the MCP tool description. */
60
+ summary: string;
61
+ input: I;
62
+ output: O;
63
+ /**
64
+ * Input fields that the CLI also takes by position, in order:
65
+ * `open-url <url>`. Each one still works as a flag.
66
+ */
67
+ positionals?: readonly (keyof z.output<I> & string)[];
68
+ /**
69
+ * The command changes nothing on the device, and it writes a file only
70
+ * where its input names one. An MCP client can run such a tool with no
71
+ * prompt.
72
+ */
73
+ readOnly?: boolean;
74
+ run(input: z.output<I>, context: CommandContext): Promise<z.input<O>> | z.input<O>;
75
+ /** A short summary for a person at a terminal. JSON is the default. */
76
+ format?(data: z.output<O>): string;
77
+ /**
78
+ * The PNG files of the result that an agent should see. The MCP result
79
+ * also holds each one as an image block; the CLI gives only the paths.
80
+ */
81
+ images?(data: z.output<O>): string[];
82
+ /**
83
+ * For a command that checks something: false when the check failed. The
84
+ * result is still a success with all its data, and the CLI exits 1.
85
+ */
86
+ passed?(data: z.output<O>): boolean;
87
+ }
88
+ declare function defineCommand<I extends z.ZodObject, O extends z.ZodType>(command: Command<I, O>): Command<I, O>;
89
+ interface Registry {
90
+ list(): readonly Command[];
91
+ get(name: string): Command | undefined;
92
+ }
93
+ declare function createRegistry(commands: readonly Command[]): Registry;
94
+
95
+ declare const deviceSchema: z.ZodObject<{
96
+ platform: z.ZodEnum<{
97
+ android: "android";
98
+ }>;
99
+ kind: z.ZodEnum<{
100
+ emulator: "emulator";
101
+ device: "device";
102
+ }>;
103
+ serial: z.ZodOptional<z.ZodString>;
104
+ avd: z.ZodOptional<z.ZodString>;
105
+ model: z.ZodOptional<z.ZodString>;
106
+ state: z.ZodEnum<{
107
+ ready: "ready";
108
+ booting: "booting";
109
+ stopped: "stopped";
110
+ offline: "offline";
111
+ unauthorized: "unauthorized";
112
+ "no-permissions": "no-permissions";
113
+ other: "other";
114
+ }>;
115
+ detail: z.ZodOptional<z.ZodString>;
116
+ apiLevel: z.ZodOptional<z.ZodNumber>;
117
+ }, z.core.$strip>;
118
+ type Device = z.infer<typeof deviceSchema>;
119
+ type DeviceState = Device['state'];
120
+
121
+ /**
122
+ * In the order of the rotation: each step turns the device a quarter turn
123
+ * to the left (counter-clockwise), as Android counts `Surface.ROTATION_*`.
124
+ */
125
+ declare const ORIENTATIONS: readonly ["portrait", "landscape-left", "portrait-upside-down", "landscape-right"];
126
+ type Orientation = (typeof ORIENTATIONS)[number];
127
+ declare const displaySchema: z.ZodObject<{
128
+ orientation: z.ZodEnum<{
129
+ portrait: "portrait";
130
+ "landscape-left": "landscape-left";
131
+ "portrait-upside-down": "portrait-upside-down";
132
+ "landscape-right": "landscape-right";
133
+ }>;
134
+ size: z.ZodObject<{
135
+ width: z.ZodNumber;
136
+ height: z.ZodNumber;
137
+ }, z.core.$strip>;
138
+ pixels: z.ZodObject<{
139
+ width: z.ZodNumber;
140
+ height: z.ZodNumber;
141
+ }, z.core.$strip>;
142
+ scale: z.ZodNumber;
143
+ }, z.core.$strip>;
144
+ type DisplayState = z.infer<typeof displaySchema>;
145
+
146
+ declare const ERROR_CODES: readonly ["unknown_command", "invalid_input", "invalid_output", "tool_missing", "tool_failed", "timeout", "no_device", "device_ambiguous", "device_unavailable", "unsupported", "orientation_locked", "app_not_in_front", "not_idle", "element_not_found", "element_ambiguous", "no_handler", "cancelled", "internal"];
147
+ type ErrorCode = (typeof ERROR_CODES)[number];
148
+ /** An error that a caller can act on by its code. */
149
+ declare class LoupeError extends Error {
150
+ readonly code: ErrorCode;
151
+ constructor(code: ErrorCode, message: string, options?: ErrorOptions);
152
+ }
153
+
154
+ interface CommandSuccess<T = unknown> {
155
+ ok: true;
156
+ command: string;
157
+ data: T;
158
+ }
159
+ interface CommandFailure {
160
+ ok: false;
161
+ command: string;
162
+ error: {
163
+ code: ErrorCode;
164
+ message: string;
165
+ };
166
+ }
167
+ type CommandResult<T = unknown> = CommandSuccess<T> | CommandFailure;
168
+ /**
169
+ * Checks the input, runs the command, and checks the output. It never
170
+ * throws: each problem comes back as a failure with a code.
171
+ */
172
+ declare function runCommand(registry: Registry, name: string, input: unknown, context?: CommandContext): Promise<CommandResult>;
173
+
174
+ type Platform = 'ios' | 'android';
175
+ /** Device points: pt on iOS, dp on Android. */
176
+ type Unit = 'pt' | 'dp';
177
+ interface Point {
178
+ x: number;
179
+ y: number;
180
+ }
181
+ interface Size {
182
+ width: number;
183
+ height: number;
184
+ }
185
+ /** The origin is the top-left corner of the current orientation. */
186
+ interface Rect extends Point, Size {
187
+ }
188
+ interface Insets {
189
+ top: number;
190
+ right: number;
191
+ bottom: number;
192
+ left: number;
193
+ }
194
+ declare function unitOf(platform: Platform): Unit;
195
+ /** Pixels are whole numbers, so the result is rounded. */
196
+ declare function toPixels(value: number, scale: number): number;
197
+ /** Not rounded: 1080 px at scale 2.625 is 411.43 dp, and a check needs it. */
198
+ declare function fromPixels(pixels: number, scale: number): number;
199
+ declare function pointToPixels(point: Point, scale: number): Point;
200
+ declare function rectFromPixels(rect: Rect, scale: number): Rect;
201
+ declare function rectRight(rect: Rect): number;
202
+ declare function rectBottom(rect: Rect): number;
203
+ declare function rectCentre(rect: Rect): Point;
204
+ /**
205
+ * True when `inner` is fully inside `outer`. `tolerance` lets `inner` run
206
+ * past each edge by that much, for sub-pixel rounding.
207
+ */
208
+ declare function containsRect(outer: Rect, inner: Rect, tolerance?: number): boolean;
209
+ /** The shared area of two rects, or null when they only touch or are apart. */
210
+ declare function intersection(a: Rect, b: Rect): Rect | null;
211
+ /** The safe area: the screen with its insets removed. */
212
+ declare function insetRect(screen: Size, insets: Insets): Rect;
213
+
214
+ export { type Command, type CommandContext, type CommandFailure, type CommandResult, type CommandSuccess, type Device, type DeviceState, type DisplayState, ERROR_CODES, type ErrorCode, type Exec, type ExecOptions, type ExecResult, type Insets, LoupeError, type Orientation, type Platform, type Point, type Rect, type Registry, type Size, type Unit, containsRect, createContext, createRegistry, defineCommand, fromPixels, insetRect, intersection, pointToPixels, rectBottom, rectCentre, rectFromPixels, rectRight, registry, runCommand, toPixels, unitOf, version };
package/dist/index.js ADDED
@@ -0,0 +1,42 @@
1
+ import {
2
+ ERROR_CODES,
3
+ LoupeError,
4
+ containsRect,
5
+ createContext,
6
+ createRegistry,
7
+ defineCommand,
8
+ fromPixels,
9
+ insetRect,
10
+ intersection,
11
+ pointToPixels,
12
+ rectBottom,
13
+ rectCentre,
14
+ rectFromPixels,
15
+ rectRight,
16
+ registry,
17
+ runCommand,
18
+ toPixels,
19
+ unitOf,
20
+ version
21
+ } from "./chunk-JDX6L5K6.js";
22
+ export {
23
+ ERROR_CODES,
24
+ LoupeError,
25
+ containsRect,
26
+ createContext,
27
+ createRegistry,
28
+ defineCommand,
29
+ fromPixels,
30
+ insetRect,
31
+ intersection,
32
+ pointToPixels,
33
+ rectBottom,
34
+ rectCentre,
35
+ rectFromPixels,
36
+ rectRight,
37
+ registry,
38
+ runCommand,
39
+ toPixels,
40
+ unitOf,
41
+ version
42
+ };
@@ -0,0 +1,211 @@
1
+ import {
2
+ createContext,
3
+ inputJsonSchema,
4
+ outputJsonSchema,
5
+ registry,
6
+ round2,
7
+ runCommand,
8
+ version
9
+ } from "./chunk-JDX6L5K6.js";
10
+
11
+ // src/mcp/server.ts
12
+ import { existsSync } from "fs";
13
+ import path from "path";
14
+ import { fileURLToPath } from "url";
15
+ import {
16
+ McpServer,
17
+ ProtocolError,
18
+ ProtocolErrorCode
19
+ } from "@modelcontextprotocol/server";
20
+ import { loadSkills } from "@modelcontextprotocol/server/ext/skills/node";
21
+ import {
22
+ serveStdio,
23
+ StdioServerTransport
24
+ } from "@modelcontextprotocol/server/stdio";
25
+
26
+ // src/mcp/tools.ts
27
+ import { readFile } from "fs/promises";
28
+ var IMAGE_LIMIT = 375e4;
29
+ function megabytes(bytes) {
30
+ return `${round2(bytes / 1e6)} MB`;
31
+ }
32
+ async function imageBlocks(files, limit = IMAGE_LIMIT) {
33
+ return Promise.all(
34
+ files.map(async (file) => {
35
+ let png;
36
+ try {
37
+ png = await readFile(file);
38
+ } catch (error) {
39
+ const why = error instanceof Error ? error.message : String(error);
40
+ return {
41
+ type: "text",
42
+ text: `loupe can't read ${file} to show it: ${why}`
43
+ };
44
+ }
45
+ if (png.length > limit) {
46
+ return {
47
+ type: "text",
48
+ text: `loupe left the image of ${file} out of this result: the PNG has ${megabytes(png.length)}, and an image block takes ${megabytes(limit)} at most. Open the file, or make the image smaller: a screenshot with a scale (for example 0.5) or a crop, or a sweep of fewer links.`
49
+ };
50
+ }
51
+ return {
52
+ type: "image",
53
+ data: png.toString("base64"),
54
+ mimeType: "image/png"
55
+ };
56
+ })
57
+ );
58
+ }
59
+ function toolSchema(command, side, schema) {
60
+ const copy = { ...schema };
61
+ delete copy.$schema;
62
+ if (copy.type !== "object") {
63
+ throw new Error(
64
+ `${command.name}: the ${side} must be an object to be an MCP tool.`
65
+ );
66
+ }
67
+ return copy;
68
+ }
69
+ function toolOf(command) {
70
+ return {
71
+ name: command.name,
72
+ description: command.summary,
73
+ inputSchema: toolSchema(command, "input", inputJsonSchema(command)),
74
+ outputSchema: toolSchema(command, "output", outputJsonSchema(command)),
75
+ annotations: { readOnlyHint: command.readOnly === true }
76
+ };
77
+ }
78
+ function toolsOf(registry2) {
79
+ return registry2.list().map(toolOf);
80
+ }
81
+ function isJsonObject(value) {
82
+ return typeof value === "object" && value !== null && !Array.isArray(value);
83
+ }
84
+ function toolResult(result) {
85
+ if (!result.ok) {
86
+ return {
87
+ content: [
88
+ { type: "text", text: JSON.stringify({ error: result.error }) }
89
+ ],
90
+ isError: true
91
+ };
92
+ }
93
+ const text = JSON.stringify(result.data);
94
+ const data = JSON.parse(text);
95
+ return {
96
+ content: [{ type: "text", text }],
97
+ ...isJsonObject(data) && { structuredContent: data }
98
+ };
99
+ }
100
+
101
+ // src/mcp/server.ts
102
+ var INSTRUCTIONS = [
103
+ "loupe checks the layout of a mobile app on an Android emulator or device. Its tools give numbers in dp.",
104
+ "Ask the user before you start an emulator, and before you open an app or a link on a device.",
105
+ "On a real phone, give `app` in each call.",
106
+ "Put back the orientation and the theme that you change; a sweep does it itself.",
107
+ "Decide pass or fail with `check` or `sweep`, not from a screenshot alone.",
108
+ "The loupe skill (skills/loupe/SKILL.md in the package) has the workflow, the rules, and what to do for each error code."
109
+ ].join(" ");
110
+ function serial() {
111
+ let last = Promise.resolve();
112
+ return (task) => {
113
+ const next = last.then(task);
114
+ last = next.catch(() => void 0);
115
+ return next;
116
+ };
117
+ }
118
+ function skillsFolder() {
119
+ let dir = path.dirname(fileURLToPath(import.meta.url));
120
+ for (; ; ) {
121
+ if (existsSync(path.join(dir, "package.json"))) {
122
+ return path.join(dir, "skills");
123
+ }
124
+ const up = path.dirname(dir);
125
+ if (up === dir) throw new Error("loupe can't find its package folder.");
126
+ dir = up;
127
+ }
128
+ }
129
+ function createMcpServer(registry2, context, { oneAtATime = serial(), skills } = {}) {
130
+ const tools = toolsOf(registry2);
131
+ const byName = new Map(tools.map((tool) => [tool.name, tool]));
132
+ const mcp = new McpServer(
133
+ { name: "loupe", version },
134
+ { instructions: INSTRUCTIONS }
135
+ );
136
+ const { server } = mcp;
137
+ server.registerCapabilities({ tools: {} });
138
+ server.setRequestHandler("tools/list", () => ({ tools }));
139
+ server.setRequestHandler("tools/call", async (request, ctx) => {
140
+ const { name, arguments: input = {} } = request.params;
141
+ const tool = byName.get(name);
142
+ if (!tool) {
143
+ throw new ProtocolError(
144
+ ProtocolErrorCode.InvalidParams,
145
+ `"${name}" is not a loupe tool.`
146
+ );
147
+ }
148
+ const token = ctx.mcpReq._meta?.progressToken;
149
+ const call = {
150
+ ...context,
151
+ signal: ctx.mcpReq.signal,
152
+ ...token !== void 0 && {
153
+ progress: (update) => {
154
+ ctx.mcpReq.notify({
155
+ method: "notifications/progress",
156
+ params: { progressToken: token, ...update }
157
+ }).catch(() => void 0);
158
+ }
159
+ }
160
+ };
161
+ const output = await oneAtATime(async () => {
162
+ const result = await runCommand(registry2, name, input, call);
163
+ const shown = toolResult(result);
164
+ const images = result.ok && registry2.get(name)?.images?.(result.data);
165
+ if (images) shown.content.push(...await imageBlocks(images));
166
+ return shown;
167
+ });
168
+ return server.projectCallToolResult(output, tool.outputSchema);
169
+ });
170
+ skills?.attach(mcp);
171
+ return mcp;
172
+ }
173
+ async function serveMcp(options = {}) {
174
+ const {
175
+ registry: registry2 = registry,
176
+ context = createContext(),
177
+ stdin = process.stdin,
178
+ stdout = process.stdout,
179
+ onerror
180
+ } = options;
181
+ const oneAtATime = serial();
182
+ const ended = new Promise((resolve) => stdin.once("end", resolve));
183
+ const skills = await loadSkills(skillsFolder(), {
184
+ onWarning: ({ path: file, message }) => onerror?.(new Error(`The skill at ${file}: ${message}`))
185
+ }).catch((error) => {
186
+ onerror?.(
187
+ new Error(
188
+ `loupe serves no skill: ${error instanceof Error ? error.message : String(error)}`
189
+ )
190
+ );
191
+ return void 0;
192
+ });
193
+ const closed = new Promise((resolve) => {
194
+ serveStdio(
195
+ () => {
196
+ const mcp = createMcpServer(registry2, context, { oneAtATime, skills });
197
+ mcp.server.onclose = resolve;
198
+ return mcp;
199
+ },
200
+ { transport: new StdioServerTransport(stdin, stdout), onerror }
201
+ );
202
+ });
203
+ await Promise.race([ended, closed]);
204
+ }
205
+ export {
206
+ INSTRUCTIONS,
207
+ createMcpServer,
208
+ serial,
209
+ serveMcp,
210
+ skillsFolder
211
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rootnative/loupe",
3
- "version": "0.0.0-alpha.0",
3
+ "version": "0.0.0-alpha.1",
4
4
  "description": "loupe by Root Native: layout checks for iOS and Android, built for AI agents. Drive simulators and emulators, and measure every screen to the point.",
5
5
  "license": "MIT",
6
6
  "author": "Root Native",
@@ -25,11 +25,50 @@
25
25
  "ai-agents",
26
26
  "cli"
27
27
  ],
28
+ "type": "module",
29
+ "main": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
31
+ "bin": {
32
+ "loupe": "./dist/bin.js"
33
+ },
34
+ "exports": {
35
+ "./package.json": "./package.json",
36
+ ".": {
37
+ "types": "./dist/index.d.ts",
38
+ "default": "./dist/index.js"
39
+ }
40
+ },
28
41
  "files": [
42
+ "dist",
43
+ "skills",
29
44
  "README.md",
45
+ "CHANGELOG.md",
30
46
  "LICENSE"
31
47
  ],
48
+ "engines": {
49
+ "node": ">=20.19"
50
+ },
51
+ "scripts": {
52
+ "build": "tsup",
53
+ "prepack": "turbo run build --filter=@rootnative/loupe",
54
+ "dev": "tsup --watch",
55
+ "typecheck": "tsc --noEmit",
56
+ "test": "vitest run",
57
+ "lint": "eslint . --max-warnings 0",
58
+ "clean": "node -e \"for (const p of ['dist', '.turbo']) require('node:fs').rmSync(p, { recursive: true, force: true })\""
59
+ },
60
+ "devDependencies": {
61
+ "@modelcontextprotocol/client": "^2.4.0",
62
+ "@types/node": "^22.20.2",
63
+ "tsup": "^8.5.1",
64
+ "typescript": "^5.9.3",
65
+ "vitest": "^3.2.4"
66
+ },
32
67
  "publishConfig": {
33
68
  "access": "public"
69
+ },
70
+ "dependencies": {
71
+ "@modelcontextprotocol/server": "^2.4.0",
72
+ "zod": "^4.6.7"
34
73
  }
35
74
  }
@@ -0,0 +1,150 @@
1
+ ---
2
+ name: loupe
3
+ description: Check the layout of a mobile app on an Android emulator or device with the loupe tools, and get numbers in dp, not guesses from a screenshot. Use it when you check or fix how a screen looks in portrait or landscape, light or dark, LTR or RTL, near the system bars, the cutout, or the screen edges.
4
+ ---
5
+
6
+ # loupe
7
+
8
+ loupe drives an Android emulator or device and measures each screen of your
9
+ app. It gives you exact numbers: element frames, safe areas, cutouts, and
10
+ edges. Use them to say "pass" or "fail" with evidence.
11
+
12
+ Each loupe tool gives JSON. Each input field has a description in the tool's
13
+ schema, so this skill doesn't repeat them. loupe works on Android 11
14
+ (API level 30) and later.
15
+
16
+ ## Ask the user first
17
+
18
+ - Ask before you start an emulator. Don't start one on your own.
19
+ - Ask before you open an app or a link on a device, unless the user asked
20
+ for that run.
21
+ - On a real phone, give `app` in each call. loupe then reads the screen
22
+ only while that app is in front, so it never shows you another app.
23
+ - Don't change a setting that the user didn't ask for. `rotate` and
24
+ `theme` change the device. Put back what you changed. `sweep` puts the
25
+ orientation and the theme back itself.
26
+
27
+ ## Before the first check
28
+
29
+ 1. Run `devices`. Only a device in the state `ready` takes commands.
30
+ 2. When two or more devices are ready, give `device` (the serial or the
31
+ AVD name) in each call.
32
+ 3. Give `app` in each call that reads or touches the screen. For Expo Go,
33
+ it's `host.exp.exponent`.
34
+ 4. Run one loupe call at a time on a device. Two touches at the same time
35
+ lose events. The MCP server already runs its calls one after the other.
36
+
37
+ ## Units
38
+
39
+ - Each position and size is in dp, from the top-left corner of the
40
+ current orientation.
41
+ - Each reading gives `scale`: the pixels in one dp.
42
+ - Each screenshot is upright, in each orientation.
43
+
44
+ ## Check one screen
45
+
46
+ 1. Open the screen with `open-url` and its deep link. Give `waitText` (a
47
+ text on that screen) or `waitStill`, so the call ends when the screen is
48
+ there.
49
+ 2. Run `check`. Read `passed`, then the findings of each rule that failed.
50
+ 3. Run `rotate` with `landscape-left`, then `check` again.
51
+ 4. Run `rotate` with `landscape-right`, then `check` again. A cutout on one
52
+ side shows only in one of the two landscapes.
53
+ 5. Run `rotate` with `portrait` to put the device back.
54
+
55
+ Take a `screenshot` when you want to see the screen, but decide with
56
+ `check`. Over MCP, the result of `screenshot` also holds the image. Give
57
+ `scale` (for example 0.5) or `crop` to make it smaller.
58
+
59
+ ## Check many screens: sweep
60
+
61
+ Give `sweep` one `url` for each screen. Add `orientation`
62
+ (`portrait,landscape-left`) and `theme` (`light,dark`) to check each
63
+ screen in each of them. Add `scroll` to check each screen again after one
64
+ scroll down.
65
+
66
+ - The result lists each screen that failed, with each finding and its
67
+ numbers. You don't need to check those screens again.
68
+ - A sweep writes to `out` (`loupe-sweep` by default): `report.json`, a
69
+ screenshot of each screen, and a contact sheet of each variant. A red
70
+ frame on the contact sheet marks a screen that failed. Over MCP, the
71
+ result also holds each contact sheet as an image.
72
+ - A screen that loupe can't open or check gets its error in the report,
73
+ and the sweep goes on.
74
+ - A sweep can take minutes. Over MCP, it sends its progress after each
75
+ screen. When you cancel it, it stops before the next screen and puts
76
+ the orientation and the theme back. It then writes no report.
77
+
78
+ ## The rules
79
+
80
+ `check` runs each rule by default. Give `rules` (a comma list) to run
81
+ fewer.
82
+
83
+ | Rule | Fails when | What to look at |
84
+ |---|---|---|
85
+ | `inset` | An element with text, a label, or a touch sits under a system bar or the cutout, or outside the safe area. | The edge in the finding. In landscape, the left and the right insets can differ. A full-screen scrim doesn't count. |
86
+ | `overflow` | An element at a screen edge is shorter than the elements like it in its row or column: the edge cuts it. | The row or the column of the element. Let it wrap or scroll, or make its items smaller. |
87
+ | `centred` | A text with an element on each side is more than 4 dp from the centre of its container. | Centre the text in the whole bar, not in the space between the side items. Name a text with `centred`, `centredLabel`, or `centredId` to check it. |
88
+ | `touch-target` | An element that you can press is smaller than 48 × 48 dp. | From 40 dp, loupe gives a warning, not a finding: the tree doesn't show `hitSlop`. Look in the code for a `hitSlop` that makes it 48 dp. |
89
+ | `mirrored` | In RTL, an element sits where LTR puts it. | It runs only with `mirrorOf` (see below). |
90
+
91
+ To check `mirrored`:
92
+
93
+ 1. Show the screen in LTR. Run `ui` with `out` set to a file.
94
+ 2. Show the same screen in RTL, in the same orientation.
95
+ 3. Run `check` with `mirrorOf` set to that file.
96
+
97
+ ## Read a result
98
+
99
+ - `passed` is false when a rule failed. A failed check is still a
100
+ success: the data has each finding. The CLI exits with 1 for it.
101
+ - Each finding has the `element`, a `message`, and `details` in dp.
102
+ - `safeAreaSource` says where the safe area came from: `probe` (the app's
103
+ own numbers) or `dumpsys` (the system's numbers).
104
+ - A `warnings` line says where loupe isn't sure. Read it before you decide.
105
+ - After a fix, reload the app and check the same screen again, in the same
106
+ orientation.
107
+
108
+ ## The probe
109
+
110
+ `@rootnative/loupe-probe` gives loupe the app's own safe area, layout
111
+ direction, colour scheme, and route. Render `<LoupeProbe route={path} />`
112
+ once, inside your `SafeAreaProvider`. It renders nothing in a release
113
+ build. Without it, loupe takes the safe area from Android.
114
+
115
+ ## Errors
116
+
117
+ A failed call has an error `code` and a `message`. The message says what
118
+ to do. The codes:
119
+
120
+ | Code | What to do |
121
+ |---|---|
122
+ | `no_device` | Ask the user to start an emulator or to connect a phone. |
123
+ | `device_ambiguous` | Run `devices`, then give `device`. |
124
+ | `device_unavailable` | The device is offline, not authorized, or still booting. Wait, or ask the user. |
125
+ | `tool_missing` | loupe can't find adb. Ask the user to set `ANDROID_HOME`. |
126
+ | `tool_failed` | adb failed. Read the message. |
127
+ | `app_not_in_front` | Another app or a dialog is in front. Run `dismiss` for a dialog or a sheet, or `foreground` for the app. |
128
+ | `not_idle` | The screen didn't keep still long enough to read it. Run `wait` with `still`, then try again. |
129
+ | `element_not_found` | Run `ui`, find the element, and give its exact text, label, or id. |
130
+ | `element_ambiguous` | More than one element matches. Give its `id`. |
131
+ | `orientation_locked` | The app sets its own orientation. Check the orientations it allows. |
132
+ | `timeout` | The screen didn't get there in time. The message says whether the action ran. |
133
+ | `no_handler` | No app on the device opens that link. |
134
+ | `invalid_input` | Fix the input. The message names the field. |
135
+ | `unsupported` | loupe can't do this on this device or API level. |
136
+ | `cancelled` | The call was cancelled. loupe stopped at a safe point. |
137
+
138
+ ## The CLI
139
+
140
+ The CLI has the same commands: run `loupe <command> --help`. A field such
141
+ as `waitText` is the flag `--wait-text`. When you read the output through a
142
+ pipe, it's JSON: `{ "ok": true, "command": …, "data": … }`, or `"ok": false`
143
+ with `"error": { "code": …, "message": … }`. Exit codes: 0 passed, 1
144
+ failed, 2 a wrong command or flag, 130 cancelled.
145
+
146
+ ## Don't
147
+
148
+ - Don't decide pass or fail from a screenshot when a rule gives numbers.
149
+ - Don't run two loupe calls at the same time on one device.
150
+ - Don't leave the device turned or in another theme.