emd-agents 0.15.0 → 0.16.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.
package/README.md CHANGED
@@ -14,7 +14,7 @@ Status: early. Expo apps on the iOS simulator only.
14
14
 
15
15
  - A Mac with Xcode 26 or 27 and at least one iPhone simulator.
16
16
  - Node 22 or newer.
17
- - An Expo app with its dependencies installed and an iOS app ID. [Check your app](#check-your-app) shows how to check both.
17
+ - An Expo app with its dependencies installed. [Check your app](#check-your-app) shows how to check it.
18
18
 
19
19
  Tested: Expo SDK 58 on Xcode 26 and 27. On Xcode 27, apps below Expo SDK 56 can't build (Expo's bug). Use Xcode 26, or upgrade the app to SDK 56 or newer.
20
20
 
@@ -41,10 +41,7 @@ Run this yourself before you ask your agent:
41
41
  npx -y emd-agents@latest detect /path/to/my-app
42
42
  ```
43
43
 
44
- It must print `"verdict":"detected"` and an iOS app ID, for example `"appIds":{"ios":"com.example.myapp"}`. Without the ID, `launch` stops. If the ID is missing:
45
-
46
- - Add one. New Expo apps (from `create-expo-app`) have none. In `app.json`, under `expo.ios`, add `"bundleIdentifier": "com.example.myapp"`.
47
- - If the app config already has one, install the app's dependencies. EMD reads the config with the app's own Expo CLI.
44
+ It must print `"verdict":"detected"` and no `problem`. For example, `"appIds":{"ios":"com.example.myapp"}`. If the app has no iOS app ID, `detect` says so in `notes`: new Expo apps (from `create-expo-app`) have none, and `launch` lets Expo's build set one in the app config (`ios.bundleIdentifier`). EMD writes nothing to the config. Expo's first `run:ios` also creates the `ios/` folder and points the `ios` and `android` scripts in package.json at `expo run:ios` and `expo run:android`. If `problem` appears, install the app's dependencies: EMD reads the config with the app's own Expo CLI.
48
45
 
49
46
  ## First run
50
47
 
@@ -131,11 +128,11 @@ EMD is open source but does not accept pull requests from outside contributors y
131
128
  `emd mcp` serves these tools:
132
129
 
133
130
  - `detect`: finds the stack, platforms, app IDs, run commands and package manager of a folder. At a workspace root, it lists the app folders instead (`apps`).
134
- - `launch`: builds the app, installs and opens it on an iOS simulator, and keeps its dev server running. Returns a job at once.
135
- - `job_status`: the state of a job (queued, running, succeeded, failed) and, at the end, its result. It waits up to 50 s (`waitSeconds`) and returns when the job ends.
131
+ - `launch`: builds the app, installs and opens it on an iOS simulator, and keeps its dev server running. Waits up to 25 s (`waitSeconds`): a reload or relaunch returns its result, a build returns a job.
132
+ - `job_status`: the state of a job (queued, running, succeeded, failed) and, at the end, its result. It waits up to 30 s (`waitSeconds`) and returns when the job ends. In Claude Code, `setup` raises the default wait of `launch`, `check` and `job_status` to 100 s (`EMD_WAIT_SECONDS`), so a build takes fewer calls; a client that cancels a call gets the short waits again.
136
133
  - `logs`: the `[EMD:<tag>]` lines that the app wrote during the run of a launch job.
137
134
  - `tap`, `type`, `swipe`: act on the launched app. `tap` takes a testID, a visible text or a point. Each says which tool did it (AXe or Maestro).
138
- - `check`: passes or fails a run from tagged log lines and on-screen elements (by testID or text). Returns a job.
135
+ - `check`: passes or fails a run from tagged log lines and on-screen elements (by testID or text). Waits up to 25 s (`waitSeconds`) and usually returns the verdict; a longer check returns a job. It can run taps, typing and swipes first (`actions`). Each check rewrites the run's evidence folder and returns its path.
139
136
  - `evidence`: puts the checks, log lines, screenshots and Maestro flows of a run in one folder.
140
137
 
141
138
  ### CLI commands
@@ -157,7 +154,7 @@ Run them as `npx -y emd-agents@latest <command>`, or `node dist/bin.js <command>
157
154
 
158
155
  ### Requirements in detail
159
156
 
160
- - An Expo app with `expo` in package.json and `ios.bundleIdentifier` in its app config (app.json, app.config.js or app.config.ts). EMD reads it with the app's own `expo config`. Without the ID, `launch` stops: "No iOS app ID found".
157
+ - An Expo app with `expo` in package.json. EMD reads its app config (app.json, app.config.js or app.config.ts) with the app's own `expo config`. Without `ios.bundleIdentifier`, Expo's build sets one and `launch` reports it (`appIdSet`).
161
158
  - The app's dependencies, installed. EMD does not install them.
162
159
  - macOS. On other systems `detect` works, and `launch` returns "iOS simulators need macOS."
163
160
  - Xcode, tested with Xcode 26 and 27. Expo SDK 58 apps need Xcode 26 or newer. Without Xcode, `launch` fails: "Could not set up this worktree's simulator and build folders."
@@ -1,3 +1,4 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { createRequire } from "node:module";
2
3
  import { join } from "node:path";
3
4
  import { runTool } from "../../core/index.js";
@@ -8,10 +9,13 @@ async function readExpoConfig(dir) {
8
9
  try {
9
10
  const cli = createRequire(join(dir, "package.json")).resolve("expo/bin/cli");
10
11
  const { stdout } = await runTool("expo config", process.execPath, [cli, "config", dir, "--json"], 60);
11
- return JSON.parse(stdout) ?? {};
12
+ return { config: JSON.parse(stdout) ?? {} };
12
13
  }
13
- catch {
14
- return {};
14
+ catch (error) {
15
+ const line = String(error)
16
+ .split("\n")[0]
17
+ ?.replace(/^Error: /, "") ?? "";
18
+ return { config: {}, error: line.slice(0, 200) };
15
19
  }
16
20
  }
17
21
  // Expo's own fingerprint, from the project's installed Expo (never downloaded).
@@ -28,7 +32,7 @@ const nonEmpty = (value) => typeof value === "string" && value !== "" ? value :
28
32
  const adapter = {
29
33
  id: "expo",
30
34
  async detect(dir, project) {
31
- const config = await readExpoConfig(dir);
35
+ const { config, error } = await readExpoConfig(dir);
32
36
  const declared = Array.isArray(config.platforms)
33
37
  ? [...new Set(config.platforms.filter(isPlatform))]
34
38
  : [];
@@ -40,6 +44,17 @@ const adapter = {
40
44
  appIds.ios = ios;
41
45
  if (android && platforms.includes("android"))
42
46
  appIds.android = android;
47
+ // Expo sets the ID only when it generates ios/, so with ios/ and no ID
48
+ // the build would run for minutes and still find none.
49
+ const noId = platforms.includes("ios") && !appIds.ios && !error;
50
+ const hasIos = existsSync(join(dir, "ios"));
51
+ const atLaunch = "At launch, Expo's build sets ios.bundleIdentifier in the app config.";
52
+ const notes = [];
53
+ if (noId && !hasIos) {
54
+ notes.push(typeof config.bundleIdentifier === "string"
55
+ ? `bundleIdentifier is set directly under expo; Expo reads ios.bundleIdentifier, so the app has no iOS app ID. ${atLaunch}`
56
+ : `The app has no iOS app ID. ${atLaunch}`);
57
+ }
43
58
  const expo = `${project.exec} expo`;
44
59
  const run = {};
45
60
  for (const platform of platforms)
@@ -48,6 +63,14 @@ const adapter = {
48
63
  stack: "expo",
49
64
  platforms,
50
65
  appIds,
66
+ ...(error && {
67
+ problem: `The app config could not be read: ${error}. Install the app's dependencies.`,
68
+ }),
69
+ ...(noId &&
70
+ hasIos && {
71
+ problem: "The app has an ios/ folder and no ios.bundleIdentifier in the app config. Expo sets the ID only when it creates ios/. Set ios.bundleIdentifier in the app config.",
72
+ }),
73
+ ...(notes.length > 0 && { notes }),
51
74
  commands: { run, server: `${expo} start` },
52
75
  };
53
76
  },
package/dist/cli/main.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { parseArgs } from "node:util";
3
- import { check, detect, doctor, evidence, gc, jobStatus, launch, logs, resetChecks, runJob, setup, swipe, tap, typeText, version, } from "../core/index.js";
3
+ import { check, detect, doctor, evidence, gc, jobStatus, launchInline, logs, resetChecks, runJob, setup, swipe, tap, typeText, version, } from "../core/index.js";
4
4
  const usage = "Commands: detect [dir], launch [dir] [--device X] [--timeout N], job status <id>, logs <jobId> [--tag T] [--limit N], check <jobId> [--log TAG[=TEXT]] [--element id=X|text=Y] [--name N] [--agent pass|fail], check reset [dir], tap <jobId> --id X|--text Y|--x N --y N, type <jobId> [--] <text>, swipe <jobId> up|down|left|right, evidence <jobId>, gc [--apply], setup [--dry-run] [--yes] [--agent claude-code|codex|cursor], doctor, mcp";
5
5
  // --log smoke or --log smoke=tapped
6
6
  const logSpec = (raw) => {
@@ -71,7 +71,7 @@ export async function run(argv) {
71
71
  console.error(`emd: --timeout must be a number of seconds. ${usage}`);
72
72
  return 2;
73
73
  }
74
- const result = await launch({
74
+ const result = await launchInline({
75
75
  dir: positionals[0],
76
76
  device: values.device,
77
77
  timeoutSeconds,
@@ -12,6 +12,8 @@ export type StackDetection = {
12
12
  stack: StackId;
13
13
  platforms: Platform[];
14
14
  appIds: Partial<Record<Platform, string>>;
15
+ problem?: string;
16
+ notes?: string[];
15
17
  commands: {
16
18
  run: Partial<Record<Platform, string>>;
17
19
  server: string;
@@ -5,3 +5,4 @@ export type BuildRecord = {
5
5
  export declare function readBuildRecord(derivedData: string): BuildRecord | undefined;
6
6
  export declare function writeBuildRecord(derivedData: string, record: BuildRecord): void;
7
7
  export declare function whyBuild(record: BuildRecord | undefined, now: BuildRecord, installed: boolean): string | undefined;
8
+ export declare function builtApp(derivedData: string): string | undefined;
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync } from "node:fs";
1
+ import { readdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  const file = (derivedData) => join(derivedData, "emd-build.json");
4
4
  export function readBuildRecord(derivedData) {
@@ -29,3 +29,17 @@ export function whyBuild(record, now, installed) {
29
29
  return "app not installed";
30
30
  return undefined;
31
31
  }
32
+ // The one `.app` an earlier Debug build left in DerivedData (launch builds
33
+ // Debug). Undefined when there is none or more than one.
34
+ export function builtApp(derivedData) {
35
+ const dir = join(derivedData, "Build/Products/Debug-iphonesimulator");
36
+ try {
37
+ const apps = readdirSync(dir).filter((name) => name.endsWith(".app"));
38
+ return apps.length === 1 ? join(dir, apps[0] ?? "") : undefined;
39
+ }
40
+ catch (error) {
41
+ if (error.code === "ENOENT")
42
+ return undefined;
43
+ throw error;
44
+ }
45
+ }
@@ -1,20 +1,32 @@
1
1
  import { type LogSpec } from "./checkrecord.js";
2
2
  import { type ScreenRead } from "./device/backend.js";
3
3
  import { type ElementSpec } from "./device/screen.js";
4
+ import { type TapOptions } from "./input.js";
4
5
  import { type LogsOptions } from "./logs.js";
5
- import type { CheckResult, LogsResult } from "./result.js";
6
+ import type { CheckResult, EvidenceResult, InputResult, LogsResult } from "./result.js";
6
7
  import { type RunRef } from "./run.js";
7
8
  export type CheckOptions = RunRef & {
8
9
  logs?: LogSpec[];
9
10
  elements?: ElementSpec[];
10
11
  name?: string;
11
12
  agentReading?: "pass" | "fail";
13
+ actions?: CheckAction[];
14
+ };
15
+ type CheckAction = {
16
+ tap: Omit<TapOptions, "jobId">;
17
+ } | {
18
+ type: string;
19
+ } | {
20
+ swipe: string;
12
21
  };
13
22
  export type Deps = {
14
23
  logs: (options: Omit<LogsOptions, "limit">) => Promise<LogsResult>;
15
24
  screen: (device: string) => Promise<ScreenRead>;
16
25
  screenshot: (device: string, path: string) => Promise<string | undefined>;
17
26
  recheckSeconds: number;
27
+ evidence: (ref: RunRef) => Promise<EvidenceResult>;
28
+ act: (action: CheckAction, ref: RunRef) => Promise<InputResult>;
18
29
  };
19
30
  export declare const primaryDisplay: (message: string) => string | undefined;
20
31
  export declare function check(options: CheckOptions, report?: (step: string) => void, deps?: Deps): Promise<CheckResult>;
32
+ export {};
@@ -5,17 +5,29 @@ import { axeBackend } from "./device/axe.js";
5
5
  import { detectEnvironment, readScreen, } from "./device/backend.js";
6
6
  import { maestroBackend } from "./device/maestro.js";
7
7
  import { hasElement } from "./device/screen.js";
8
- import { recordCheck } from "./evidence.js";
8
+ import { recordCheck, evidence as writeEvidence } from "./evidence.js";
9
+ import { swipe, tap, typeText } from "./input.js";
9
10
  import { firstLine } from "./log.js";
10
11
  import { allLines, tagPattern, } from "./logs.js";
11
12
  import { worktreeKey } from "./owned.js";
12
13
  import { resolveRun } from "./run.js";
13
14
  import { runTool } from "./tool.js";
15
+ const maxActions = 10;
16
+ // One action through the same code as the tap, type and swipe tools.
17
+ function runAction(action, ref) {
18
+ if ("tap" in action)
19
+ return tap({ ...ref, ...action.tap });
20
+ if ("type" in action)
21
+ return typeText({ ...ref, text: action.type });
22
+ return swipe({ ...ref, direction: action.swipe });
23
+ }
14
24
  const realDeps = {
15
25
  // Measured by the result's `waited` in the e2e log. A tap through AXe
16
26
  // returns at once, and in 2 of 2 e2e runs the check after it waited 5 s.
17
27
  recheckSeconds: 10,
18
28
  logs: allLines,
29
+ evidence: (ref) => writeEvidence(ref),
30
+ act: runAction,
19
31
  screen: async (device) => readScreen(device, await detectEnvironment(), [axeBackend, maestroBackend]),
20
32
  screenshot: async (device, path) => {
21
33
  mkdirSync(dirname(path), { recursive: true });
@@ -58,6 +70,9 @@ export async function check(options, report = () => { }, deps = realDeps) {
58
70
  if (logSpecs.length > maxSpecs || elementSpecs.length > maxSpecs) {
59
71
  return error(`At most ${maxSpecs} expectations of each kind.`);
60
72
  }
73
+ if ((options.actions?.length ?? 0) > maxActions) {
74
+ return error(`At most ${maxActions} actions.`);
75
+ }
61
76
  for (const spec of logSpecs) {
62
77
  if (!tagPattern.test(spec.tag) || (spec.message?.length ?? 0) > maxText) {
63
78
  return error(`A log expectation needs a tag (letters, digits, dot, dash, underscore) and a message of at most ${maxText} characters.`);
@@ -99,6 +114,34 @@ export async function check(options, report = () => { }, deps = realDeps) {
99
114
  if (missing.length > 0) {
100
115
  return error(`Check "${name}" first expected: ${missing.join("; ")}. Keep each of these unchanged; you can add more. For a different moment, use a new name. Only a person can clear this (emd check reset).`);
101
116
  }
117
+ // Seconds each step took, like launch's phases. A step that runs again
118
+ // adds up.
119
+ const phases = {};
120
+ const timed = async (name, step) => {
121
+ const at = Date.now();
122
+ try {
123
+ return await step();
124
+ }
125
+ finally {
126
+ phases[name] =
127
+ Math.round(((phases[name] ?? 0) * 1000 + Date.now() - at) / 100) / 10;
128
+ }
129
+ };
130
+ // The actions run first, in order. A failed one stops the rest and the
131
+ // read: the check could not run, so it does not count.
132
+ const actions = [];
133
+ for (const [i, action] of (options.actions ?? []).entries()) {
134
+ const done = await timed("actions", () => deps.act(action, { jobId: options.jobId }));
135
+ actions.push(done);
136
+ if (done.verdict !== "ok") {
137
+ return {
138
+ verdict: "error",
139
+ reason: `Action ${i + 1} (${Object.keys(action)[0]}) failed: ${done.reason ?? "no reason given"}. Nothing was read.`,
140
+ actions,
141
+ phases,
142
+ };
143
+ }
144
+ }
102
145
  const byTag = new Map();
103
146
  const readLogs = async () => {
104
147
  for (const tag of new Set(logSpecs.map((spec) => spec.tag))) {
@@ -140,13 +183,13 @@ export async function check(options, report = () => { }, deps = realDeps) {
140
183
  const screenMissing = first || elementResults.some((r) => !r.found);
141
184
  if (logSpecs.length > 0 && logsMissing) {
142
185
  report(first ? "reading the logs" : "reading the logs again");
143
- const failure = await readLogs();
186
+ const failure = await timed("logs", readLogs);
144
187
  if (failure)
145
188
  return error(failure);
146
189
  }
147
190
  if (elementSpecs.length > 0 && screenMissing) {
148
191
  report(first ? "reading the screen" : "reading the screen again");
149
- const failure = await readTheScreen();
192
+ const failure = await timed("screen", readTheScreen);
150
193
  if (failure)
151
194
  return error(failure);
152
195
  }
@@ -154,7 +197,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
154
197
  const missing = [...logResults, ...elementResults].some((r) => !r.found);
155
198
  if (!missing || Date.now() - started >= deps.recheckSeconds * 1000)
156
199
  break;
157
- await new Promise((resolve) => setTimeout(resolve, 1000));
200
+ await timed("wait", () => new Promise((resolve) => setTimeout(resolve, 1000)));
158
201
  }
159
202
  const waited = Math.round((Date.now() - started) / 1000);
160
203
  const nodes = screen?.nodes ?? [];
@@ -162,7 +205,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
162
205
  report("taking a screenshot");
163
206
  const stamp = Date.now();
164
207
  const shotPath = join(logDir, `check-${stamp}.png`);
165
- const shotError = await deps.screenshot(device, shotPath);
208
+ const shotError = await timed("screenshot", () => deps.screenshot(device, shotPath));
166
209
  const shot = shotError === undefined ? shotPath : undefined;
167
210
  // What the screen reader got, next to the screenshot, for when they disagree.
168
211
  if (screen) {
@@ -177,6 +220,7 @@ export async function check(options, report = () => { }, deps = realDeps) {
177
220
  : {}),
178
221
  };
179
222
  const evidence = {
223
+ ...(actions.length > 0 ? { actions } : {}),
180
224
  ...(waited > 0 ? { waited } : {}),
181
225
  logs: logResults.length > 0 ? logResults : undefined,
182
226
  elements: elementResults.length > 0 ? elementResults : undefined,
@@ -186,8 +230,10 @@ export async function check(options, report = () => { }, deps = realDeps) {
186
230
  secondOpinion,
187
231
  };
188
232
  // Only a check that read something is a check that ran. It sets the count
189
- // (a pass starts it over) and the name's last verdict.
190
- const ran = (result) => {
233
+ // (a pass starts it over) and the name's last verdict. Then it rewrites the
234
+ // run's evidence folder, so the agent needs no evidence call (#207). A
235
+ // folder that can't be written leaves the result as it was.
236
+ const ran = async (result) => {
191
237
  recordCheck(logDir, name, result);
192
238
  writeRecord(key, {
193
239
  failures: result.verdict === "passed" ? 0 : before + 1,
@@ -196,7 +242,15 @@ export async function check(options, report = () => { }, deps = realDeps) {
196
242
  [name]: { expected: first ?? expected, last: result.verdict },
197
243
  },
198
244
  });
199
- return result;
245
+ const written = await timed("evidence", () => deps.evidence({ jobId: options.jobId }).catch(() => undefined));
246
+ if (written?.verdict !== "written")
247
+ return { ...result, phases };
248
+ return {
249
+ ...result,
250
+ evidenceDir: written.dir,
251
+ ...(written.notPassed && { notPassed: written.notPassed }),
252
+ phases,
253
+ };
200
254
  };
201
255
  if (passed)
202
256
  return ran({ verdict: "passed", ...evidence });
@@ -16,12 +16,13 @@ export async function detect(dir = ".") {
16
16
  const found = await (await loadAdapter(id)).detect(root, project);
17
17
  if (!found)
18
18
  return { verdict: "none", root };
19
+ const { notes: appNotes = [], ...rest } = found;
19
20
  return {
20
21
  verdict: "detected",
21
22
  root,
22
- ...found,
23
+ ...rest,
23
24
  packageManager: project.packageManager,
24
25
  maestroFlows,
25
- notes,
26
+ notes: [...appNotes, ...notes],
26
27
  };
27
28
  }
@@ -38,14 +38,14 @@ export function parseAxe(output) {
38
38
  }
39
39
  // The accessibility tree of what is on the simulator's screen now. AXe talks to
40
40
  // the simulator directly, with no driver to start.
41
- async function readScreen(device, bin) {
42
- const { stdout } = await runTool("axe describe-ui", bin, ["describe-ui", "--udid", device], 120);
41
+ async function readScreen(device, bin, seconds = 120) {
42
+ const { stdout } = await runTool("axe describe-ui", bin, ["describe-ui", "--udid", device], seconds);
43
43
  return parseAxe(stdout);
44
44
  }
45
45
  // One AXe command on the simulator. AXe needs no driver, so a gesture takes
46
46
  // about a second (experiments/tap-tools.md).
47
- const run = async (bin, { device }, command, args) => {
48
- await runTool(`axe ${command}`, bin, [command, "--udid", device, ...args], 60);
47
+ const run = async (bin, { device }, command, args, seconds = 60) => {
48
+ await runTool(`axe ${command}`, bin, [command, "--udid", device, ...args], seconds);
49
49
  };
50
50
  // By testID (AXUniqueId) or label (AXLabel), AXe waits up to 10 s for the
51
51
  // element to appear (the limit `check` reads again for), then taps its
@@ -61,7 +61,7 @@ export const axeBackend = {
61
61
  readScreen,
62
62
  tap: (where, bin, target) => run(bin, where, "tap", targetArgs(target)),
63
63
  // `--` so text that starts with a dash is typed, not read as an option.
64
- type: (where, bin, text) => run(bin, where, "type", ["--", text]),
64
+ type: (where, bin, text, seconds) => run(bin, where, "type", ["--", text], seconds),
65
65
  // AXe's preset scrolls 200 points through the screen's centre, the finger
66
66
  // moving the way named.
67
67
  swipe: (where, bin, direction) => run(bin, where, "gesture", [`scroll-${direction}`]),
@@ -17,9 +17,9 @@ export type Where = {
17
17
  };
18
18
  export interface DeviceBackend {
19
19
  id: BackendId;
20
- readScreen(device: string, bin: string): Promise<UiNode[]>;
20
+ readScreen(device: string, bin: string, seconds?: number): Promise<UiNode[]>;
21
21
  tap(where: Where, bin: string, target: Target): Promise<void>;
22
- type(where: Where, bin: string, text: string): Promise<void>;
22
+ type(where: Where, bin: string, text: string, seconds?: number): Promise<void>;
23
23
  swipe(where: Where, bin: string, direction: Direction): Promise<void>;
24
24
  }
25
25
  export type Environment = Partial<Record<BackendId, string>>;
@@ -35,10 +35,11 @@ export type Acted<T> = {
35
35
  export declare function firstWorking<B extends {
36
36
  id: BackendId;
37
37
  }, T>(what: string, env: Environment, backends: B[], act: (backend: B, bin: string) => Promise<T>): Promise<Acted<T>>;
38
+ export declare function secondsTo(until: number): number;
38
39
  export type ScreenRead = Omit<Acted<UiNode[]>, "value"> & {
39
40
  nodes: UiNode[];
40
41
  };
41
- export declare function readScreen(device: string, env: Environment, backends: Pick<DeviceBackend, "id" | "readScreen">[]): Promise<ScreenRead>;
42
+ export declare function readScreen(device: string, env: Environment, backends: Pick<DeviceBackend, "id" | "readScreen">[], until?: number): Promise<ScreenRead>;
42
43
  export declare function untilReadable(read: () => Promise<UiNode[]>, limitSeconds: number, whenEmpty?: {
43
44
  afterSeconds: number;
44
45
  act: () => Promise<void>;
@@ -36,9 +36,19 @@ export async function firstWorking(what, env, backends, act) {
36
36
  }
37
37
  throw new Error(`no backend could ${what} (${fellBack.map((f) => `${f.backend}: ${f.reason}`).join("; ")})`);
38
38
  }
39
- export async function readScreen(device, env, backends) {
39
+ // Seconds left until `until` (a Date.now() time), for one backend's call. When
40
+ // none are left, it throws, so no backend starts after a caller's deadline.
41
+ export function secondsTo(until) {
42
+ const seconds = (until - Date.now()) / 1000;
43
+ if (seconds <= 0)
44
+ throw new Error("no time left");
45
+ return seconds;
46
+ }
47
+ export async function readScreen(device, env, backends,
48
+ // A Date.now() time that no backend's read may pass.
49
+ until) {
40
50
  const { value, ...rest } = await firstWorking("read the screen", env, backends, async (backend, bin) => {
41
- const nodes = await backend.readScreen(device, bin);
51
+ const nodes = await backend.readScreen(device, bin, until === undefined ? undefined : secondsTo(until));
42
52
  // Every good read includes the app's root node, so none means the read
43
53
  // failed (AXe sometimes reads nothing right after a relaunch).
44
54
  if (nodes.length === 0)
@@ -34,9 +34,9 @@ const driverEnv = () => ({
34
34
  // The accessibility tree of what is on the simulator's screen now. Maestro
35
35
  // starts and stops its XCUITest driver on every call, which takes about 20 s,
36
36
  // and about 50 s for the first call after an app launch.
37
- async function readScreen(device, bin) {
37
+ async function readScreen(device, bin, seconds = 240) {
38
38
  try {
39
- const { stdout } = await runTool("maestro hierarchy", bin, ["--device", device, "hierarchy"], 240, { env: driverEnv() });
39
+ const { stdout } = await runTool("maestro hierarchy", bin, ["--device", device, "hierarchy"], seconds, { env: driverEnv() });
40
40
  return parseMaestro(stdout);
41
41
  }
42
42
  catch (error) {
@@ -54,12 +54,12 @@ async function readScreen(device, bin) {
54
54
  }
55
55
  // One step as a Maestro flow for the app. JSON strings are valid YAML
56
56
  // strings. A run takes 80 to 100 s (experiments/tap-tools.md).
57
- async function runStep({ device, appId }, bin, step) {
57
+ async function runStep({ device, appId }, bin, step, seconds = 240) {
58
58
  const dir = mkdtempSync(join(tmpdir(), "emd-maestro-"));
59
59
  try {
60
60
  const flow = join(dir, "step.yaml");
61
61
  writeFileSync(flow, `appId: ${JSON.stringify(appId)}\n---\n- ${step}\n`);
62
- await runTool("maestro test", bin, ["--device", device, "test", flow], 240, {
62
+ await runTool("maestro test", bin, ["--device", device, "test", flow], seconds, {
63
63
  env: driverEnv(),
64
64
  });
65
65
  }
@@ -81,6 +81,6 @@ export const maestroBackend = {
81
81
  id: "maestro",
82
82
  readScreen,
83
83
  tap: (where, bin, target) => runStep(where, bin, tapStep(target)),
84
- type: (where, bin, text) => runStep(where, bin, `inputText: ${JSON.stringify(text)}`),
84
+ type: (where, bin, text, seconds) => runStep(where, bin, `inputText: ${JSON.stringify(text)}`, seconds),
85
85
  swipe: (where, bin, direction) => runStep(where, bin, `swipe: { direction: ${direction.toUpperCase()} }`),
86
86
  };
@@ -0,0 +1,20 @@
1
+ import type { UiNode } from "./screen.js";
2
+ type Typing = {
3
+ type(text: string, seconds: number): Promise<void>;
4
+ read(seconds: number): Promise<UiNode[]>;
5
+ sleep(ms: number): Promise<void>;
6
+ now(): number;
7
+ };
8
+ type Typed = {
9
+ seconds: number;
10
+ retyped?: string;
11
+ } & ({
12
+ verdict: "shown";
13
+ } | {
14
+ verdict: "secure";
15
+ } | {
16
+ verdict: "failed";
17
+ reason: string;
18
+ });
19
+ export declare function typeUntilShown(io: Typing, text: string, limitSeconds?: number, pauseMs?: number): Promise<Typed>;
20
+ export {};
@@ -0,0 +1,120 @@
1
+ const bullets = /^•+$/;
2
+ // A node is its id plus its place among nodes with that id.
3
+ function keyed(nodes) {
4
+ const seen = new Map();
5
+ const out = new Map();
6
+ for (const node of nodes) {
7
+ const n = seen.get(node.id) ?? 0;
8
+ seen.set(node.id, n + 1);
9
+ out.set(`${node.id}#${n}`, node.texts);
10
+ }
11
+ return out;
12
+ }
13
+ function judge(before, nodes, text) {
14
+ let found = { kind: "none" };
15
+ for (const [key, texts] of keyed(nodes)) {
16
+ const old = before.get(key) ?? [];
17
+ const olds = ["", ...old];
18
+ for (const shown of texts.filter((t) => !old.includes(t))) {
19
+ if (olds.some((o) => shown === o + text || shown === text)) {
20
+ return { kind: "shown" };
21
+ }
22
+ const oldBullets = Math.max(0, ...old.filter((o) => bullets.test(o)).map((o) => o.length));
23
+ if (bullets.test(shown) && shown.length === oldBullets + text.length) {
24
+ return { kind: "secure" };
25
+ }
26
+ if (shown.includes(text))
27
+ found = { kind: "extra", shown };
28
+ else if (found.kind === "none") {
29
+ for (const o of olds) {
30
+ const rest = shown.startsWith(o) ? shown.slice(o.length) : "";
31
+ if (rest && rest.length < text.length && text.startsWith(rest)) {
32
+ found = { kind: "partial", key, have: rest.length, shown };
33
+ break;
34
+ }
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return found;
40
+ }
41
+ // What the screen shows, in one short phrase, for a failure message.
42
+ function describeScreen(nodes) {
43
+ const texts = [...new Set(nodes.flatMap((node) => node.texts))].slice(0, 8);
44
+ return texts.length > 0
45
+ ? `the screen shows ${texts.map((t) => JSON.stringify(t.slice(0, 40))).join(", ")}`
46
+ : "the screen shows no text";
47
+ }
48
+ // Types `text`, then reads until it shows. The whole call, from the read before
49
+ // typing, takes at most `limitSeconds`: each step gets only the time left, and
50
+ // no step starts after the limit. The MCP client gives up at 60 s.
51
+ //
52
+ // If the screen stays the same for half the limit, types the missing rest once
53
+ // (all of it when no key arrived). Late keys come 10 to 27 s late, so a shorter
54
+ // wait doubles text. Doubled text fails the exact match, so a retype can never
55
+ // give a false `ok`.
56
+ export async function typeUntilShown(io, text, limitSeconds = 40, pauseMs = 1000) {
57
+ const start = io.now();
58
+ const end = start + limitSeconds * 1000;
59
+ const left = () => Math.max(0, (end - io.now()) / 1000);
60
+ const seconds = () => Math.round((io.now() - start) / 100) / 10;
61
+ let retyped;
62
+ const failed = (reason) => ({
63
+ verdict: "failed",
64
+ seconds: seconds(),
65
+ ...(retyped ? { retyped } : {}),
66
+ reason,
67
+ });
68
+ let last = await io.read(left());
69
+ const before = keyed(last);
70
+ if (left() === 0) {
71
+ return failed(`Reading the screen before typing took ${seconds()} s.`);
72
+ }
73
+ await io.type(text, left());
74
+ let lastError = "";
75
+ let state = "";
76
+ let since = io.now();
77
+ for (;;) {
78
+ if (left() === 0) {
79
+ const error = lastError
80
+ ? `; the last read failed: ${lastError.split("\n")[0]}`
81
+ : "";
82
+ return failed(`The text did not show on screen after ${seconds()} s${retyped ? " and one retype" : ""}; ${describeScreen(last)}${error}.`);
83
+ }
84
+ let rest;
85
+ try {
86
+ last = await io.read(left());
87
+ lastError = "";
88
+ const judged = judge(before, last, text);
89
+ if (judged.kind === "shown" || judged.kind === "secure") {
90
+ return {
91
+ verdict: judged.kind,
92
+ seconds: seconds(),
93
+ ...(retyped ? { retyped } : {}),
94
+ };
95
+ }
96
+ if (judged.kind === "extra") {
97
+ return failed(`The field shows ${JSON.stringify(judged.shown.slice(0, 80))}: more than the typed text.`);
98
+ }
99
+ const now = judged.kind === "partial" ? `${judged.key}=${judged.shown}` : "";
100
+ if (now !== state) {
101
+ state = now;
102
+ since = io.now();
103
+ }
104
+ else if (!retyped && io.now() - since >= (end - start) / 2) {
105
+ rest = text.slice(judged.kind === "partial" ? judged.have : 0);
106
+ }
107
+ }
108
+ catch (error) {
109
+ // A failed read says nothing about the text; read again.
110
+ lastError = error instanceof Error ? error.message : String(error);
111
+ }
112
+ // Outside the try: a failed retype must fail the call, not be read again.
113
+ if (rest && left() > 0) {
114
+ retyped = rest;
115
+ await io.type(rest, left());
116
+ }
117
+ if (left() > 0)
118
+ await io.sleep(Math.min(pauseMs, left() * 1000));
119
+ }
120
+ }
@@ -7,8 +7,7 @@ export { type DoctorResult, doctor } from "./doctor.js";
7
7
  export { evidence } from "./evidence.js";
8
8
  export { type GcResult, gc } from "./gc.js";
9
9
  export { swipe, tap, typeText } from "./input.js";
10
- export { jobStatus, runJob, startJob, waitForJob } from "./jobs.js";
11
- export { launch } from "./launch.js";
10
+ export { jobStatus, launchInline, runJob, startJob, waitForJob, } from "./jobs.js";
12
11
  export { logs } from "./logs.js";
13
12
  export { loadedAdapters } from "./registry.js";
14
13
  export { type CheckResult, checkResultSchema, type DetectResult, detectResultSchema, type EvidenceResult, evidenceResultSchema, type InputResult, inputResultSchema, type JobView, jobViewSchema, type LaunchResult, type LogsResult, launchResultSchema, logsResultSchema, } from "./result.js";
@@ -6,8 +6,7 @@ export { doctor } from "./doctor.js";
6
6
  export { evidence } from "./evidence.js";
7
7
  export { gc } from "./gc.js";
8
8
  export { swipe, tap, typeText } from "./input.js";
9
- export { jobStatus, runJob, startJob, waitForJob } from "./jobs.js";
10
- export { launch } from "./launch.js";
9
+ export { jobStatus, launchInline, runJob, startJob, waitForJob, } from "./jobs.js";
11
10
  export { logs } from "./logs.js";
12
11
  export { loadedAdapters } from "./registry.js";
13
12
  export { checkResultSchema, detectResultSchema, evidenceResultSchema, inputResultSchema, jobViewSchema, launchResultSchema, logsResultSchema, } from "./result.js";