mobile-automator 0.31.2 → 0.32.0

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.
@@ -12,6 +12,7 @@ const fs = require('fs');
12
12
 
13
13
  const { startDaemon } = require('../src/device/session-daemon');
14
14
  const paths = require('../src/device/session-paths');
15
+ const { sessionEngineFromEnv } = require('../src/device/engine');
15
16
  const { boundRecorder } = require('../src/observe/recorder');
16
17
  const { daemonEventLogPath } = require('../src/observe/paths');
17
18
  const { makeFlusher } = require('../src/observe/flush');
@@ -66,6 +67,9 @@ async function main() {
66
67
  const device = process.env.MAUTO_SESSION_DEVICE || null;
67
68
  const idleRaw = process.env.MAUTO_SESSION_IDLE_MS;
68
69
  const idleMs = idleRaw ? Number(idleRaw) : undefined;
70
+ // The engine the spawner resolved (MAUTO_SESSION_ENGINE / _SOURCE), or —
71
+ // when started without one — what this process's own env resolves to (#251).
72
+ const { engine, source: engineSource } = sessionEngineFromEnv(process.env);
69
73
 
70
74
  // Where this process's events go: its own log file (daemon.ndjson, not the
71
75
  // CLI's mauto.ndjson — see observe/paths.js). `env` is read once and the log
@@ -146,6 +150,8 @@ async function main() {
146
150
  daemon = await startDaemon({
147
151
  projectRoot,
148
152
  device,
153
+ engine,
154
+ engineSource,
149
155
  idleMs,
150
156
  recorderFor,
151
157
  // Same defensive shape as recorderFor's own construction guarantee: a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mobile-automator",
3
- "version": "0.31.2",
3
+ "version": "0.32.0",
4
4
  "description": "Host-agnostic mauto CLI for AI-driven mobile QA automation — analyzes a mobile project and drives devices through mobile-mcp.",
5
5
  "homepage": "https://github.com/sh3lan93/mobile-automator#readme",
6
6
  "repository": {
package/src/cli.js CHANGED
@@ -33,7 +33,7 @@ const { record } = require('./observe/recorder');
33
33
  const { resolveRunId } = require('./observe/settings');
34
34
  const { runTracePath } = require('./observe/paths');
35
35
  const { readTrace, deriveRun, pruneRunTraces } = require('./observe/trace');
36
- const { readHandle, readSessionId } = require('./device/session-handle');
36
+ const { readSessionId } = require('./device/session-handle');
37
37
  const { captureOnFailure } = require('./observe/failure-capture');
38
38
  const { crashTimestampMs } = require('./device/crash-model');
39
39
  const { probeCrashes } = require('./device/failure-probe');
@@ -894,7 +894,7 @@ function handleConfigGet({ projectRoot }, key) {
894
894
  // Coerce the raw CLI string into the type config_schema.json declares for this
895
895
  // key, then validate that one key before writing. Per-key (not whole-document)
896
896
  // so unrelated pre-existing drift never blocks an otherwise-valid write.
897
- function handleConfigSet({ projectRoot }, key, rawValue) {
897
+ function handleConfigSet({ projectRoot, env = process.env, store = selectionStore }, key, rawValue) {
898
898
  const value = coerceValue(key, rawValue);
899
899
  const { valid, errors } = validateAt(key, value);
900
900
  if (!valid) {
@@ -907,10 +907,54 @@ function handleConfigSet({ projectRoot }, key, rawValue) {
907
907
  exitKind: 'invalid_input',
908
908
  };
909
909
  }
910
+ if (key === 'engine') return setEngine({ projectRoot, env, store }, value);
910
911
  configManager.set(projectRoot, key, value);
911
912
  return { envelope: ok({ key, value }), exitKind: 'ok' };
912
913
  }
913
914
 
915
+ // #251: switching the engine invalidates device ids — the default robot lists
916
+ // Android emulators by AVD name, the legacy one by adb serial — so a persisted
917
+ // `devices use` selection is cleared rather than left to fail every verb. The
918
+ // session is NOT ended here: the next device verb restarts a daemon running
919
+ // the stale engine on its own. Setting the effective value again (a missing
920
+ // key is the default) is a plain write with no side effects.
921
+ function setEngine({ projectRoot, env, store }, value) {
922
+ const engineModule = require('./device/engine');
923
+ const stored = configManager.get(projectRoot, 'engine');
924
+ const previous = engineModule.isEngine(stored) ? stored : engineModule.DEFAULT_ENGINE;
925
+ configManager.set(projectRoot, 'engine', value);
926
+ if (value === previous) return { envelope: ok({ key: 'engine', value }), exitKind: 'ok' };
927
+
928
+ const cleared = store.read(projectRoot) != null;
929
+ store.clear(projectRoot);
930
+ // The engine that will actually run: an exported MOBILEMCP_LEGACY_ROBOT
931
+ // beats the key, so promising a restart onto `value` would be a lie.
932
+ const resolved = engineModule.resolveEngine({ config: { engine: value }, env });
933
+ const overridden = resolved.source === 'env';
934
+ const hints = [
935
+ overridden
936
+ ? `MOBILEMCP_LEGACY_ROBOT is exported in this environment and overrides the engine key — the ${resolved.engine} engine keeps running until you unset it.`
937
+ : `Engine switched from ${previous} to ${value}; the next device verb restarts the session on it.`,
938
+ 'Device ids differ between engines (Android emulators: AVD name on mobilecli, adb serial on legacy) — ' +
939
+ (cleared
940
+ ? 'the persisted device selection was cleared; run `mauto devices`, then `mauto devices use <id>` to pin one again.'
941
+ : 'if you pin a device, take its id from `mauto devices`, then `mauto devices use <id>`.'),
942
+ ];
943
+ if (resolved.engine === 'legacy') {
944
+ hints.push(
945
+ 'On Android, if a verb then fails with a uiautomator error, a leftover mobilecli DeviceServer is holding ' +
946
+ 'UiAutomation: run `adb shell pkill -f com.mobilenext.mobilecli.DeviceServer` (upstream mobilecli#470).'
947
+ );
948
+ }
949
+ return {
950
+ envelope: ok(
951
+ { key: 'engine', value, previous, device_selection_cleared: cleared },
952
+ hints.join(' ')
953
+ ),
954
+ exitKind: 'ok',
955
+ };
956
+ }
957
+
914
958
  // --- Slice 5: telemetry consent surface -----------------------------------
915
959
  //
916
960
  // `status` is the informed half of informed consent, and it is COMPUTED: the
@@ -1245,7 +1289,12 @@ async function handleSessionStart(
1245
1289
  projectRoot,
1246
1290
  spawn = require('./device/session-spawn'),
1247
1291
  client = require('./device/session-client'),
1248
- readHandle: readHandleDevice = require('./device/resolve-connection').readHandleDevice,
1292
+ // The live daemon's handle — ONE read; the device pin and the engine are
1293
+ // both projections of it below (session-handle.js owns the file).
1294
+ readHandle = require('./device/session-handle').readHandle,
1295
+ // #251: the workspace's engine, and the one decoder of the handle's.
1296
+ resolveEngine = require('./device/engine').readEngine,
1297
+ handleEngine = require('./device/engine').handleEngine,
1249
1298
  },
1250
1299
  opts = {}
1251
1300
  ) {
@@ -1268,7 +1317,8 @@ async function handleSessionStart(
1268
1317
  // pinned to A reported already_running:true, device:B while every verb
1269
1318
  // kept driving A. Fail with a hint instead — the agent stays in control
1270
1319
  // and decides whether to `session end` and repin.
1271
- const pinned = readHandleDevice(projectRoot);
1320
+ const handle = readHandle(projectRoot);
1321
+ const pinned = (handle && handle.device) || null;
1272
1322
  if (device !== null && device !== pinned) {
1273
1323
  return {
1274
1324
  envelope: fail(
@@ -1280,13 +1330,23 @@ async function handleSessionStart(
1280
1330
  exitKind: 'device',
1281
1331
  };
1282
1332
  }
1333
+ // The live daemon's engine, not the resolved one: reporting the resolved
1334
+ // engine here would repeat #148's lie for the robot instead of the device.
1335
+ // A stale engine is not an error — the next device verb restarts the
1336
+ // daemon on the resolved one — but it is worth saying.
1337
+ const running = handleEngine(handle);
1338
+ const resolved = resolveEngine(projectRoot);
1283
1339
  return {
1284
- envelope: ok({ started: false, already_running: true, device }),
1340
+ envelope: ok(
1341
+ { started: false, already_running: true, device, engine: running },
1342
+ running !== resolved.engine ? staleEngineHint(running, resolved.engine, resolved.source) : null
1343
+ ),
1285
1344
  exitKind: 'ok',
1286
1345
  };
1287
1346
  }
1288
1347
 
1289
- const started = await connection.startSession({ projectRoot, device, idleMs, spawn });
1348
+ const { engine, source: engineSource } = resolveEngine(projectRoot);
1349
+ const started = await connection.startSession({ projectRoot, device, idleMs, engine, engineSource, spawn });
1290
1350
  if (!started) {
1291
1351
  // The daemon's stdout/stderr are captured to the workspace log, so the
1292
1352
  // "why" of a startup crash exists on disk — but only this hint tells the
@@ -1298,17 +1358,30 @@ async function handleSessionStart(
1298
1358
  exitKind: 'device',
1299
1359
  };
1300
1360
  }
1301
- return { envelope: ok({ started: true, device }), exitKind: 'ok' };
1361
+ return { envelope: ok({ started: true, device, engine }), exitKind: 'ok' };
1362
+ }
1363
+
1364
+ // A live daemon on a different engine than the workspace resolves (#251).
1365
+ // Plain strings, not a reconstituted {engine, source} object: both callers
1366
+ // already have the fields as fields.
1367
+ function staleEngineHint(runningEngine, resolvedEngine, resolvedSource) {
1368
+ return `The running session uses the ${runningEngine} engine, but this workspace resolves ${resolvedEngine} (from ${resolvedSource}); the next device verb will restart the session on ${resolvedEngine}.`;
1302
1369
  }
1303
1370
 
1304
1371
  async function handleSessionStatus(
1305
- { projectRoot, client = require('./device/session-client') } = {}
1372
+ {
1373
+ projectRoot,
1374
+ client = require('./device/session-client'),
1375
+ resolveEngine = require('./device/engine').readEngine,
1376
+ } = {}
1306
1377
  ) {
1307
- const status = await connection.sessionStatus(projectRoot, { client });
1308
- const hint =
1309
- status.reason === 'engine_exited'
1310
- ? `The device engine exited; this session is shutting down and the next verb starts a fresh one. ${connection.daemonLogHint(projectRoot)}`
1311
- : null;
1378
+ const status = await connection.sessionStatus(projectRoot, { client, resolveEngine });
1379
+ let hint = null;
1380
+ if (status.reason === 'engine_exited') {
1381
+ hint = `The device engine exited; this session is shutting down and the next verb starts a fresh one. ${connection.daemonLogHint(projectRoot)}`;
1382
+ } else if (status.running && status.engine !== status.resolved_engine) {
1383
+ hint = staleEngineHint(status.engine, status.resolved_engine, status.resolved_engine_source);
1384
+ }
1312
1385
  return { envelope: ok(status, hint), exitKind: 'ok' };
1313
1386
  }
1314
1387
 
@@ -1328,7 +1401,11 @@ const SESSION_END_FAILURE_HINTS = {
1328
1401
  async function handleSessionEnd(
1329
1402
  { projectRoot, client = require('./device/session-client'), end = {} } = {}
1330
1403
  ) {
1331
- const { outcome, pid } = await connection.endSession(projectRoot, { client, ...end });
1404
+ // session-end.js, not the connection facade: the same module the stale-engine
1405
+ // restart goes through (resolve-connection.js), so `session end` and an
1406
+ // engine switch report identical outcomes for an identical daemon.
1407
+ const { endSession } = require('./device/session-end');
1408
+ const { outcome, pid } = await endSession(projectRoot, { client, ...end });
1332
1409
  const logHint = connection.daemonLogHint(projectRoot);
1333
1410
  if (Object.prototype.hasOwnProperty.call(SESSION_END_FAILURE_HINTS, outcome)) {
1334
1411
  const pidFile = require('./device/session-paths').pidFilePath(projectRoot);
@@ -1426,7 +1503,9 @@ async function handleDevicesClear({
1426
1503
  store = selectionStore,
1427
1504
  projectRoot,
1428
1505
  isAlive = require('./device/connection').isSessionAlive,
1429
- readHandle: readHandleDevice = require('./device/resolve-connection').readHandleDevice,
1506
+ // The live daemon's handle, same seam as handleSessionStart: one read, the
1507
+ // pin is a projection of it.
1508
+ readHandle = require('./device/session-handle').readHandle,
1430
1509
  } = {}) {
1431
1510
  const previous = store.read(projectRoot);
1432
1511
  store.clear(projectRoot);
@@ -1438,7 +1517,8 @@ async function handleDevicesClear({
1438
1517
  if (!alive) {
1439
1518
  return { envelope: ok({ cleared: previous || null }), exitKind: 'ok' };
1440
1519
  }
1441
- const pinned = readHandleDevice(projectRoot);
1520
+ const handle = readHandle(projectRoot);
1521
+ const pinned = (handle && handle.device) || null;
1442
1522
  return {
1443
1523
  envelope: ok(
1444
1524
  { cleared: previous || null, daemon_still_pinned: pinned },
@@ -1464,6 +1544,7 @@ const CRASH_LIST_HINT =
1464
1544
  // begin". No handle means no watermark, which means UNSCOPED, which the envelope
1465
1545
  // reports as `since: null` rather than pretending the list is recent.
1466
1546
  function sessionWatermark(projectRoot) {
1547
+ const { readHandle } = require('./device/session-handle');
1467
1548
  const handle = readHandle(projectRoot);
1468
1549
  const t = handle && handle.started_at;
1469
1550
  return typeof t === 'string' && Number.isFinite(Date.parse(t)) ? t : null;
@@ -8,20 +8,20 @@
8
8
  // lives privately in resolve-connection.js; this module is the ONE place the
9
9
  // rest of the app reaches for a connection.
10
10
  //
11
- // It also owns the session lifecycle ops (is a daemon alive / spawn one / shut
12
- // one down) so "should I reuse, spawn, or stop the daemon" has a single owner
13
- // instead of being re-wired independently by the verb path and the lifecycle
14
- // handlers.
11
+ // It also fronts the session lifecycle ops (is a daemon alive / spawn one)
12
+ // so "should I reuse, spawn, or stop the daemon" has a single owner instead of
13
+ // being re-wired independently by the verb path and the lifecycle handlers.
14
+ // Ending one is the one exception: endSession lives in session-end.js, which
15
+ // this facade AND resolve-connection.js (the stale-engine restart, #251) both
16
+ // reach downward — resolve-connection must not require this module back.
15
17
 
16
18
  const { resolveDeviceConnection } = require('./resolve-connection');
17
- const { readSessionId } = require('./session-handle');
19
+ const { readHandle, readSessionId } = require('./session-handle');
20
+ const { readEngine, handleEngine } = require('./engine');
18
21
  const { daemonLogHint } = require('./session-log');
19
22
  const paths = require('./session-paths');
20
23
  const sessionClient = require('./session-client');
21
24
  const sessionSpawn = require('./session-spawn');
22
- const sessionDaemon = require('./session-daemon');
23
- const processIdentity = require('./process-identity');
24
- const processReaper = require('./process-reaper');
25
25
 
26
26
  // Acquire a device connection, transparently reusing a live daemon when one
27
27
  // fits and falling back to a one-shot mobile-mcp spawn otherwise. Returns
@@ -62,8 +62,21 @@ function isSessionAlive(projectRoot, { client = sessionClient } = {}) {
62
62
  // case where a user is reaching for `session status` to find out why the daemon
63
63
  // is dead. The path is a pure function of the workspace, so we can always
64
64
  // answer it. Do not "simplify" this into the ping payload.
65
- async function sessionStatus(projectRoot, { client = sessionClient } = {}) {
65
+ //
66
+ // The engine (#251) is reported twice, on purpose. engine/engine_source are the
67
+ // LIVE daemon's, read from its handle (null when not running, like session_id;
68
+ // a pre-#251 handle without one is mobilecli with an unknown source).
69
+ // resolved_engine/resolved_engine_source are what this workspace resolves now —
70
+ // what the next spawn would use — and are always present. When they differ the
71
+ // daemon is stale and the next device verb restarts it.
72
+ async function sessionStatus(
73
+ projectRoot,
74
+ { client = sessionClient, resolveEngine = readEngine } = {}
75
+ ) {
66
76
  const status = await client.getSessionStatus(projectRoot);
77
+ const running = !!(status && status.running);
78
+ const handle = running ? readHandle(projectRoot) : null;
79
+ const resolved = resolveEngine(projectRoot);
67
80
  return {
68
81
  ...status,
69
82
  // Always present (#156): null, or why a reachable daemon is not running.
@@ -78,81 +91,24 @@ async function sessionStatus(projectRoot, { client = sessionClient } = {}) {
78
91
  // purpose (a dead daemon's log is exactly what you want then). A SIGKILLed
79
92
  // daemon leaves its handle behind, so reporting that id alongside
80
93
  // running:false would name a session that no longer exists.
81
- session_id: status && status.running ? readSessionId(projectRoot) : null,
94
+ session_id: running ? readSessionId(projectRoot) : null,
95
+ engine: running ? handleEngine(handle) : null,
96
+ engine_source: (handle && handle.engine_source) || null,
97
+ resolved_engine: resolved.engine,
98
+ resolved_engine_source: resolved.source,
82
99
  };
83
100
  }
84
101
 
85
102
  // Spawn a daemon and wait until it answers. Resolves true on success.
86
- function startSession({ projectRoot, device = null, idleMs, spawn = sessionSpawn } = {}) {
87
- return spawn.spawnDaemon({ projectRoot, device, idleMs });
88
- }
89
-
90
- // How long `session end` waits for an acknowledged daemon to exit before it
91
- // treats it as stuck: stop() drains in-flight calls (bounded by the daemon call
92
- // timeout) and then closes the engine (the SDK's ~4s ladder). Derived, not
93
- // restated; pinned by tests/unit/device/timeout-invariant.test.js.
94
- const END_BUDGET_MS = sessionDaemon.DAEMON_CALL_TIMEOUT_MS + 10000;
95
-
96
- // Stop the daemon and report only what is true (#156). The daemon acks the
97
- // shutdown frame BEFORE its teardown runs, so an ack is a promise, not a fact:
98
- // 'stopped' is reported only once the pid is gone.
99
- //
100
- // Returns { outcome, pid } — ONE discriminated answer, so a caller dispatches
101
- // on what happened instead of re-deriving it from a bag of booleans:
102
- // 'stopped' - acked, and the pid exited (or there was no pid to watch)
103
- // 'already_stopped' - nothing acked and nothing of ours was running
104
- // 'forced' - ours, stuck in teardown, terminated by a group kill
105
- // 'survived' - ours, stuck, and still alive after SIGTERM + SIGKILL
106
- // 'foreign' - acked, but the live pid's command line does not name
107
- // this workspace, so it was reported, never signalled
108
- // 'unverified' - the pid could not be identified (`ps` failed), so it
109
- // was never signalled
110
- // The last three are failures: a daemon may still be alive.
111
- async function endSession(
103
+ function startSession({
112
104
  projectRoot,
113
- {
114
- client = sessionClient,
115
- reaper = processReaper,
116
- // Bound to THIS workspace (#156): a group kill must never reach another
117
- // workspace's daemon through a copied or recycled pidfile.
118
- identify = (pid) => processIdentity.pidIdentity(pid, { projectRoot }),
119
- readPid = () => processIdentity.readPidFile(paths.pidFilePath(projectRoot)),
120
- budgetMs = END_BUDGET_MS,
121
- } = {}
122
- ) {
123
- // Read BEFORE asking: a daemon that exits cleanly removes its pidfile, and we
124
- // need to know whom to watch.
125
- const pid = readPid();
126
- const acked = await client.requestShutdown(projectRoot);
127
- const report = (outcome) => ({ outcome, pid: pid || null });
128
- // The daemon is gone: it stopped because we asked, or was never running.
129
- const gone = () => report(acked ? 'stopped' : 'already_stopped');
130
-
131
- // No pidfile: nothing to watch, so the ack is all we have (as before). Our
132
- // own pid: the in-process daemon of a test — never wait on it, never signal it.
133
- if (!pid || pid === process.pid) return gone();
134
-
135
- // A non-acking daemon whose pidfile names a live process is checked at once
136
- // (budget 0): either it is gone, or it is stuck too badly to answer.
137
- if (await reaper.waitForDeath(pid, { budgetMs: acked ? budgetMs : 0 })) return gone();
138
-
139
- switch (identify(pid)) {
140
- case 'dead':
141
- case 'other': // the pid was recycled: our daemon is gone
142
- return gone();
143
- case 'foreign':
144
- // A mauto daemon whose command line does not name this workspace:
145
- // another workspace's, reached through a copied or recycled pidfile.
146
- // Never signalled. Without an ack nothing answered on OUR socket, so none
147
- // of ours was running. With an ack the daemon that answered is ours, but
148
- // its command line cannot prove it (one started before the workspace
149
- // marker), so it is reported rather than killed.
150
- return report(acked ? 'foreign' : 'already_stopped');
151
- case 'ours':
152
- return report((await reaper.terminate(pid, { group: true })) === 'dead' ? 'forced' : 'survived');
153
- default: // 'unknown': never signal a process we cannot identify
154
- return report('unverified');
155
- }
105
+ device = null,
106
+ idleMs,
107
+ engine,
108
+ engineSource,
109
+ spawn = sessionSpawn,
110
+ } = {}) {
111
+ return spawn.spawnDaemon({ projectRoot, device, idleMs, engine, engineSource });
156
112
  }
157
113
 
158
114
  module.exports = {
@@ -164,6 +120,4 @@ module.exports = {
164
120
  isSessionAlive,
165
121
  sessionStatus,
166
122
  startSession,
167
- endSession,
168
- END_BUDGET_MS,
169
123
  };
@@ -36,6 +36,56 @@ function nullable(v) {
36
36
  return v === undefined || v === null || v === '' ? null : v;
37
37
  }
38
38
 
39
+ // The legacy robot (MOBILEMCP_LEGACY_ROBOT=1) reads uiautomator XML and hands
40
+ // attribute values back still entity-escaped: a Flutter nav label arrives as
41
+ // `Home&#10;Tab 1 of 3` instead of `Home\nTab 1 of 3` (#251). Decode numeric
42
+ // (decimal / hex) references and the five XML named entities in ONE pass, so
43
+ // `&amp;#10;` becomes the literal `&#10;` rather than a newline. Unknown named
44
+ // entities and out-of-range code points are left exactly as received.
45
+ const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
46
+ const ENTITY_RE = /&(?:#(\d+)|#[xX]([0-9a-fA-F]+)|([a-zA-Z]+));/g;
47
+
48
+ function decodeEntities(value) {
49
+ if (typeof value !== 'string' || !value.includes('&')) return value;
50
+ return value.replace(ENTITY_RE, (whole, dec, hex, name) => {
51
+ if (name !== undefined) {
52
+ return Object.prototype.hasOwnProperty.call(NAMED_ENTITIES, name) ? NAMED_ENTITIES[name] : whole;
53
+ }
54
+ const code = dec !== undefined ? parseInt(dec, 10) : parseInt(hex, 16);
55
+ return Number.isInteger(code) && code >= 0 && code <= 0x10ffff ? String.fromCodePoint(code) : whole;
56
+ });
57
+ }
58
+
59
+ // The legacy robot also reports every Flutter field twice with identical
60
+ // bounds: once carrying the semantics label (`Name`) and once with neither
61
+ // text nor label. Drop the bare twin when a labeled element shares its bounds.
62
+ // Safe for every NON-empty target: a target only ever matches on text or label
63
+ // (see `matches()` in src/assertion/evaluator.js), so the bare twin can never
64
+ // be what a step or a targeted assertion resolves to, and its geometry survives
65
+ // on the labeled sibling. A bare element with no labeled twin is kept — it
66
+ // still occupies the screen. Order is kept.
67
+ //
68
+ // The one place the collapse IS visible: `matches()` treats a null/empty target
69
+ // as matching ALL elements, so an `element_count` / `list_item_count` /
70
+ // `list_is_empty` assertion with NO target counts the whole list — and the
71
+ // collapse changes that count, on every engine (a native bare wrapper sharing
72
+ // its labeled child's bounds drops too). That is deliberate: the pre-collapse
73
+ // count double-counted each twin and counted a wrapper no target could ever
74
+ // reach. Pinned by the empty-target count test below the collapse tests, which
75
+ // uses the evaluator's own countMatching.
76
+ function isBare(e) {
77
+ return e.text === null && e.accessibility_label === null;
78
+ }
79
+
80
+ function collapseUnlabeledTwins(elements) {
81
+ const labeledBounds = new Set(elements.filter((e) => !isBare(e)).map((e) => e.bounds.join(',')));
82
+ return elements.filter((e) => !(isBare(e) && labeledBounds.has(e.bounds.join(','))));
83
+ }
84
+
85
+ // Both rules above are engine-independent. On the default engine (mobilecli)
86
+ // labels carry no references, but the collapse still fires on native layouts:
87
+ // a bare wrapper container (FrameLayout/ViewGroup) sharing bounds with its
88
+ // labeled child is dropped — equally unmatchable, so equally safe.
39
89
  function normalize(rawElements) {
40
90
  if (!Array.isArray(rawElements)) return [];
41
91
 
@@ -46,16 +96,16 @@ function normalize(rawElements) {
46
96
  if (!bounds) continue; // can't position it -> not useful, skip
47
97
 
48
98
  out.push({
49
- text: nullable(raw.text),
99
+ text: nullable(decodeEntities(raw.text)),
50
100
  accessibility_label: nullable(
51
- raw.accessibility_label !== undefined ? raw.accessibility_label : raw.label
101
+ decodeEntities(raw.accessibility_label !== undefined ? raw.accessibility_label : raw.label)
52
102
  ),
53
103
  bounds,
54
104
  center: centerOf(bounds),
55
105
  type: nullable(raw.type),
56
106
  });
57
107
  }
58
- return out;
108
+ return collapseUnlabeledTwins(out);
59
109
  }
60
110
 
61
111
  // Short, single-line excerpt of an unparseable payload for the error message:
@@ -101,4 +151,4 @@ function parseElements(raw) {
101
151
  throw err;
102
152
  }
103
153
 
104
- module.exports = { normalize, parseElements };
154
+ module.exports = { normalize, parseElements, decodeEntities, collapseUnlabeledTwins };
@@ -55,14 +55,17 @@ function missingAgentHint(message, resolver) {
55
55
  }
56
56
 
57
57
  // B2: mobile-mcp 1.0.5's default robot lists Android emulators by AVD name,
58
- // MOBILEMCP_LEGACY_ROBOT=1 (and 0.0.55) by adb serial, and each rejects the
59
- // other's id — so a selection persisted before the upgrade fails every verb.
58
+ // the legacy robot (and 0.0.55) by adb serial, and each rejects the other's id
59
+ // — so a selection made under the other engine fails every verb. Since #251
60
+ // the workspace `engine` key selects the robot; the env var still overrides it.
60
61
  function deviceNotFoundHint(id) {
61
62
  return (
62
- `Device "${id}" is not known to the current engine. Device ids can differ between engines: ` +
63
- "mauto 0.27's default engine lists Android emulators by AVD name (e.g. Pixel_9_Pro), while " +
64
- 'MOBILEMCP_LEGACY_ROBOT=1 uses the adb serial (e.g. emulator-5554). Run `mauto devices`, then ' +
65
- '`mauto devices use` with an id from that list (or pass that id to --device).'
63
+ `Device "${id}" is not known to the current engine. Device ids differ between engines: ` +
64
+ 'the default mobilecli engine lists Android emulators by AVD name (e.g. Pixel_9_Pro), while the ' +
65
+ 'legacy engine uses the adb serial (e.g. emulator-5554). Check which engine this workspace uses with ' +
66
+ '`mauto config get engine` and change it with `mauto config set engine <mobilecli|legacy>`; an exported ' +
67
+ 'MOBILEMCP_LEGACY_ROBOT overrides that key. Then run `mauto devices` and `mauto devices use` with an id ' +
68
+ 'from that list (or pass that id to --device).'
66
69
  );
67
70
  }
68
71
 
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ // Which mobile-mcp device robot ("engine") drives the device (#251).
4
+ //
5
+ // mobile-mcp picks its robot once per process from MOBILEMCP_LEGACY_ROBOT: the
6
+ // exact string "1" selects the legacy robot (adb/uiautomator on Android,
7
+ // go-ios/WDA on real iOS devices), anything else the default mobilecli robot.
8
+ // iOS simulators always use mobilecli. The workspace `engine` config key lets a
9
+ // user choose the legacy robot without exporting the variable; the default
10
+ // stays mobilecli.
11
+ //
12
+ // The engine list and default are read from config_schema.json — the single
13
+ // source of truth for the key — rather than restated here.
14
+
15
+ const configSchema = require('../schemas/config_schema.json');
16
+ const manager = require('../config/manager');
17
+
18
+ const ENGINE_PROPERTY = configSchema.properties.engine;
19
+ const ENGINES = Object.freeze([...ENGINE_PROPERTY.enum]);
20
+ const DEFAULT_ENGINE = ENGINE_PROPERTY.default;
21
+ const LEGACY_ENV = 'MOBILEMCP_LEGACY_ROBOT';
22
+
23
+ function isEngine(value) {
24
+ return typeof value === 'string' && ENGINES.includes(value);
25
+ }
26
+
27
+ // Precedence: an exported MOBILEMCP_LEGACY_ROBOT (ANY defined value) wins,
28
+ // because buildEngineEnv never overrides a user-set value — the engine that
29
+ // actually runs is the env's, so reporting the config's would be a lie. Then a
30
+ // valid config.engine, then the default. An invalid config value (hand-edited;
31
+ // `config set` rejects it) is ignored rather than fatal.
32
+ function resolveEngine({ config, env = process.env } = {}) {
33
+ if (env && env[LEGACY_ENV] !== undefined) {
34
+ return { engine: env[LEGACY_ENV] === '1' ? 'legacy' : 'mobilecli', source: 'env' };
35
+ }
36
+ if (config && isEngine(config.engine)) return { engine: config.engine, source: 'config' };
37
+ return { engine: DEFAULT_ENGINE, source: 'default' };
38
+ }
39
+
40
+ // resolveEngine against a workspace's config.json. A missing or unreadable
41
+ // config resolves like an empty one: picking a device robot must never be the
42
+ // reason a device verb fails.
43
+ function readEngine(projectRoot, { env = process.env, load = manager.load } = {}) {
44
+ let config = null;
45
+ try {
46
+ config = load(projectRoot);
47
+ } catch (_) {
48
+ config = null;
49
+ }
50
+ return resolveEngine({ config, env });
51
+ }
52
+
53
+ // The engine a session handle records. Daemons spawned before #251 wrote no
54
+ // engine; they ran the default robot unless the user exported
55
+ // MOBILEMCP_LEGACY_ROBOT, which the handle cannot tell us — so they count as
56
+ // mobilecli, and the rare exported-variable case costs one restart.
57
+ function handleEngine(handle) {
58
+ return handle && isEngine(handle.engine) ? handle.engine : DEFAULT_ENGINE;
59
+ }
60
+
61
+ const SOURCES = Object.freeze(['env', 'config', 'default']);
62
+
63
+ // The engine a spawned daemon runs, from the env its spawner set
64
+ // (MAUTO_SESSION_ENGINE / _SOURCE, see session-spawn.js). Without it — the
65
+ // daemon started by hand, or by a test — the daemon resolves from its own env,
66
+ // which is what the engine process will inherit.
67
+ function sessionEngineFromEnv(env = process.env) {
68
+ if (isEngine(env.MAUTO_SESSION_ENGINE)) {
69
+ const source = SOURCES.includes(env.MAUTO_SESSION_ENGINE_SOURCE) ? env.MAUTO_SESSION_ENGINE_SOURCE : null;
70
+ return { engine: env.MAUTO_SESSION_ENGINE, source };
71
+ }
72
+ return resolveEngine({ config: null, env });
73
+ }
74
+
75
+ module.exports = {
76
+ ENGINES,
77
+ DEFAULT_ENGINE,
78
+ isEngine,
79
+ resolveEngine,
80
+ readEngine,
81
+ handleEngine,
82
+ sessionEngineFromEnv,
83
+ };
@@ -60,11 +60,22 @@ function resolveServerEntry() {
60
60
  // accepts the exact string "1", so MOBILEMCP_ALLOW_UNSAFE_URLS=0 restores the
61
61
  // guard. The env is read when the engine spawns, so a running session daemon
62
62
  // must be ended (`mauto session end`) before a change takes effect.
63
- function buildEngineEnv({ device = null, baseEnv = process.env } = {}) {
63
+ //
64
+ // MOBILEMCP_LEGACY_ROBOT is set to "1" when `engine` is 'legacy' (#251), the
65
+ // workspace `engine` key resolved by src/device/engine.js. mobile-mcp picks its
66
+ // robot once per process from that exact string. Same rule as above: a
67
+ // user-set value always wins, in either direction, and engine.js's
68
+ // resolveEngine reports the env as the source so the recorded engine matches
69
+ // the one that runs. Unlike the URL guard, a running daemon on the other
70
+ // engine needs no manual `session end`: resolve-connection.js restarts it.
71
+ function buildEngineEnv({ device = null, baseEnv = process.env, engine = null } = {}) {
64
72
  const env = {
65
73
  ...baseEnv,
66
74
  MOBILEMCP_ALLOW_UNSAFE_URLS: baseEnv.MOBILEMCP_ALLOW_UNSAFE_URLS ?? '1',
67
75
  };
76
+ if (engine === 'legacy' && baseEnv.MOBILEMCP_LEGACY_ROBOT === undefined) {
77
+ env.MOBILEMCP_LEGACY_ROBOT = '1';
78
+ }
68
79
  // mobile-mcp reads the target device from the environment / its own
69
80
  // selection; we pass it through when provided so callers can pin a device.
70
81
  if (device) env.MOBILE_MCP_DEVICE = device;
@@ -97,6 +108,7 @@ function pidTracking(Transport) {
97
108
  // a fixture MCP server.
98
109
  async function createCall({
99
110
  device,
111
+ engine = null,
100
112
  connectTimeoutMs = CONNECT_TIMEOUT_MS,
101
113
  onEngineExit = null,
102
114
  sdk = { Client, StdioClientTransport },
@@ -109,7 +121,7 @@ async function createCall({
109
121
  const transport = new Transport({
110
122
  command,
111
123
  args,
112
- env: buildEngineEnv({ device }),
124
+ env: buildEngineEnv({ device, engine }),
113
125
  });
114
126
 
115
127
  const client = new sdk.Client({ name: 'mauto', version: '0.1.0' }, { capabilities: {} });
@@ -11,6 +11,10 @@
11
11
  // shared daemon down — other verbs depend on it).
12
12
  // (b) device-pin MISMATCH (daemon bound to A, verb asks for B)
13
13
  // -> one-shot connection for this call (do not silently reuse A).
14
+ // (b') device pin fits but the daemon runs a different ENGINE than the one
15
+ // this workspace resolves (#251) -> the daemon is stale: end it, then
16
+ // spawn on the requested engine (keeping its device pin) and connect
17
+ // daemon-backed. If it cannot be ended, one-shot instead.
14
18
  // (c) autostart && no reachable daemon
15
19
  // -> spawn a daemon, then connect daemon-backed (no-op close).
16
20
  // (d) spawn failed, or autostart:false
@@ -26,6 +30,8 @@ const { readHandle } = require('./session-handle');
26
30
  const sessionClient = require('./session-client');
27
31
  const { daemonLogHint } = require('./session-log');
28
32
  const sessionSpawn = require('./session-spawn');
33
+ const { readEngine, DEFAULT_ENGINE, handleEngine } = require('./engine');
34
+ const { endSession, ENDED_OUTCOMES } = require('./session-end');
29
35
 
30
36
  function defaultCreateCall(opts) {
31
37
  return require('./mobile-mcp-client').createCall(opts);
@@ -52,18 +58,49 @@ function deviceMatches(requested, handleDevice) {
52
58
  return requested === handleDevice;
53
59
  }
54
60
 
61
+ // Does a daemon running `runningEngine` satisfy a request for `requested`?
62
+ // The production caller passes engine.js's handleEngine() — the ONE decoder of
63
+ // a handle's engine (a missing or invalid value is the default robot), so
64
+ // `session status` and the restart decision can never disagree about the same
65
+ // handle. A falsy `runningEngine` here (a direct caller's pre-#251 handle)
66
+ // still counts as the default robot. A caller that resolved no engine does not
67
+ // compare at all.
68
+ function engineMatches(requested, runningEngine) {
69
+ if (!requested) return true;
70
+ return requested === (runningEngine || DEFAULT_ENGINE);
71
+ }
72
+
55
73
  // PURE decision: given the observed facts, which strategy should we run?
56
- // 'daemon' — a live daemon fits; connect daemon-backed (no-op close)
57
- // 'oneshot' — connect once for this call (real close)
58
- // 'spawn-then-daemon'— no daemon fits but autostart is on; spawn then connect
74
+ // 'daemon' — a live daemon fits; connect daemon-backed (no-op close)
75
+ // 'oneshot' — connect once for this call (real close)
76
+ // 'spawn-then-daemon' — no daemon fits but autostart is on; spawn then connect
77
+ // 'restart-then-daemon' — a live daemon on the requested device runs a stale
78
+ // engine (#251); end it, spawn on the requested
79
+ // engine, then connect
80
+ //
81
+ // Device before engine, deliberately. A device-pin mismatch stays 'oneshot'
82
+ // even when the engines differ too: a restart would respawn the session pinned
83
+ // to the REQUESTED device, which is exactly the silent repin (b) refuses. The
84
+ // one-shot already runs on the requested engine, so this call is correct; the
85
+ // stale daemon is restarted by the next verb whose device fits it. Only when
86
+ // the device fits is a different engine reason enough to replace the daemon —
87
+ // reusing it would answer with the robot the user configured away from.
59
88
  //
60
89
  // Zero collaborators, no I/O — value-in/value-out so the branching can be tested
61
90
  // without faking a client/spawn/createCall or writing a handle to disk. The
62
91
  // effectful resolver (below) gathers the facts, calls this, and runs exactly one
63
- // of the three thin effect paths.
64
- function chooseConnectionStrategy({ alive, handleDevice, requestedDevice, autostart }) {
65
- if (alive && deviceMatches(requestedDevice, handleDevice)) return 'daemon';
66
- if (alive) return 'oneshot'; // live daemon, but its device pin mismatches
92
+ // of the thin effect paths.
93
+ function chooseConnectionStrategy({
94
+ alive,
95
+ handleDevice,
96
+ requestedDevice,
97
+ autostart,
98
+ runningEngine = null,
99
+ requestedEngine = null,
100
+ }) {
101
+ if (alive && !deviceMatches(requestedDevice, handleDevice)) return 'oneshot';
102
+ if (alive && engineMatches(requestedEngine, runningEngine)) return 'daemon';
103
+ if (alive) return autostart ? 'restart-then-daemon' : 'oneshot';
67
104
  if (autostart) return 'spawn-then-daemon';
68
105
  return 'oneshot';
69
106
  }
@@ -77,12 +114,40 @@ async function resolveDeviceConnection({
77
114
  spawn = sessionSpawn,
78
115
  createCall = defaultCreateCall,
79
116
  idleMs = undefined,
117
+ // (projectRoot) => { engine, source } — the workspace's engine (#251).
118
+ resolveEngine = readEngine,
119
+ // Ends a stale-engine daemon through the same honest path `mauto session end`
120
+ // uses — session-end.js's endSession, verbatim: its signature is already
121
+ // (projectRoot, { client }), so the seam defaults to it directly, no wrapper.
122
+ // The restart inherits its refusal to lie about pids that will not die.
123
+ end = endSession,
80
124
  } = {}) {
125
+ // Resolved once per verb, and used by every path below: the one-shot, the
126
+ // spawned daemon, and the staleness check against a live one.
127
+ const { engine, source: engineSource } = resolveEngine(projectRoot);
128
+
81
129
  const oneShot = async () => {
82
- const { call, close } = await createCall({ device });
130
+ const { call, close } = await createCall({ device, engine });
83
131
  return { bridge: new DeviceBridge({ call, device }), close, source: 'oneshot' };
84
132
  };
85
133
 
134
+ // (d) explicit one-shot, or spawn failed / unreachable. When the SPAWN is
135
+ // what failed, the daemon's log is the only record of why, and transparent
136
+ // autostart is the common path — most users never type `mauto session start`,
137
+ // so without this the log stays invisible to almost everyone. The signal
138
+ // rides err.hint because deviceFail() in cli.js already surfaces it on every
139
+ // device verb, so acquireConnection's deliberately narrow contract is
140
+ // untouched (#163).
141
+ const oneShotWithLogHint = async (afterFailedSpawn) => {
142
+ try {
143
+ return await oneShot();
144
+ } catch (err) {
145
+ // Never clobber a more specific hint the transport already attached.
146
+ if (afterFailedSpawn && !err.hint) err.hint = daemonLogHint(projectRoot);
147
+ throw err;
148
+ }
149
+ };
150
+
86
151
  const daemonBacked = async () => {
87
152
  const conn = await client.tryConnect(projectRoot);
88
153
  if (!conn) return null;
@@ -105,15 +170,30 @@ async function resolveDeviceConnection({
105
170
  };
106
171
  };
107
172
 
173
+ // Spawn a daemon on the resolved engine, then connect to it. Resolves the
174
+ // connection, null when the daemon came up but was unreachable, or false when
175
+ // the spawn itself failed.
176
+ const spawnThenConnect = async (spawnDevice) => {
177
+ const started = await spawn.spawnDaemon({ projectRoot, device: spawnDevice, idleMs, engine, engineSource });
178
+ if (!started) return false;
179
+ return daemonBacked();
180
+ };
181
+
108
182
  const alive = await client.isAlive(projectRoot);
109
183
 
110
184
  if (alive) {
111
- const handleDevice = readHandleDevice(projectRoot);
185
+ const handle = readHandle(projectRoot);
186
+ const handleDevice = (handle && handle.device) || null;
112
187
  const strategy = chooseConnectionStrategy({
113
188
  alive: true,
114
189
  handleDevice,
115
190
  requestedDevice: device,
116
191
  autostart,
192
+ // engine.js's canonical projection — the same decoder `session status`
193
+ // reads the handle through — never the raw field, which a hand-edited or
194
+ // half-written handle can corrupt into a "stale" verdict status denies.
195
+ runningEngine: handleEngine(handle),
196
+ requestedEngine: engine,
117
197
  });
118
198
  if (strategy === 'daemon') {
119
199
  // (a) reuse the live daemon.
@@ -121,8 +201,18 @@ async function resolveDeviceConnection({
121
201
  if (conn) return conn;
122
202
  // Race: daemon vanished between isAlive and connect — fall through and
123
203
  // re-decide as if no daemon were alive.
204
+ } else if (strategy === 'restart-then-daemon') {
205
+ // (b') stale engine. The respawn keeps the daemon's device pin when the
206
+ // verb named none: the user pinned it (`session start --device`), and an
207
+ // engine switch is no reason to forget that.
208
+ const { outcome } = await end(projectRoot, { client });
209
+ if (!ENDED_OUTCOMES.has(outcome)) return oneShot();
210
+ const conn = await spawnThenConnect(device || handleDevice);
211
+ if (conn) return conn;
212
+ return oneShotWithLogHint(conn === false);
124
213
  } else {
125
- // (b) device-pin mismatch: never silently reuse the wrong device.
214
+ // (b) device-pin mismatch: never silently reuse the wrong device. Also a
215
+ // stale engine with autostart off: never reuse the wrong robot either.
126
216
  return oneShot();
127
217
  }
128
218
  }
@@ -137,36 +227,20 @@ async function resolveDeviceConnection({
137
227
  let spawnFailed = false;
138
228
  if (strategy === 'spawn-then-daemon') {
139
229
  // (c) spawn a daemon, then connect daemon-backed.
140
- const started = await spawn.spawnDaemon({ projectRoot, device, idleMs });
141
- if (started) {
142
- const conn = await daemonBacked();
143
- if (conn) return conn;
144
- // Spawn worked; the daemon just wasn't reachable. Its log has nothing to
145
- // say about a subsequent one-shot failure, so no hint — fall through.
146
- } else {
147
- spawnFailed = true;
148
- }
230
+ const conn = await spawnThenConnect(device);
231
+ if (conn) return conn;
232
+ // null: spawn worked; the daemon just wasn't reachable. Its log has nothing
233
+ // to say about a subsequent one-shot failure, so no hint — fall through.
234
+ spawnFailed = conn === false;
149
235
  }
150
236
 
151
- // (d) explicit one-shot, or spawn failed / unreachable. When the SPAWN is
152
- // what failed, the daemon's log is the only record of why, and transparent
153
- // autostart is the common path — most users never type `mauto session start`,
154
- // so without this the log stays invisible to almost everyone. The signal
155
- // rides err.hint because deviceFail() in cli.js already surfaces it on every
156
- // device verb, so acquireConnection's deliberately narrow contract is
157
- // untouched (#163).
158
- try {
159
- return await oneShot();
160
- } catch (err) {
161
- // Never clobber a more specific hint the transport already attached.
162
- if (spawnFailed && !err.hint) err.hint = daemonLogHint(projectRoot);
163
- throw err;
164
- }
237
+ return oneShotWithLogHint(spawnFailed);
165
238
  }
166
239
 
167
240
  module.exports = {
168
241
  resolveDeviceConnection,
169
242
  chooseConnectionStrategy,
170
243
  deviceMatches,
244
+ engineMatches,
171
245
  readHandleDevice,
172
246
  };
@@ -28,6 +28,7 @@ const { makeDeviceCall } = require('./device-call');
28
28
  const { safeObserve: guardObserve } = require('../observe/recorder');
29
29
  const { FLUSH_INTERVAL_MS } = require('../observe/flush');
30
30
  const { pidIdentity, readPidFile } = require('./process-identity');
31
+ const { DEFAULT_ENGINE } = require('./engine');
31
32
 
32
33
  const DEFAULT_IDLE_MS = 5 * 60 * 1000;
33
34
 
@@ -99,6 +100,13 @@ function cleanStale(projectRoot, { execFile } = {}) {
99
100
  async function startDaemon({
100
101
  projectRoot,
101
102
  device = null,
103
+ // The device robot this daemon's engine runs (#251) and where that choice
104
+ // came from. Recorded in the handle beside `device`, for the same reason: a
105
+ // verb compares it with what it resolved and restarts a stale daemon.
106
+ // Defaulted to the default robot with an unknown source — the in-process
107
+ // tests that omit it run no real engine at all.
108
+ engine = DEFAULT_ENGINE,
109
+ engineSource = null,
102
110
  idleMs = DEFAULT_IDLE_MS,
103
111
  createCall = defaultCreateCall,
104
112
  onUndeliverable = null,
@@ -264,7 +272,7 @@ async function startDaemon({
264
272
  let call;
265
273
  let close;
266
274
  try {
267
- ({ call, close } = await createCall({ device, onEngineExit }));
275
+ ({ call, close } = await createCall({ device, engine, onEngineExit }));
268
276
  } catch (err) {
269
277
  // #156's core symptom: mobile-mcp never came up, and until now the only
270
278
  // trace was a 15s readiness timeout in the spawning verb.
@@ -725,6 +733,8 @@ async function startDaemon({
725
733
  // there instead of paying a socket round trip (src/device/session-handle.js).
726
734
  session_id: sessionId,
727
735
  device: device || null,
736
+ engine,
737
+ engine_source: engineSource,
728
738
  socket: socketPath,
729
739
  started_at: new Date().toISOString(),
730
740
  idle_ms: idleMs,
@@ -0,0 +1,93 @@
1
+ 'use strict';
2
+
3
+ // Ends a device session daemon, honestly (#156).
4
+ //
5
+ // Its own module, not a member of connection.js, because two layers need it:
6
+ // connection.js (the verb-facing facade `mauto session end` calls through) and
7
+ // resolve-connection.js (the connection-strategy layer, which ends a stale-
8
+ // engine daemon before respawning it, #251). resolve-connection must not
9
+ // require connection — connection requires IT — so the shared path lives here,
10
+ // where both reach it downward and the dependency direction stays one-way.
11
+
12
+ const sessionDaemon = require('./session-daemon');
13
+ const sessionClient = require('./session-client');
14
+ const paths = require('./session-paths');
15
+ const processIdentity = require('./process-identity');
16
+ const processReaper = require('./process-reaper');
17
+
18
+ // How long `session end` waits for an acknowledged daemon to exit before it
19
+ // treats it as stuck: stop() drains in-flight calls (bounded by the daemon call
20
+ // timeout) and then closes the engine (the SDK's ~4s ladder). Derived, not
21
+ // restated; pinned by tests/unit/device/timeout-invariant.test.js.
22
+ const END_BUDGET_MS = sessionDaemon.DAEMON_CALL_TIMEOUT_MS + 10000;
23
+
24
+ // Stop the daemon and report only what is true (#156). The daemon acks the
25
+ // shutdown frame BEFORE its teardown runs, so an ack is a promise, not a fact:
26
+ // 'stopped' is reported only once the pid is gone.
27
+ //
28
+ // Returns { outcome, pid } — ONE discriminated answer, so a caller dispatches
29
+ // on what happened instead of re-deriving it from a bag of booleans:
30
+ // 'stopped' - acked, and the pid exited (or there was no pid to watch)
31
+ // 'already_stopped' - nothing acked and nothing of ours was running
32
+ // 'forced' - ours, stuck in teardown, terminated by a group kill
33
+ // 'survived' - ours, stuck, and still alive after SIGTERM + SIGKILL
34
+ // 'foreign' - acked, but the live pid's command line does not name
35
+ // this workspace, so it was reported, never signalled
36
+ // 'unverified' - the pid could not be identified (`ps` failed), so it
37
+ // was never signalled
38
+ // The last three are failures: a daemon may still be alive.
39
+ async function endSession(
40
+ projectRoot,
41
+ {
42
+ client = sessionClient,
43
+ reaper = processReaper,
44
+ // Bound to THIS workspace (#156): a group kill must never reach another
45
+ // workspace's daemon through a copied or recycled pidfile.
46
+ identify = (pid) => processIdentity.pidIdentity(pid, { projectRoot }),
47
+ readPid = () => processIdentity.readPidFile(paths.pidFilePath(projectRoot)),
48
+ budgetMs = END_BUDGET_MS,
49
+ } = {}
50
+ ) {
51
+ // Read BEFORE asking: a daemon that exits cleanly removes its pidfile, and we
52
+ // need to know whom to watch.
53
+ const pid = readPid();
54
+ const acked = await client.requestShutdown(projectRoot);
55
+ const report = (outcome) => ({ outcome, pid: pid || null });
56
+ // The daemon is gone: it stopped because we asked, or was never running.
57
+ const gone = () => report(acked ? 'stopped' : 'already_stopped');
58
+
59
+ // No pidfile: nothing to watch, so the ack is all we have (as before). Our
60
+ // own pid: the in-process daemon of a test — never wait on it, never signal it.
61
+ if (!pid || pid === process.pid) return gone();
62
+
63
+ // A non-acking daemon whose pidfile names a live process is checked at once
64
+ // (budget 0): either it is gone, or it is stuck too badly to answer.
65
+ if (await reaper.waitForDeath(pid, { budgetMs: acked ? budgetMs : 0 })) return gone();
66
+
67
+ switch (identify(pid)) {
68
+ case 'dead':
69
+ case 'other': // the pid was recycled: our daemon is gone
70
+ return gone();
71
+ case 'foreign':
72
+ // A mauto daemon whose command line does not name this workspace:
73
+ // another workspace's, reached through a copied or recycled pidfile.
74
+ // Never signalled. Without an ack nothing answered on OUR socket, so none
75
+ // of ours was running. With an ack the daemon that answered is ours, but
76
+ // its command line cannot prove it (one started before the workspace
77
+ // marker), so it is reported rather than killed.
78
+ return report(acked ? 'foreign' : 'already_stopped');
79
+ case 'ours':
80
+ return report((await reaper.terminate(pid, { group: true })) === 'dead' ? 'forced' : 'survived');
81
+ default: // 'unknown': never signal a process we cannot identify
82
+ return report('unverified');
83
+ }
84
+ }
85
+
86
+ // Outcomes after which no daemon of ours is left holding the workspace.
87
+ // Anything else ('survived', 'foreign', 'unverified') may leave the stale
88
+ // daemon alive — spawning then would just find it answering pings. Lives beside
89
+ // the vocabulary it classifies so a new outcome can never drift from its
90
+ // classification (#251's restart path, resolve-connection.js, reads it).
91
+ const ENDED_OUTCOMES = new Set(['stopped', 'forced', 'already_stopped']);
92
+
93
+ module.exports = { endSession, END_BUDGET_MS, ENDED_OUTCOMES };
@@ -28,6 +28,11 @@ async function spawnDaemon({
28
28
  projectRoot,
29
29
  device = null,
30
30
  idleMs = undefined,
31
+ // The engine the caller resolved (src/device/engine.js) and where it came
32
+ // from (#251). The daemon passes `engine` to createCall and records both in
33
+ // its handle, which is how a later verb spots a daemon on a stale engine.
34
+ engine = null,
35
+ engineSource = null,
31
36
  spawn = childProcess.spawn,
32
37
  readyTimeoutMs = DEFAULT_READY_TIMEOUT_MS,
33
38
  pollMs = DEFAULT_POLL_MS,
@@ -43,6 +48,12 @@ async function spawnDaemon({
43
48
  const env = { ...process.env, MAUTO_SESSION_PROJECT_ROOT: projectRoot };
44
49
  if (device) env.MAUTO_SESSION_DEVICE = device;
45
50
  if (idleMs !== undefined && idleMs !== null) env.MAUTO_SESSION_IDLE_MS = String(idleMs);
51
+ // Never inherited: a value leaking in from the parent's env would make the
52
+ // daemon record an engine nobody resolved for it.
53
+ delete env.MAUTO_SESSION_ENGINE;
54
+ delete env.MAUTO_SESSION_ENGINE_SOURCE;
55
+ if (engine) env.MAUTO_SESSION_ENGINE = engine;
56
+ if (engine && engineSource) env.MAUTO_SESSION_ENGINE_SOURCE = engineSource;
46
57
 
47
58
  // Must precede the spawn: the fd has to exist before the child can inherit it.
48
59
  // Never null — a workspace we cannot write to yields the `stdio: 'ignore'`
@@ -159,6 +159,18 @@ default — a report from last week is not evidence about this step. And a repor
159
159
  whose own timestamp is unreadable is counted in `unattributed` rather than
160
160
  included; if that count is non-zero, widen `--since` and look yourself.
161
161
 
162
+ ### When the element list looks wrong, check the engine
163
+
164
+ If the app is alive but `mauto elements` misses the label of a text field you
165
+ can see on screen, or lists content from a tab that is not showing, the device
166
+ engine is the likely cause, not the app. Run `mauto config get engine`: if it is
167
+ `mobilecli` or unset, record the step as failed with that observation and tell
168
+ the user that `mauto config set engine legacy` should fix it. On older device
169
+ OS versions the legacy engine still hides inactive-tab content but may not
170
+ recover text-field labels; if the engine is already `legacy`, a missing
171
+ text-field label is the device OS version, not the engine setting. Do not
172
+ switch the engine mid-run yourself.
173
+
162
174
  ### 4. Validate Assertions (27 types)
163
175
 
164
176
  For each assertion, pick the type recorded in the scenario and evaluate it. The 27 types split into two tiers by **who decides pass/fail**:
@@ -207,6 +207,19 @@ default — a report from last week is not evidence about this step. And a repor
207
207
  whose own timestamp is unreadable is counted in `unattributed` rather than
208
208
  included; if that count is non-zero, widen `--since` and look yourself.
209
209
 
210
+ ### When the element list looks wrong, check the engine
211
+
212
+ If the app is alive but `mauto elements` misses the label of a text field you
213
+ can see on screen, or lists content from a tab that is not showing (common in
214
+ Flutter and other cross-platform apps on Android), the device engine is the
215
+ likely cause, not the app. Run `mauto config get engine`: if it is `mobilecli`
216
+ or unset, record the step as failed with that observation and tell the user
217
+ that `mauto config set engine legacy` should fix it — it hides hidden-tab
218
+ content on every Android version tested, but recovers text-field labels only on recent Android
219
+ versions (verified on API 36; not on API 33). If the engine is already
220
+ `legacy`, a missing text-field label is the Android version, not the engine
221
+ setting. Do not switch the engine mid-run yourself.
222
+
210
223
  ### 5. Validate Assertions (27 types)
211
224
 
212
225
  For each assertion in the scenario (evaluated after the referenced step), pick the type recorded in the scenario and evaluate it. The 27 types split into two tiers by **who decides pass/fail**:
@@ -42,7 +42,17 @@ List the source directories the QA tooling must NEVER modify (it operates on tes
42
42
 
43
43
  In this mode environments are decoupled from build flavors — they are just labels for the test target. Ask the user whether the project has named environments (e.g. `production, staging, dev`). If yes, persist the list: `mauto config set environments <production,staging,dev>`. If no, leave it unset (or persist an empty list).
44
44
 
45
- ## 6. Confirm the config
45
+ ## 6. Device engine (check once a device is connected)
46
+
47
+ Leave `engine` at its default unless the element list is wrong. With a device connected and the app on a screen that has a text field or tabs, run `mauto elements`. If it misses the label of a text field you can see, or lists content from a tab that is not showing — common with apps that draw their own UI — switch engines:
48
+
49
+ ```
50
+ mauto config set engine legacy
51
+ ```
52
+
53
+ Follow the `hint` the command prints, then run `mauto elements` again. On older device OS versions the legacy engine still hides inactive-tab content but may not recover text-field labels; if a label stays missing, keep `legacy` for the tab fix and tell the user the label gap is the device OS version. Switching clears any pinned device, because the engines may name the same device differently; re-select it with `mauto devices` and `mauto devices use <id>`.
54
+
55
+ ## 7. Confirm the config
46
56
 
47
57
  Read the persisted values back with `mauto config get <key>` for each finding, and present a concise summary to the user. The workspace is now analyzed and configured: `mauto guide generate` and `mauto guide execute` will read these values to drive portable scenario authoring and execution. At execute time the four semantic actions — `press_back`, `dismiss_keyboard`, `grant_permission`, `deny_permission` — resolve per platform automatically, so nothing platform-specific needs to live in this config.
48
58
 
@@ -72,7 +72,17 @@ Infer each of the following from the codebase, confirm uncertain values with the
72
72
  - **Loading indicators** — grep for loading widgets/components (progress indicators, spinners, shimmer/skeleton placeholders) and any `*Loading*`/`*Spinner*`/`*Shimmer*`/`*Skeleton*` classes. Persist the found names, or a description like `"progress bars, spinners, shimmer effects"` if none found. Persist: `mauto config set loading_indicators "<list>"`.
73
73
  - **Protected directories** — list the source directories the QA tooling must NEVER modify (e.g. `app/src/`, `lib/`, `src/`, `shared/`, `composeApp/`, `iosApp/`). Confirm with the user. Persist a comma-separated value (stored as a list): `mauto config set protected_directories "<app/src/, lib/, core/>"`.
74
74
 
75
- ## 5. Confirm the config
75
+ ## 5. Choose the device engine
76
+
77
+ For a Flutter app (or another app that draws its own UI, such as Compose Multiplatform) tested on Android, set the legacy engine: the default `mobilecli` engine drops text-field labels and reports content from hidden tabs in `mauto elements`. The legacy engine hides hidden-tab content on every Android version tested, but recovers text-field labels only on recent Android versions (verified on Android 16 / API 36; not on API 33) — on older devices, labels may stay missing on both engines. Native Android and iOS apps can keep the default.
78
+
79
+ ```
80
+ mauto config set engine legacy
81
+ ```
82
+
83
+ Follow the `hint` the command prints. Switching clears any pinned device, because the engines name Android devices differently; re-select it with `mauto devices` and `mauto devices use <id>`. iOS simulators use `mobilecli` whatever this key says.
84
+
85
+ ## 6. Confirm the config
76
86
 
77
87
  Read the persisted values back with `mauto config get <key>` for each finding, and present a concise summary to the user. The workspace is now analyzed and configured: `mauto guide generate` and `mauto guide execute` will read these values to drive scenario authoring and execution.
78
88
 
@@ -21,6 +21,12 @@
21
21
  "enum": ["platform-aware", "platform-agnostic"],
22
22
  "description": "Selected at setup. Configs predating this field are treated as platform-aware."
23
23
  },
24
+ "engine": {
25
+ "type": "string",
26
+ "enum": ["mobilecli", "legacy"],
27
+ "default": "mobilecli",
28
+ "description": "Which mobile-mcp device robot drives the device. `mobilecli` (default) is mobile-mcp's mobilecli robot. `legacy` selects mobile-mcp's legacy robot (MOBILEMCP_LEGACY_ROBOT=1) — adb/uiautomator on Android, go-ios/WDA on real iOS devices (iOS simulators always use mobilecli). An exported MOBILEMCP_LEGACY_ROBOT overrides this key. Device ids differ between engines (AVD name vs adb serial), so re-run `mauto devices` after switching. A running session on the other engine is restarted by the next device verb. See #251."
29
+ },
24
30
  "project_name": { "$ref": "#/definitions/nullableString" },
25
31
  "platform": { "type": "string", "description": "Detected platform (platform-aware mode)." },
26
32
  "platform_details": { "type": "string" },