@swmansion/argent 0.34.1-next.22 → 0.34.1-next.24

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.
@@ -21981,21 +21981,21 @@ function visit(schema, fnOrHandlers) {
21981
21981
  const h = fnOrHandlers[node2._zod.def.type];
21982
21982
  return h ? h(node2, rewritten) : node2;
21983
21983
  };
21984
- const cache4 = /* @__PURE__ */ new Map();
21984
+ const cache5 = /* @__PURE__ */ new Map();
21985
21985
  function run2(s) {
21986
- const cached3 = cache4.get(s);
21986
+ const cached3 = cache5.get(s);
21987
21987
  if (cached3 === RESOLVING) {
21988
21988
  return new $ZodLazy({
21989
21989
  type: "lazy",
21990
- getter: () => cache4.get(s)
21990
+ getter: () => cache5.get(s)
21991
21991
  });
21992
21992
  }
21993
21993
  if (cached3 !== void 0)
21994
21994
  return cached3;
21995
- cache4.set(s, RESOLVING);
21995
+ cache5.set(s, RESOLVING);
21996
21996
  const inner = mapInner(s);
21997
21997
  const mapped = fn(inner, inner !== s);
21998
- cache4.set(s, mapped);
21998
+ cache5.set(s, mapped);
21999
21999
  return mapped;
22000
22000
  }
22001
22001
  function mapInner(s) {
@@ -55178,7 +55178,7 @@ var require_application = __commonJS({
55178
55178
  return this;
55179
55179
  };
55180
55180
  app.render = function render2(name, options, callback) {
55181
- var cache4 = this.cache;
55181
+ var cache5 = this.cache;
55182
55182
  var done = callback;
55183
55183
  var engines = this.engines;
55184
55184
  var opts = options || {};
@@ -55192,7 +55192,7 @@ var require_application = __commonJS({
55192
55192
  renderOptions.cache = this.enabled("view cache");
55193
55193
  }
55194
55194
  if (renderOptions.cache) {
55195
- view = cache4[name];
55195
+ view = cache5[name];
55196
55196
  }
55197
55197
  if (!view) {
55198
55198
  var View2 = this.get("view");
@@ -55208,7 +55208,7 @@ var require_application = __commonJS({
55208
55208
  return done(err);
55209
55209
  }
55210
55210
  if (renderOptions.cache) {
55211
- cache4[name] = view;
55211
+ cache5[name] = view;
55212
55212
  }
55213
55213
  }
55214
55214
  tryRender(view, renderOptions, done);
@@ -77919,7 +77919,7 @@ var require_range2 = __commonJS({
77919
77919
  range = range.replace(BUILDSTRIPRE, "");
77920
77920
  const memoOpts = (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | (this.options.loose && FLAG_LOOSE);
77921
77921
  const memoKey = memoOpts + ":" + range;
77922
- const cached3 = cache4.get(memoKey);
77922
+ const cached3 = cache5.get(memoKey);
77923
77923
  if (cached3) {
77924
77924
  return cached3;
77925
77925
  }
@@ -77953,7 +77953,7 @@ var require_range2 = __commonJS({
77953
77953
  rangeMap.delete("");
77954
77954
  }
77955
77955
  const result = [...rangeMap.values()];
77956
- cache4.set(memoKey, result);
77956
+ cache5.set(memoKey, result);
77957
77957
  return result;
77958
77958
  }
77959
77959
  intersects(range, options) {
@@ -77992,7 +77992,7 @@ var require_range2 = __commonJS({
77992
77992
  };
77993
77993
  module2.exports = Range;
77994
77994
  var LRU = require_lrucache();
77995
- var cache4 = new LRU();
77995
+ var cache5 = new LRU();
77996
77996
  var parseOptions = require_parse_options();
77997
77997
  var Comparator = require_comparator();
77998
77998
  var debug = require_debug();
@@ -99277,10 +99277,10 @@ var BatchLogRecordProcessorBase = class {
99277
99277
  let toFlush = this._finishedLogRecords;
99278
99278
  this._finishedLogRecords = [];
99279
99279
  this._clearTimer();
99280
- const inFlight3 = this._currentExport;
99281
- if (inFlight3 !== null) {
99280
+ const inFlight4 = this._currentExport;
99281
+ if (inFlight4 !== null) {
99282
99282
  await this._exporter.forceFlush();
99283
- await inFlight3.exportCompleted;
99283
+ await inFlight4.exportCompleted;
99284
99284
  this._currentExport = null;
99285
99285
  }
99286
99286
  while (toFlush.length > 0) {
@@ -101396,7 +101396,7 @@ function isCi(env = process.env) {
101396
101396
  var SESSION_ID = (0, import_node_crypto3.randomUUID)();
101397
101397
  function readCliVersion() {
101398
101398
  if (true) {
101399
- return "0.34.1-next.22";
101399
+ return "0.34.1-next.23";
101400
101400
  }
101401
101401
  return "0.0.0";
101402
101402
  }
@@ -105112,6 +105112,56 @@ function pickIosHost(device) {
105112
105112
  return device.platform === "ios-remote" ? remoteIosHost : localIosHost;
105113
105113
  }
105114
105114
 
105115
+ // ../tool-server/src/tools/describe/contract.ts
105116
+ init_zod();
105117
+ var describeFrameSchema = external_exports.object({
105118
+ x: external_exports.number().finite().min(0).max(1),
105119
+ y: external_exports.number().finite().min(0).max(1),
105120
+ width: external_exports.number().finite().min(0).max(1),
105121
+ height: external_exports.number().finite().min(0).max(1)
105122
+ });
105123
+ var describeNodeSchema = external_exports.lazy(
105124
+ () => external_exports.object({
105125
+ role: external_exports.string().min(1),
105126
+ frame: describeFrameSchema,
105127
+ children: external_exports.array(describeNodeSchema),
105128
+ label: external_exports.string().optional(),
105129
+ hint: external_exports.string().optional(),
105130
+ identifier: external_exports.string().optional(),
105131
+ value: external_exports.string().optional(),
105132
+ subtreeText: external_exports.string().optional(),
105133
+ clickable: external_exports.boolean().optional(),
105134
+ longClickable: external_exports.boolean().optional(),
105135
+ scrollable: external_exports.boolean().optional(),
105136
+ checkable: external_exports.boolean().optional(),
105137
+ checked: external_exports.boolean().optional(),
105138
+ disabled: external_exports.boolean().optional(),
105139
+ password: external_exports.boolean().optional(),
105140
+ scrollHidden: external_exports.number().int().nonnegative().optional(),
105141
+ focused: external_exports.boolean().optional(),
105142
+ selected: external_exports.boolean().optional(),
105143
+ layer: external_exports.number().int().nonnegative().optional()
105144
+ }).passthrough()
105145
+ );
105146
+ var UI_ORIENTATIONS = [
105147
+ "portrait",
105148
+ "portraitUpsideDown",
105149
+ "landscapeLeft",
105150
+ "landscapeRight"
105151
+ ];
105152
+ function asUiOrientation(v) {
105153
+ return typeof v === "string" && UI_ORIENTATIONS.includes(v) ? v : void 0;
105154
+ }
105155
+ function parseDescribeResult(input2) {
105156
+ return describeNodeSchema.parse(input2);
105157
+ }
105158
+ function getDescribeTapPoint(frame2) {
105159
+ return {
105160
+ x: frame2.x + frame2.width / 2,
105161
+ y: frame2.y + frame2.height / 2
105162
+ };
105163
+ }
105164
+
105115
105165
  // ../tool-server/src/blueprints/ax-service.ts
105116
105166
  var AX_SERVICE_NAMESPACE = "AXService";
105117
105167
  function axServiceRef(device, { transport = "unix" } = {}) {
@@ -105526,6 +105576,7 @@ var axServiceBlueprint = {
105526
105576
  );
105527
105577
  });
105528
105578
  }
105579
+ let lacksOrientationCommand = false;
105529
105580
  const api = {
105530
105581
  degraded: !entitlementBypassActive,
105531
105582
  async describe() {
@@ -105541,6 +105592,7 @@ var axServiceBlueprint = {
105541
105592
  return {
105542
105593
  alertVisible: result.alertVisible ?? false,
105543
105594
  screenFrame: result.screenFrame,
105595
+ interfaceOrientation: asUiOrientation(result.interfaceOrientation),
105544
105596
  elements: result.elements ?? []
105545
105597
  };
105546
105598
  },
@@ -105560,6 +105612,7 @@ var axServiceBlueprint = {
105560
105612
  return {
105561
105613
  alertVisible: result.alertVisible ?? false,
105562
105614
  screenFrame: result.screenFrame,
105615
+ interfaceOrientation: asUiOrientation(result.interfaceOrientation),
105563
105616
  nodes: result.nodes ?? [],
105564
105617
  truncated: result.truncated === true,
105565
105618
  foregroundApp: result.foregroundApp,
@@ -105569,6 +105622,30 @@ var axServiceBlueprint = {
105569
105622
  async foregroundApp() {
105570
105623
  return await query("foreground_app");
105571
105624
  },
105625
+ async orientation() {
105626
+ if (!lacksOrientationCommand) {
105627
+ try {
105628
+ const result = await query("orientation", LIVE_PANEL_TIMEOUT_MS);
105629
+ if (result.error) {
105630
+ throw new FailureError(`ax-service orientation error: ${result.error}`, {
105631
+ error_code: FAILURE_CODES.AX_QUERY_FAILED,
105632
+ failure_stage: "ax_service_orientation",
105633
+ failure_area: "tool_server",
105634
+ error_kind: "unknown"
105635
+ });
105636
+ }
105637
+ return {
105638
+ interfaceOrientation: asUiOrientation(result.interfaceOrientation),
105639
+ screenFrame: result.screenFrame
105640
+ };
105641
+ } catch (err) {
105642
+ if (!(err instanceof Error) || err.message !== "unknown_command") throw err;
105643
+ lacksOrientationCommand = true;
105644
+ }
105645
+ }
105646
+ const { interfaceOrientation, screenFrame } = await api.describe();
105647
+ return { interfaceOrientation, screenFrame };
105648
+ },
105572
105649
  async livePanel() {
105573
105650
  const result = await query("live_panel", LIVE_PANEL_TIMEOUT_MS);
105574
105651
  if (result.error) {
@@ -114964,7 +115041,7 @@ var Publisher = class {
114964
115041
  }
114965
115042
  const priority = fromWire(msg.subscriberPriority);
114966
115043
  const track2 = broadcast.subscribe(msg.trackName, { priority });
114967
- let cache4;
115044
+ let cache5;
114968
115045
  try {
114969
115046
  const timescale = (await track2.info()).timescale;
114970
115047
  const edge = liveEdge(track2);
@@ -114978,7 +115055,7 @@ var Publisher = class {
114978
115055
  if (startGroup !== void 0)
114979
115056
  track2.startAt(startGroup);
114980
115057
  const fill = msg.fill && isDraft20(version3) ? fillRange(msg.fill, msg.filter, edge.largest) : void 0;
114981
- cache4 = fill && fill.kind !== "empty" ? track2.fork({ priority }) : void 0;
115058
+ cache5 = fill && fill.kind !== "empty" ? track2.fork({ priority }) : void 0;
114982
115059
  await stream.writer.u53(SubscribeOk.id);
114983
115060
  const ok = new SubscribeOk({
114984
115061
  requestId: version3 === Version.DRAFT_14 || version3 === Version.DRAFT_15 || version3 === Version.DRAFT_16 ? msg.requestId : void 0,
@@ -115031,11 +115108,11 @@ var Publisher = class {
115031
115108
  });
115032
115109
  }
115033
115110
  })();
115034
- const filling = fill && cache4 ? this.#runFill({
115111
+ const filling = fill && cache5 ? this.#runFill({
115035
115112
  requestId: msg.requestId,
115036
115113
  priority,
115037
115114
  fill,
115038
- cache: cache4,
115115
+ cache: cache5,
115039
115116
  timescale,
115040
115117
  stamped: msg.propertiesWanted,
115041
115118
  unsubscribed
@@ -115068,7 +115145,7 @@ var Publisher = class {
115068
115145
  stream.abort(e);
115069
115146
  } finally {
115070
115147
  track2.close();
115071
- cache4?.close();
115148
+ cache5?.close();
115072
115149
  }
115073
115150
  }
115074
115151
  /**
@@ -115139,7 +115216,7 @@ var Publisher = class {
115139
115216
  * fill-failure signal. Nothing here touches the subscription either way.
115140
115217
  */
115141
115218
  async #runFill(options) {
115142
- const { requestId, fill, cache: cache4, timescale, stamped, unsubscribed } = options;
115219
+ const { requestId, fill, cache: cache5, timescale, stamped, unsubscribed } = options;
115143
115220
  const version3 = this.#session.version;
115144
115221
  let stream;
115145
115222
  try {
@@ -115155,7 +115232,7 @@ var Publisher = class {
115155
115232
  if (fill.kind !== "group") {
115156
115233
  throw new Error("a fill spanning several groups is not supported");
115157
115234
  }
115158
- const group = takeGroup(cache4, Number(fill.sequence));
115235
+ const group = takeGroup(cache5, Number(fill.sequence));
115159
115236
  try {
115160
115237
  await this.#writeFillGroup(stream, group, fill, timescale, stamped, unsubscribed);
115161
115238
  } finally {
@@ -115168,7 +115245,7 @@ var Publisher = class {
115168
115245
  console.debug(`fill failed, resetting its stream: fill=${requestId} error=${reason(e)}`);
115169
115246
  stream?.reset(e);
115170
115247
  } finally {
115171
- cache4.close();
115248
+ cache5.close();
115172
115249
  }
115173
115250
  }
115174
115251
  /**
@@ -115516,9 +115593,9 @@ var Publisher = class {
115516
115593
  });
115517
115594
  }
115518
115595
  };
115519
- function takeGroup(cache4, sequence) {
115596
+ function takeGroup(cache5, sequence) {
115520
115597
  for (; ; ) {
115521
- const group = cache4.tryRecvGroup();
115598
+ const group = cache5.tryRecvGroup();
115522
115599
  if (!group)
115523
115600
  throw new Error(`group not found: ${sequence}`);
115524
115601
  if (group.sequence === sequence)
@@ -124238,6 +124315,185 @@ async function foldablePostureHint(udid, expected, actual) {
124238
124315
  return `${base} ${expected.width}x${expected.height} is ${from2}; ${actual.width}x${actual.height} is ${to}. Fold the device to the baseline's posture with the fold tool, or take a baseline for this posture.`;
124239
124316
  }
124240
124317
 
124318
+ // ../tool-server/src/utils/simulator-client.ts
124319
+ init_device_info();
124320
+
124321
+ // ../tool-server/src/utils/ios-ui-orientation.ts
124322
+ var import_node_async_hooks2 = require("node:async_hooks");
124323
+ init_device_info();
124324
+ var sourceFor;
124325
+ function setUiOrientationSourceProvider(provider) {
124326
+ sourceFor = provider;
124327
+ }
124328
+ var MAX_AGE_MS = 1e3;
124329
+ var READ_TIMEOUT_MS = 2500;
124330
+ var cache4 = /* @__PURE__ */ new Map();
124331
+ var inFlight2 = /* @__PURE__ */ new Map();
124332
+ var generations = /* @__PURE__ */ new Map();
124333
+ var TURN_SETTLE_MS = 1500;
124334
+ var noReuseUntil = /* @__PURE__ */ new Map();
124335
+ function noteUiOrientation(udid, orientation, nativeScreen) {
124336
+ if (orientation === void 0 || turning(udid)) return;
124337
+ cache4.set(udid, {
124338
+ read: { orientation, ...nativeScreen ? { nativeScreen } : {} },
124339
+ at: Date.now()
124340
+ });
124341
+ }
124342
+ function forgetUiOrientation(udid) {
124343
+ cache4.delete(udid);
124344
+ generations.set(udid, (generations.get(udid) ?? 0) + 1);
124345
+ noReuseUntil.set(udid, Date.now() + TURN_SETTLE_MS);
124346
+ }
124347
+ function turning(udid) {
124348
+ const until = noReuseUntil.get(udid);
124349
+ if (until === void 0) return false;
124350
+ if (Date.now() < until) return true;
124351
+ noReuseUntil.delete(udid);
124352
+ return false;
124353
+ }
124354
+ function readUiOrientation(udid) {
124355
+ const hit = cache4.get(udid);
124356
+ if (hit && Date.now() - hit.at <= MAX_AGE_MS && !turning(udid)) return Promise.resolve(hit.read);
124357
+ const generation = generations.get(udid) ?? 0;
124358
+ const pending = inFlight2.get(udid);
124359
+ if (pending && pending.generation === generation) return pending.read;
124360
+ const read = readFresh(udid).then((result) => {
124361
+ if ((generations.get(udid) ?? 0) === generation && !turning(udid)) {
124362
+ cache4.set(udid, { read: result, at: Date.now() });
124363
+ }
124364
+ return result;
124365
+ });
124366
+ const entry = { generation, read };
124367
+ inFlight2.set(udid, entry);
124368
+ void read.finally(() => {
124369
+ if (inFlight2.get(udid) === entry) inFlight2.delete(udid);
124370
+ });
124371
+ return read;
124372
+ }
124373
+ async function readFresh(udid) {
124374
+ if (!sourceFor) return {};
124375
+ if (resolveDevice(udid).platform === "ios" && await isTvOsSimulator(udid).catch(() => false)) {
124376
+ return {};
124377
+ }
124378
+ let timer;
124379
+ try {
124380
+ const answer = await Promise.race([
124381
+ sourceFor(udid).then((source) => source.orientation()),
124382
+ new Promise((_, reject) => {
124383
+ timer = setTimeout(
124384
+ () => reject(new Error(`no answer within ${READ_TIMEOUT_MS}ms`)),
124385
+ READ_TIMEOUT_MS
124386
+ );
124387
+ timer.unref?.();
124388
+ })
124389
+ ]);
124390
+ const orientation = answer.interfaceOrientation;
124391
+ if (orientation === void 0) {
124392
+ return { unknownReason: "the accessibility service did not name it" };
124393
+ }
124394
+ return { orientation, ...answer.screenFrame ? { nativeScreen: answer.screenFrame } : {} };
124395
+ } catch (err) {
124396
+ return {
124397
+ unknownReason: `the accessibility service could not be asked (${err instanceof Error ? err.message : String(err)})`
124398
+ };
124399
+ } finally {
124400
+ clearTimeout(timer);
124401
+ }
124402
+ }
124403
+ function unknownOrientationNote(read, what) {
124404
+ return `The interface orientation could not be read (${read.unknownReason ?? "unknown"}), so ${what} the screen's portrait-native space. If the UI is landscape or upside down, that is not the upright space screenshots and describe frames normally use.`;
124405
+ }
124406
+ function forgettingUiOrientation(impl) {
124407
+ return {
124408
+ ...impl,
124409
+ handler: async (services, params, device, options) => {
124410
+ try {
124411
+ return await impl.handler(services, params, device, options);
124412
+ } finally {
124413
+ forgetUiOrientation(device.id);
124414
+ }
124415
+ }
124416
+ };
124417
+ }
124418
+ var coordinateSpace = new import_node_async_hooks2.AsyncLocalStorage();
124419
+ function inCoordinateSpace(space, fn) {
124420
+ return coordinateSpace.run(space, fn);
124421
+ }
124422
+ function inNativeCoordinates() {
124423
+ return coordinateSpace.getStore() === "native";
124424
+ }
124425
+
124426
+ // ../tool-server/src/utils/ui-orientation.ts
124427
+ function uiPointToNative(p, orientation) {
124428
+ switch (orientation) {
124429
+ case "landscapeRight":
124430
+ return { x: 1 - p.y, y: p.x };
124431
+ case "landscapeLeft":
124432
+ return { x: p.y, y: 1 - p.x };
124433
+ case "portraitUpsideDown":
124434
+ return { x: 1 - p.x, y: 1 - p.y };
124435
+ default:
124436
+ return { x: p.x, y: p.y };
124437
+ }
124438
+ }
124439
+ function nativeFrameToUi(f, orientation) {
124440
+ switch (orientation) {
124441
+ case "landscapeRight":
124442
+ return { x: f.y, y: snap(1 - f.x - f.width), width: f.height, height: f.width };
124443
+ case "landscapeLeft":
124444
+ return { x: snap(1 - f.y - f.height), y: f.x, width: f.height, height: f.width };
124445
+ case "portraitUpsideDown":
124446
+ return {
124447
+ x: snap(1 - f.x - f.width),
124448
+ y: snap(1 - f.y - f.height),
124449
+ width: f.width,
124450
+ height: f.height
124451
+ };
124452
+ default:
124453
+ return f;
124454
+ }
124455
+ }
124456
+ function snap(v) {
124457
+ return Math.round(v * 1e9) / 1e9;
124458
+ }
124459
+ function nativePointToUi(p, orientation) {
124460
+ switch (orientation) {
124461
+ case "landscapeRight":
124462
+ return { x: p.y, y: 1 - p.x };
124463
+ case "landscapeLeft":
124464
+ return { x: 1 - p.y, y: p.x };
124465
+ case "portraitUpsideDown":
124466
+ return { x: 1 - p.x, y: 1 - p.y };
124467
+ default:
124468
+ return { x: p.x, y: p.y };
124469
+ }
124470
+ }
124471
+ function isTurned(orientation) {
124472
+ return orientation !== void 0 && orientation !== "portrait";
124473
+ }
124474
+ function uprightCaptureRotation(orientation) {
124475
+ switch (orientation) {
124476
+ case "landscapeRight":
124477
+ return "LandscapeLeft";
124478
+ case "landscapeLeft":
124479
+ return "LandscapeRight";
124480
+ case "portraitUpsideDown":
124481
+ return "PortraitUpsideDown";
124482
+ default:
124483
+ return void 0;
124484
+ }
124485
+ }
124486
+ function nativeTreeToUi(node2, orientation) {
124487
+ return {
124488
+ ...node2,
124489
+ frame: nativeFrameToUi(node2.frame, orientation),
124490
+ children: node2.children.map((child) => nativeTreeToUi(child, orientation))
124491
+ };
124492
+ }
124493
+ function uiScreenSize(size, orientation) {
124494
+ return orientation === "landscapeLeft" || orientation === "landscapeRight" ? { ...size, width: size.height, height: size.width } : size;
124495
+ }
124496
+
124241
124497
  // ../tool-server/src/utils/simulator-client.ts
124242
124498
  var fs22 = __toESM(require("node:fs/promises"));
124243
124499
  var path19 = __toESM(require("node:path"));
@@ -124342,12 +124598,17 @@ function getOrCreateConnection(api) {
124342
124598
  }
124343
124599
  async function sendCommand(api, cmd) {
124344
124600
  const cmdName = typeof cmd.cmd === "string" ? cmd.cmd : "unknown";
124601
+ if ((cmd.cmd === "rotate" || cmd.cmd === "button") && api.deviceId) {
124602
+ forgetUiOrientation(api.deviceId);
124603
+ }
124604
+ const { cmd: native, warning: turnWarning } = await withNativeTouchSpace(api, cmd);
124345
124605
  if (api.transport) {
124346
- await sendViaTransport(api.transport, cmd, cmdName);
124347
- return {};
124606
+ await sendViaTransport(api.transport, native, cmdName);
124607
+ return turnWarning !== void 0 ? { warning: turnWarning } : {};
124348
124608
  }
124349
124609
  const conn = getOrCreateConnection(api);
124350
- const { cmd: targeted, warning } = await withActiveScreen(api, cmd);
124610
+ const { cmd: targeted, warning: screenWarning } = await withActiveScreen(api, native);
124611
+ const warning = turnWarning !== void 0 && screenWarning !== void 0 ? `${screenWarning} ${turnWarning}` : screenWarning ?? turnWarning;
124351
124612
  const id = String(++cmdId);
124352
124613
  const payload = JSON.stringify({ id, ...targeted });
124353
124614
  await new Promise((resolve19, reject) => {
@@ -124391,6 +124652,38 @@ async function sendCommand(api, cmd) {
124391
124652
  });
124392
124653
  return warning !== void 0 ? { warning } : {};
124393
124654
  }
124655
+ var gestureTurns = /* @__PURE__ */ new WeakMap();
124656
+ async function withNativeTouchSpace(api, cmd) {
124657
+ if (cmd.cmd !== "touch" || !api.deviceId || inNativeCoordinates() || !isIosSimulator(resolveDevice(api.deviceId))) {
124658
+ return { cmd };
124659
+ }
124660
+ let orientation;
124661
+ let warning;
124662
+ if (cmd.type !== "Down" && gestureTurns.has(api)) {
124663
+ orientation = gestureTurns.get(api);
124664
+ } else {
124665
+ const read = await readUiOrientation(api.deviceId);
124666
+ orientation = read.orientation;
124667
+ if (read.unknownReason !== void 0) {
124668
+ warning = unknownOrientationNote(read, "this touch was sent in");
124669
+ }
124670
+ }
124671
+ if (cmd.type === "Up") gestureTurns.delete(api);
124672
+ else gestureTurns.set(api, orientation);
124673
+ if (!isTurned(orientation)) return { cmd, ...warning !== void 0 ? { warning } : {} };
124674
+ const turned = { ...cmd };
124675
+ const first = uiPointToNative({ x: cmd.x, y: cmd.y }, orientation);
124676
+ turned.x = first.x;
124677
+ turned.y = first.y;
124678
+ const sx = cmd.second_x;
124679
+ const sy = cmd.second_y;
124680
+ if (typeof sx === "number" && typeof sy === "number") {
124681
+ const second = uiPointToNative({ x: sx, y: sy }, orientation);
124682
+ turned.second_x = second.x;
124683
+ turned.second_y = second.y;
124684
+ }
124685
+ return { cmd: turned };
124686
+ }
124394
124687
  var gestureScreens = /* @__PURE__ */ new WeakMap();
124395
124688
  async function withActiveScreen(api, cmd) {
124396
124689
  if (!api.display?.foldable || cmd.screen !== void 0) return { cmd };
@@ -124438,6 +124731,7 @@ async function fetchDisplayState(api, signal) {
124438
124731
  }
124439
124732
  }
124440
124733
  async function postHinge(api, request3, signal) {
124734
+ if (api.deviceId) forgetUiOrientation(api.deviceId);
124441
124735
  if (api.transport) {
124442
124736
  throw new FailureError(
124443
124737
  "Fold failed: a remote simulator is driven on its main screen and has no hinge control.",
@@ -124975,7 +125269,7 @@ var nativeDevtoolsBlueprint = {
124975
125269
  let nextRpcId = 1;
124976
125270
  let envSetup = false;
124977
125271
  let initFailure = null;
124978
- let inFlight3 = null;
125272
+ let inFlight4 = null;
124979
125273
  let envRetired = false;
124980
125274
  const activatedBundleIds = /* @__PURE__ */ new Set();
124981
125275
  const events = new TypedEventEmitter();
@@ -124992,17 +125286,17 @@ var nativeDevtoolsBlueprint = {
124992
125286
  };
124993
125287
  const runEnsureEnv = () => {
124994
125288
  if (envRetired) return Promise.resolve();
124995
- if (inFlight3) return inFlight3;
124996
- inFlight3 = Promise.resolve().then(() => host.setupNativeDevtoolsEnv(udid, endpoint)).then(() => {
125289
+ if (inFlight4) return inFlight4;
125290
+ inFlight4 = Promise.resolve().then(() => host.setupNativeDevtoolsEnv(udid, endpoint)).then(() => {
124997
125291
  envSetup = true;
124998
125292
  initFailure = null;
124999
125293
  }).catch((err) => {
125000
125294
  noteInitFailure(err);
125001
125295
  throw err;
125002
125296
  }).finally(() => {
125003
- inFlight3 = null;
125297
+ inFlight4 = null;
125004
125298
  });
125005
- return inFlight3;
125299
+ return inFlight4;
125006
125300
  };
125007
125301
  const ensureEnvReady = () => {
125008
125302
  if (envSetup || initFailure?.givenUp) return Promise.resolve();
@@ -125210,7 +125504,7 @@ var nativeDevtoolsBlueprint = {
125210
125504
  armsEnv: !lentSocketPath,
125211
125505
  withdrawEnv: lentSocketPath ? () => Promise.resolve() : async () => {
125212
125506
  envRetired = true;
125213
- await inFlight3?.catch(() => {
125507
+ await inFlight4?.catch(() => {
125214
125508
  });
125215
125509
  await host.withdrawNativeDevtoolsEnv(udid, endpoint);
125216
125510
  envSetup = false;
@@ -125607,17 +125901,17 @@ function startSimulatorWatcher(registry2) {
125607
125901
  }
125608
125902
  }
125609
125903
  const ready2 = simctlWouldStartInstall() ? Promise.resolve() : poll(true);
125610
- let inFlight3 = ready2.catch(() => {
125611
- }).finally(() => inFlight3 = null);
125904
+ let inFlight4 = ready2.catch(() => {
125905
+ }).finally(() => inFlight4 = null);
125612
125906
  const interval2 = setInterval(() => {
125613
- if (inFlight3) return;
125907
+ if (inFlight4) return;
125614
125908
  if (simctlWouldStartInstall()) return;
125615
125909
  if (ticksToSkip > 0) {
125616
125910
  ticksToSkip -= 1;
125617
125911
  return;
125618
125912
  }
125619
- inFlight3 = poll(false).catch(() => {
125620
- }).finally(() => inFlight3 = null);
125913
+ inFlight4 = poll(false).catch(() => {
125914
+ }).finally(() => inFlight4 = null);
125621
125915
  }, POLL_INTERVAL_MS);
125622
125916
  return {
125623
125917
  stop: () => {
@@ -125690,6 +125984,7 @@ async function buildRemoteInstance(device) {
125690
125984
  const api = {
125691
125985
  apiUrl: stubUrl,
125692
125986
  streamUrl: stubUrl,
125987
+ deviceId: device.id,
125693
125988
  // Through `sendCommand`, as the attached instance below does, so a key the
125694
125989
  // session refuses reports the same failure as a refused touch instead of a
125695
125990
  // bare SDK error the caller cannot classify.
@@ -128368,13 +128663,13 @@ function decoded(url2) {
128368
128663
  return url2;
128369
128664
  }
128370
128665
  }
128371
- var inFlight2 = /* @__PURE__ */ new WeakMap();
128666
+ var inFlight3 = /* @__PURE__ */ new WeakMap();
128372
128667
  function navigate(cdp, url2) {
128373
128668
  const parsed2 = parseUrl(url2);
128374
128669
  if (parsed2?.protocol === "javascript:") return navigateOnce(cdp, url2, void 0);
128375
128670
  const key2 = parsed2?.href ?? url2;
128376
- let pending = inFlight2.get(cdp);
128377
- if (!pending) inFlight2.set(cdp, pending = /* @__PURE__ */ new Map());
128671
+ let pending = inFlight3.get(cdp);
128672
+ if (!pending) inFlight3.set(cdp, pending = /* @__PURE__ */ new Map());
128378
128673
  const running = pending.get(key2);
128379
128674
  if (running) return running;
128380
128675
  pending.clear();
@@ -128473,18 +128768,18 @@ var ScreencastManager = class {
128473
128768
  }
128474
128769
  } else if (this.activeCount === 0) {
128475
128770
  this.currentOpts = opts;
128476
- const inFlight3 = this.cdp.send("Page.startScreencast", this.toCdpStartArgs(opts)).then(() => void 0);
128477
- this.startInFlight = inFlight3;
128771
+ const inFlight4 = this.cdp.send("Page.startScreencast", this.toCdpStartArgs(opts)).then(() => void 0);
128772
+ this.startInFlight = inFlight4;
128478
128773
  try {
128479
- await inFlight3;
128774
+ await inFlight4;
128480
128775
  } catch (err) {
128481
- if (this.startInFlight === inFlight3) {
128776
+ if (this.startInFlight === inFlight4) {
128482
128777
  this.startInFlight = null;
128483
128778
  this.currentOpts = null;
128484
128779
  }
128485
128780
  throw err;
128486
128781
  }
128487
- if (this.startInFlight === inFlight3) {
128782
+ if (this.startInFlight === inFlight4) {
128488
128783
  this.startInFlight = null;
128489
128784
  this.activeCount += 1;
128490
128785
  acquired = true;
@@ -130378,56 +130673,6 @@ function parseNativeDescribeScreenResult(input2) {
130378
130673
  return nativeDescribeScreenResultSchema.parse(input2);
130379
130674
  }
130380
130675
 
130381
- // ../tool-server/src/tools/describe/contract.ts
130382
- init_zod();
130383
- var describeFrameSchema = external_exports.object({
130384
- x: external_exports.number().finite().min(0).max(1),
130385
- y: external_exports.number().finite().min(0).max(1),
130386
- width: external_exports.number().finite().min(0).max(1),
130387
- height: external_exports.number().finite().min(0).max(1)
130388
- });
130389
- var describeNodeSchema = external_exports.lazy(
130390
- () => external_exports.object({
130391
- role: external_exports.string().min(1),
130392
- frame: describeFrameSchema,
130393
- children: external_exports.array(describeNodeSchema),
130394
- label: external_exports.string().optional(),
130395
- hint: external_exports.string().optional(),
130396
- identifier: external_exports.string().optional(),
130397
- value: external_exports.string().optional(),
130398
- subtreeText: external_exports.string().optional(),
130399
- clickable: external_exports.boolean().optional(),
130400
- longClickable: external_exports.boolean().optional(),
130401
- scrollable: external_exports.boolean().optional(),
130402
- checkable: external_exports.boolean().optional(),
130403
- checked: external_exports.boolean().optional(),
130404
- disabled: external_exports.boolean().optional(),
130405
- password: external_exports.boolean().optional(),
130406
- scrollHidden: external_exports.number().int().nonnegative().optional(),
130407
- focused: external_exports.boolean().optional(),
130408
- selected: external_exports.boolean().optional(),
130409
- layer: external_exports.number().int().nonnegative().optional()
130410
- }).passthrough()
130411
- );
130412
- var UI_ORIENTATIONS = [
130413
- "portrait",
130414
- "portraitUpsideDown",
130415
- "landscapeLeft",
130416
- "landscapeRight"
130417
- ];
130418
- function asUiOrientation(v) {
130419
- return typeof v === "string" && UI_ORIENTATIONS.includes(v) ? v : void 0;
130420
- }
130421
- function parseDescribeResult(input2) {
130422
- return describeNodeSchema.parse(input2);
130423
- }
130424
- function getDescribeTapPoint(frame2) {
130425
- return {
130426
- x: frame2.x + frame2.width / 2,
130427
- y: frame2.y + frame2.height / 2
130428
- };
130429
- }
130430
-
130431
130676
  // ../tool-server/src/tools/describe/platforms/ios/ios-native-adapter.ts
130432
130677
  function clamp01(value) {
130433
130678
  return Math.min(1, Math.max(0, value));
@@ -130599,10 +130844,30 @@ async function describeIos(registry2, device, params, options = {}) {
130599
130844
  const facts = {};
130600
130845
  const data = await readIos(registry2, device, params, options, facts);
130601
130846
  readFacts.set(data, facts);
130847
+ if (options.frameSpace !== "native" && !facts.tvOs) {
130848
+ await toUprightFrames(data, device, facts);
130849
+ }
130602
130850
  return data;
130603
130851
  }
130852
+ async function toUprightFrames(data, device, facts) {
130853
+ let orientation = facts.uiOrientation;
130854
+ if (orientation === void 0) {
130855
+ if (facts.axAnswered || data.tree.children.length === 0) return;
130856
+ const read = facts.daemonGone ? { unknownReason: "the accessibility service is not running" } : await readUiOrientation(device.id);
130857
+ orientation = read.orientation;
130858
+ if (orientation === void 0) {
130859
+ if (read.unknownReason === void 0) return;
130860
+ const note = unknownOrientationNote(read, "these frames are in");
130861
+ data.hint = data.hint ? `${data.hint} ${note}` : note;
130862
+ return;
130863
+ }
130864
+ }
130865
+ if (!isTurned(orientation)) return;
130866
+ data.tree = nativeTreeToUi(data.tree, orientation);
130867
+ }
130604
130868
  async function readIos(registry2, device, params, options, facts) {
130605
130869
  const isTvOs = options.isTvOs ?? await isTvOsSimulator(device.id);
130870
+ facts.tvOs = isTvOs;
130606
130871
  if (isTvOs) {
130607
130872
  return { tree: emptyTree(), source: "ax-service", hint: TVOS_HINT };
130608
130873
  }
@@ -130632,7 +130897,11 @@ async function readIos(registry2, device, params, options, facts) {
130632
130897
  }
130633
130898
  if (axApi) {
130634
130899
  try {
130635
- tree = adaptAXDescribeToDescribeResult(await axApi.describe());
130900
+ const response = await axApi.describe();
130901
+ facts.axAnswered = true;
130902
+ facts.uiOrientation = response.interfaceOrientation;
130903
+ noteUiOrientation(device.id, response.interfaceOrientation, response.screenFrame);
130904
+ tree = adaptAXDescribeToDescribeResult(response);
130636
130905
  } catch (err) {
130637
130906
  crashSignal = axDaemonCrashSignal(err);
130638
130907
  if (crashSignal === void 0) {
@@ -132609,18 +132878,18 @@ function wsUrlFromHttp(httpUrl2) {
132609
132878
  function createPreviewRouter(registry2) {
132610
132879
  const router = import_express.default.Router();
132611
132880
  let lastOpenedRound = -1;
132612
- const trackPreviewOpenedOnce = (snap2) => {
132613
- if (!(snap2.proposals.length > 0 || snap2.cliSession) || snap2.round === lastOpenedRound) return;
132614
- lastOpenedRound = snap2.round;
132881
+ const trackPreviewOpenedOnce = (snap3) => {
132882
+ if (!(snap3.proposals.length > 0 || snap3.cliSession) || snap3.round === lastOpenedRound) return;
132883
+ lastOpenedRound = snap3.round;
132615
132884
  track("lens:preview_opened", {
132616
- round: snap2.round,
132617
- element_count: snap2.proposals.length,
132618
- variant_count: snap2.proposals.reduce((n, p) => n + p.variants.length, 0),
132619
- is_cli_session: snap2.cliSession,
132885
+ round: snap3.round,
132886
+ element_count: snap3.proposals.length,
132887
+ variant_count: snap3.proposals.reduce((n, p) => n + p.variants.length, 0),
132888
+ is_cli_session: snap3.cliSession,
132620
132889
  // `device` deliberately survives the store's reset(), so a CLI up-front
132621
132890
  // open (no proposals staged yet) would otherwise report a prior flow's
132622
132891
  // platform.
132623
- platform: snap2.proposals.length > 0 && snap2.device ? classifyDeviceForTelemetry(snap2.device) : void 0
132892
+ platform: snap3.proposals.length > 0 && snap3.device ? classifyDeviceForTelemetry(snap3.device) : void 0
132624
132893
  });
132625
132894
  };
132626
132895
  const requireLensFlag = (res) => {
@@ -132987,9 +133256,13 @@ data: ${JSON.stringify(data)}
132987
133256
  res.status(400).json({ error: `Unknown device "${udid}". Use a udid/serial from /preview/simulators.` });
132988
133257
  return;
132989
133258
  }
132990
- const data = device.platform === "ios" ? await describeIos(registry2, device, {}) : await describeAndroid(registry2, udid);
133259
+ const data = device.platform === "ios" ? (
133260
+ // Drawn over the native video stream, so in its portrait-native space.
133261
+ await describeIos(registry2, device, {}, { frameSpace: "native" })
133262
+ ) : await describeAndroid(registry2, udid);
133263
+ const uiOrientation = device.platform === "ios" && isIosSimulator(device) ? (await readUiOrientation(device.id)).orientation : void 0;
132991
133264
  res.set("Cache-Control", "no-store");
132992
- res.json(data);
133265
+ res.json(uiOrientation ? { ...data, uiOrientation } : data);
132993
133266
  } catch (err) {
132994
133267
  res.status(500).json({ error: err instanceof Error ? err.message : String(err) });
132995
133268
  }
@@ -144119,67 +144392,6 @@ async function queryMacosTree(registry2, device) {
144119
144392
 
144120
144393
  // ../tool-server/src/utils/ui-tree-match.ts
144121
144394
  init_zod();
144122
-
144123
- // ../tool-server/src/tools/flows/flow-orientation.ts
144124
- function uiPointToNative(p, orientation) {
144125
- switch (orientation) {
144126
- case "landscapeRight":
144127
- return { x: 1 - p.y, y: p.x };
144128
- case "landscapeLeft":
144129
- return { x: p.y, y: 1 - p.x };
144130
- case "portraitUpsideDown":
144131
- return { x: 1 - p.x, y: 1 - p.y };
144132
- default:
144133
- return { x: p.x, y: p.y };
144134
- }
144135
- }
144136
- function nativeFrameToUi(f, orientation) {
144137
- switch (orientation) {
144138
- case "landscapeRight":
144139
- return { x: f.y, y: snap(1 - f.x - f.width), width: f.height, height: f.width };
144140
- case "landscapeLeft":
144141
- return { x: snap(1 - f.y - f.height), y: f.x, width: f.height, height: f.width };
144142
- case "portraitUpsideDown":
144143
- return {
144144
- x: snap(1 - f.x - f.width),
144145
- y: snap(1 - f.y - f.height),
144146
- width: f.width,
144147
- height: f.height
144148
- };
144149
- default:
144150
- return f;
144151
- }
144152
- }
144153
- function snap(v) {
144154
- return Math.round(v * 1e9) / 1e9;
144155
- }
144156
- function uiVectorToNative(v, orientation) {
144157
- switch (orientation) {
144158
- case "landscapeRight":
144159
- return { x: -v.y, y: v.x };
144160
- case "landscapeLeft":
144161
- return { x: v.y, y: -v.x };
144162
- case "portraitUpsideDown":
144163
- return { x: -v.x, y: -v.y };
144164
- default:
144165
- return { x: v.x, y: v.y };
144166
- }
144167
- }
144168
- var DIRECTION_VECTOR = {
144169
- up: { x: 0, y: -1 },
144170
- down: { x: 0, y: 1 },
144171
- left: { x: -1, y: 0 },
144172
- right: { x: 1, y: 0 }
144173
- };
144174
- function nativeDirection(d, orientation) {
144175
- const v = uiVectorToNative(DIRECTION_VECTOR[d], orientation);
144176
- if (v.x > 0) return "right";
144177
- if (v.x < 0) return "left";
144178
- if (v.y > 0) return "down";
144179
- return "up";
144180
- }
144181
-
144182
- // ../tool-server/src/utils/ui-tree-match.ts
144183
144395
  function hasVisibleText(text) {
144184
144396
  return text.replace(/[\p{Cf}\p{Co}\p{Cc}]/gu, "").trim().length > 0;
144185
144397
  }
@@ -144303,20 +144515,8 @@ function followKind(node2, anchor2) {
144303
144515
  function frameAfter(node2, anchor2) {
144304
144516
  return followKind(node2, anchor2) !== "no";
144305
144517
  }
144306
- function readingFrames(orientation) {
144307
- if (orientation === void 0 || orientation === "portrait") return (node2) => node2.frame;
144308
- const turned = /* @__PURE__ */ new Map();
144309
- return (node2) => {
144310
- let frame2 = turned.get(node2);
144311
- if (frame2 === void 0) {
144312
- frame2 = nativeFrameToUi(node2.frame, orientation);
144313
- turned.set(node2, frame2);
144314
- }
144315
- return frame2;
144316
- };
144317
- }
144318
- function afterTester(anchors, reading) {
144319
- return (node2) => anchors.some((a) => a !== node2 && frameAfter(reading(node2), reading(a)));
144518
+ function afterTester(anchors) {
144519
+ return (node2) => anchors.some((a) => a !== node2 && frameAfter(node2.frame, a.frame));
144320
144520
  }
144321
144521
  function comparePick(a, b) {
144322
144522
  return frameArea(a) - frameArea(b) || a.width - b.width || a.height - b.height;
@@ -144327,21 +144527,21 @@ function compareBandPick(a, b) {
144327
144527
  function compareBelowPick(a, b) {
144328
144528
  return a.y - b.y || a.x - b.x || comparePick(a, b);
144329
144529
  }
144330
- function nearestAfter(candidates, anchors, reading) {
144530
+ function nearestAfter(candidates, anchors) {
144331
144531
  if (candidates.length === 0 || anchors.length === 0) return [];
144332
144532
  const picked = /* @__PURE__ */ new Set();
144333
144533
  for (const anchor2 of anchors) {
144334
- const af = reading(anchor2);
144534
+ const af = anchor2.frame;
144335
144535
  let band;
144336
144536
  let below;
144337
144537
  for (const c of candidates) {
144338
144538
  if (c === anchor2) continue;
144339
- const f = reading(c);
144539
+ const f = c.frame;
144340
144540
  const kind = followKind(f, af);
144341
144541
  if (kind === "band") {
144342
- if (band === void 0 || compareBandPick(f, reading(band)) < 0) band = c;
144542
+ if (band === void 0 || compareBandPick(f, band.frame) < 0) band = c;
144343
144543
  } else if (kind === "below") {
144344
- if (below === void 0 || compareBelowPick(f, reading(below)) < 0) below = c;
144544
+ if (below === void 0 || compareBelowPick(f, below.frame) < 0) below = c;
144345
144545
  }
144346
144546
  }
144347
144547
  const best = band ?? below;
@@ -144349,28 +144549,28 @@ function nearestAfter(candidates, anchors, reading) {
144349
144549
  }
144350
144550
  return candidates.filter((c) => picked.has(c));
144351
144551
  }
144352
- function findAll(root, selector, orientation) {
144552
+ function findAll(root, selector) {
144353
144553
  const all = [];
144354
144554
  const collect2 = (node2) => {
144355
144555
  all.push(node2);
144356
144556
  for (const child of node2.children) collect2(child);
144357
144557
  };
144358
144558
  for (const child of root.children) collect2(child);
144359
- return resolveSelector(all, selector, readingFrames(orientation));
144559
+ return resolveSelector(all, selector);
144360
144560
  }
144361
144561
  var SELECTOR_RELATIONS = ["within", "after", "next"];
144362
144562
  var RELATION_RESOLVERS = {
144363
144563
  within: (matches2, scope) => matches2.filter(containmentTester(scope)),
144364
- after: (matches2, scope, reading) => matches2.filter(afterTester(scope, reading)),
144365
- next: (matches2, scope, reading) => nearestAfter(matches2, scope, reading)
144564
+ after: (matches2, scope) => matches2.filter(afterTester(scope)),
144565
+ next: (matches2, scope) => nearestAfter(matches2, scope)
144366
144566
  };
144367
- function resolveSelector(all, selector, reading) {
144567
+ function resolveSelector(all, selector) {
144368
144568
  const regex = selectorTextRegex(selector);
144369
144569
  let matches2 = all.filter((n) => matchNodeWithRegex(n, selector, regex));
144370
144570
  for (const relation of SELECTOR_RELATIONS) {
144371
144571
  const scope = selector[relation];
144372
144572
  if (scope === void 0) continue;
144373
- matches2 = RELATION_RESOLVERS[relation](matches2, resolveSelector(all, scope, reading), reading);
144573
+ matches2 = RELATION_RESOLVERS[relation](matches2, resolveSelector(all, scope));
144374
144574
  }
144375
144575
  return matches2;
144376
144576
  }
@@ -144382,12 +144582,11 @@ function frontmost(nodes) {
144382
144582
  for (const n of nodes) top = Math.max(top, n.layer ?? 0);
144383
144583
  return top === 0 ? nodes : nodes.filter((n) => n.layer === top);
144384
144584
  }
144385
- function firstInReadingOrder(matches2, orientation) {
144386
- const reading = readingFrames(orientation);
144585
+ function firstInReadingOrder(matches2) {
144387
144586
  let best;
144388
144587
  let bestFrame;
144389
144588
  for (const n of frontmost(matches2)) {
144390
- const f = reading(n);
144589
+ const f = n.frame;
144391
144590
  if (bestFrame === void 0 || f.y < bestFrame.y || f.y === bestFrame.y && f.x < bestFrame.x) {
144392
144591
  best = n;
144393
144592
  bestFrame = f;
@@ -144404,15 +144603,15 @@ function macFieldText(node2, macos) {
144404
144603
  return macos && MAC_TEXT_FIELD_ROLES.has(node2.role) && !node2.password ? node2.value ?? "" : void 0;
144405
144604
  }
144406
144605
  var MAC_TEXT_ROLES = /* @__PURE__ */ new Set(["AXStaticText", "AXHeading", "AXLink"]);
144407
- function textCheckTarget(matches2, orientation, macos) {
144606
+ function textCheckTarget(matches2, macos) {
144408
144607
  const read = macos ? matches2.filter(
144409
144608
  (n) => n.role !== "AXTextArea" || !matches2.some(
144410
144609
  (m) => isVisible(m) && MAC_TEXT_ROLES.has(m.role) && frameWithin(m.frame, n.frame)
144411
144610
  )
144412
144611
  ) : matches2;
144413
- return firstInReadingOrder(read.filter(isVisible), orientation) ?? firstInReadingOrder(read, orientation);
144612
+ return firstInReadingOrder(read.filter(isVisible)) ?? firstInReadingOrder(read);
144414
144613
  }
144415
- function evaluateCondition(condition, expectedText, matches2, textMatch = "contains", orientation, textFieldsShowText = false) {
144614
+ function evaluateCondition(condition, expectedText, matches2, textMatch = "contains", textFieldsShowText = false) {
144416
144615
  switch (condition) {
144417
144616
  case "exists":
144418
144617
  return matches2.length > 0;
@@ -144421,7 +144620,7 @@ function evaluateCondition(condition, expectedText, matches2, textMatch = "conta
144421
144620
  case "hidden":
144422
144621
  return !matches2.some(isVisible);
144423
144622
  case "text": {
144424
- const first = textCheckTarget(matches2, orientation, textFieldsShowText);
144623
+ const first = textCheckTarget(matches2, textFieldsShowText);
144425
144624
  if (first === void 0 || expectedText === void 0) return false;
144426
144625
  const field2 = macFieldText(first, textFieldsShowText);
144427
144626
  if (field2 !== void 0) {
@@ -144486,14 +144685,13 @@ function exactFieldCount(node2, selector, fullTextRegex) {
144486
144685
  if (selector.role !== void 0 && equalsCI(node2.role, selector.role)) count2++;
144487
144686
  return count2;
144488
144687
  }
144489
- function selectorToFrame(root, selector, orientation) {
144490
- const visible = frontmost(findAll(root, selector, orientation).filter(isVisible));
144688
+ function selectorToFrame(root, selector) {
144689
+ const visible = frontmost(findAll(root, selector).filter(isVisible));
144491
144690
  if (visible.length === 0) return void 0;
144492
- const reading = readingFrames(orientation);
144493
144691
  if (!hasOwnConstraint(selector)) {
144494
144692
  let first;
144495
144693
  for (const n of visible) {
144496
- if (first === void 0 || compareBelowPick(reading(n), reading(first)) < 0) first = n;
144694
+ if (first === void 0 || compareBelowPick(n.frame, first.frame) < 0) first = n;
144497
144695
  }
144498
144696
  return first?.frame;
144499
144697
  }
@@ -144510,8 +144708,8 @@ function selectorToFrame(root, selector, orientation) {
144510
144708
  continue;
144511
144709
  }
144512
144710
  const areaDelta = frameArea(n.frame) - frameArea(best.frame);
144513
- const nf = reading(n);
144514
- const bf = reading(best);
144711
+ const nf = n.frame;
144712
+ const bf = best.frame;
144515
144713
  if (areaDelta < 0 || areaDelta === 0 && (nf.y < bf.y || nf.y === bf.y && nf.x < bf.x)) {
144516
144714
  best = n;
144517
144715
  }
@@ -144598,7 +144796,6 @@ function evaluateMatches(params, matches2) {
144598
144796
  params.expectedText,
144599
144797
  matches2,
144600
144798
  params.textMatch,
144601
- void 0,
144602
144799
  isMacos(params)
144603
144800
  );
144604
144801
  }
@@ -144627,7 +144824,7 @@ function timeoutNote(params, lastTree, fetchError, lastData) {
144627
144824
  let base;
144628
144825
  switch (params.condition) {
144629
144826
  case "text": {
144630
- const first = textCheckTarget(matches2, void 0, isMacos(params));
144827
+ const first = textCheckTarget(matches2, isMacos(params));
144631
144828
  const wanted = params.textMatch === "equals" ? "equal" : "contain";
144632
144829
  const shown = first ? redactTypedSecrets(params.udid, macFieldText(first, isMacos(params)) ?? assertText(first)) : void 0;
144633
144830
  base = shown !== void 0 ? `element matched but its text was "${shown}" (wanted to ${wanted} "${params.expectedText}")` : "no element matched the selector before timeout";
@@ -145317,9 +145514,12 @@ var REACT_PROFILER_TOOL_CAPABILITY = {
145317
145514
  ...RN_ONLY_TOOL_CAPABILITY,
145318
145515
  macos: { app: true, catalyst: true }
145319
145516
  };
145517
+ function isChromiumDebuggerTarget(deviceId) {
145518
+ return !!canonicalDeviceId(deviceId)?.startsWith(CHROMIUM_ID_PREFIX);
145519
+ }
145320
145520
  function debuggerServiceRef(params) {
145321
145521
  const deviceId = canonicalDeviceId(params.device_id);
145322
- if (deviceId && deviceId.startsWith(CHROMIUM_ID_PREFIX)) {
145522
+ if (deviceId && isChromiumDebuggerTarget(deviceId)) {
145323
145523
  const device = resolveDevice(deviceId);
145324
145524
  return chromiumJsRuntimeDebuggerRef(device);
145325
145525
  }
@@ -147398,10 +147598,10 @@ function createInspector(serial, packageName, initialMetroPort) {
147398
147598
  log(`the agent dropped ${conn.droppedEvents} events while it was disconnected`);
147399
147599
  }
147400
147600
  if (Array.isArray(r.inFlight)) {
147401
- const inFlight3 = new Set(r.inFlight.filter((id) => typeof id === "string"));
147601
+ const inFlight4 = new Set(r.inFlight.filter((id) => typeof id === "string"));
147402
147602
  for (let c = conn; c; c = c.resumes) {
147403
147603
  for (const record2 of c.byLayerId.values()) {
147404
- if (inFlight3.has(record2.layerId)) revive(record2);
147604
+ if (inFlight4.has(record2.layerId)) revive(record2);
147405
147605
  else if (isOpen(record2)) markLost(record2, LOST_WHILE_DISCONNECTED);
147406
147606
  }
147407
147607
  }
@@ -148255,6 +148455,93 @@ init_zod();
148255
148455
  init_src2();
148256
148456
  init_capability();
148257
148457
  init_device_info();
148458
+
148459
+ // ../tool-server/src/utils/native-devtools-upright.ts
148460
+ function isRect(v) {
148461
+ if (typeof v !== "object" || v === null) return false;
148462
+ const r = v;
148463
+ return typeof r.x === "number" && typeof r.y === "number" && typeof r.width === "number" && typeof r.height === "number";
148464
+ }
148465
+ function isSize(v) {
148466
+ if (typeof v !== "object" || v === null) return false;
148467
+ const r = v;
148468
+ return typeof r.width === "number" && typeof r.height === "number";
148469
+ }
148470
+ function uiSize(space) {
148471
+ return uiScreenSize(space.screen, space.orientation);
148472
+ }
148473
+ function turnPointsRect(rect, space) {
148474
+ const { width: w, height: h } = space.screen;
148475
+ if (!(w > 0 && h > 0)) return rect;
148476
+ const n = nativeFrameToUi(
148477
+ { x: rect.x / w, y: rect.y / h, width: rect.width / w, height: rect.height / h },
148478
+ space.orientation
148479
+ );
148480
+ const ui = uiSize(space);
148481
+ return {
148482
+ ...rect,
148483
+ x: n.x * ui.width,
148484
+ y: n.y * ui.height,
148485
+ width: n.width * ui.width,
148486
+ height: n.height * ui.height
148487
+ };
148488
+ }
148489
+ function turnPoints(p, space) {
148490
+ const { width: w, height: h } = space.screen;
148491
+ if (!(w > 0 && h > 0)) return p;
148492
+ const n = nativePointToUi({ x: p.x / w, y: p.y / h }, space.orientation);
148493
+ const ui = uiSize(space);
148494
+ return { ...p, x: n.x * ui.width, y: n.y * ui.height };
148495
+ }
148496
+ function fixedSpaceOf(result, read) {
148497
+ const r = typeof result === "object" && result !== null ? result : {};
148498
+ const screen = isSize(r.screen) ? r.screen : void 0;
148499
+ const orientation = asUiOrientation(
148500
+ screen?.interfaceOrientation
148501
+ ) ?? read.orientation;
148502
+ if (!isTurned(orientation)) return void 0;
148503
+ const size = screen ?? (isSize(r.screenFrame) ? r.screenFrame : void 0) ?? read.nativeScreen;
148504
+ if (!size || !(size.width > 0 && size.height > 0)) return void 0;
148505
+ return { orientation, screen: { width: size.width, height: size.height } };
148506
+ }
148507
+ function uprightNativeResult(method, result, space) {
148508
+ const describeScreen = method === "ViewHierarchy.describeScreen";
148509
+ const walk = (v, inElement) => {
148510
+ if (Array.isArray(v)) return v.map((item) => walk(item, inElement));
148511
+ if (typeof v !== "object" || v === null) return v;
148512
+ const out = {};
148513
+ for (const [key2, value] of Object.entries(v)) {
148514
+ if (key2 === "screenFrame" && isRect(value)) out[key2] = turnPointsRect(value, space);
148515
+ else if (key2 === "screenFrame" && isSize(value))
148516
+ out[key2] = uiScreenSize(value, space.orientation);
148517
+ else if (key2 === "screen" && isSize(value)) out[key2] = uiScreenSize(value, space.orientation);
148518
+ else if (key2 === "normalizedFrame" && isRect(value))
148519
+ out[key2] = { ...value, ...nativeFrameToUi(value, space.orientation) };
148520
+ else if (key2 === "normalizedTapPoint" && isPoint(value))
148521
+ out[key2] = { ...value, ...nativePointToUi(value, space.orientation) };
148522
+ else if (inElement && key2 === "frame" && isRect(value))
148523
+ out[key2] = turnPointsRect(value, space);
148524
+ else if (inElement && key2 === "tapPoint" && isPoint(value))
148525
+ out[key2] = turnPoints(value, space);
148526
+ else out[key2] = walk(value, describeScreen && key2 === "elements");
148527
+ }
148528
+ return out;
148529
+ };
148530
+ return walk(result, false);
148531
+ }
148532
+ function isPoint(v) {
148533
+ if (typeof v !== "object" || v === null) return false;
148534
+ const r = v;
148535
+ return typeof r.x === "number" && typeof r.y === "number";
148536
+ }
148537
+ function fixedPointFromUpright(p, space) {
148538
+ const ui = uiSize(space);
148539
+ if (!(ui.width > 0 && ui.height > 0)) return p;
148540
+ const n = uiPointToNative({ x: p.x / ui.width, y: p.y / ui.height }, space.orientation);
148541
+ return { x: n.x * space.screen.width, y: n.y * space.screen.height };
148542
+ }
148543
+
148544
+ // ../tool-server/src/tools/native-devtools/macos-view-hierarchy.ts
148258
148545
  var nativeAppTarget = {
148259
148546
  udid: external_exports.string().describe(
148260
148547
  "Simulator UDID<flag:macos-apps>, or a Mac app id (macos-app-<bundle id>)</flag:macos-apps>"
@@ -148295,7 +148582,17 @@ async function queryViewHierarchyFor(services, params, toolId, method, errorCode
148295
148582
  const api = services.nativeDevtools;
148296
148583
  const blocked = await precheckNativeDevtools(api, udid, bundleId);
148297
148584
  if (blocked) return blocked;
148585
+ const read = isIosSimulator(device) && !inNativeCoordinates() ? await readUiOrientation(device.id) : void 0;
148586
+ const lookupSpace = read ? fixedSpaceOf(void 0, read) : void 0;
148587
+ if (lookupSpace && typeof rpcParams.x === "number" && typeof rpcParams.y === "number") {
148588
+ Object.assign(
148589
+ rpcParams,
148590
+ fixedPointFromUpright({ x: rpcParams.x, y: rpcParams.y }, lookupSpace)
148591
+ );
148592
+ }
148298
148593
  result = await api.queryViewHierarchy(bundleId, method, rpcParams);
148594
+ const space = read ? fixedSpaceOf(result, read) : void 0;
148595
+ if (space) result = uprightNativeResult(method, result, space);
148299
148596
  }
148300
148597
  if (errorCode2 && result.error) {
148301
148598
  throw new FailureError(result.error, {
@@ -148522,7 +148819,7 @@ var nativeFindViewsTool = {
148522
148819
  id: "native-find-views",
148523
148820
  description: `Search for specific UIViews in the running app by class name, accessibility identifier, accessibility label, tag or React Native nativeID; at least one of these params is required.
148524
148821
  Use when you need to locate a specific view by its properties without dumping the entire native-full-hierarchy.
148525
- Returns { status: "ok", matches }: the matching views with their frames, properties, optional ancestors and optional children. Frames are in points. frame and center are relative to the superview, and windowFrame turns with the UI. To tap a view, divide the centre of its screenFrame by the screen size in points, which native-full-hierarchy returns as screen (maxDepth: 1 is enough), and pass the result to gesture-tap. Matches are not filtered for visibility. Before tapping, call native-view-at-point with hitTest: true at that centre, with skipClasses ["UITextEffectsWindow"]. If it does not return the match or a descendant, check a screenshot.
148822
+ Returns { status: "ok", matches }: the matching views with their frames, properties, optional ancestors and optional children. Frames are in points. frame and center are relative to the superview, and windowFrame turns with the UI. screenFrame is on the axes of the UI as the user sees it, also when the UI is landscape. To tap a view, divide the centre of its screenFrame by the screen size in points, which native-full-hierarchy returns as screen (maxDepth: 1 is enough), and pass the result to gesture-tap. Matches are not filtered for visibility. Before tapping, call native-view-at-point with hitTest: true at that centre, with skipClasses ["UITextEffectsWindow"]. If it does not return the match or a descendant, check a screenshot.
148526
148823
  <flag:macos-apps>On a Mac app it searches the NSViews of every visible window: className is the NSView class, and identifier matches the accessibility identifier or the view identifier. SwiftUI sets a control's identifier and label on an accessibility element, not on an NSView, so an identifier or label search does not find SwiftUI controls: describe lists them with their identifiers and frames. The tap recipe above and the statuses below are iOS only.
148527
148824
  </flag:macos-apps>If status is restart_required: follow the message (usually restart-app), then retry. If status is service_stale: the app is already injected, so restarting it cannot help. Restart the tool-server (\`argent server stop && argent server start --detach\`) and retry. If the same status comes back after that restart, stop restarting: follow the message, which names the terminal fallback. If status is connect_pending: the app is injected and still connecting. Do not restart it, wait a few seconds and retry. If status is init_failed: follow the message (re-boot the simulator) rather than retrying.
148528
148825
  An Apple system app is rejected outright (terminal: never retry it).`,
@@ -148583,7 +148880,7 @@ var nativeFullHierarchyTool = {
148583
148880
  WARNING: Output can be extremely large (100KB\u2013500KB+) for complex apps, especially those built with SwiftUI. Prefer native-find-views for targeted queries.
148584
148881
  Reduce the output with skipClasses / skipClassPrefixes, fields and maxDepth.
148585
148882
  Use when you need deep layout debugging, finding views with no accessibility labels, or verifying view structure not exposed through the accessibility tree.
148586
- Returns { status: "ok", windows, screen } with the full view hierarchy. screen gives the screen size in points on its portrait axes, and the interfaceOrientation of the UI (portrait, portraitUpsideDown, landscapeLeft, landscapeRight). Each screenFrame uses the portrait axes of the screen. Each windowFrame uses the axes of its window, which turn with the UI.
148883
+ Returns { status: "ok", windows, screen } with the full view hierarchy. screen gives the screen size in points, and the interfaceOrientation of the UI (portrait, portraitUpsideDown, landscapeLeft, landscapeRight). The size and each screenFrame use the axes of the UI as the user sees it, also when the UI is landscape: the space of screenshots and describe frames. Each windowFrame uses the axes of its window, which turn with the UI too.
148587
148884
  <flag:macos-apps>On a Mac app it returns the AppKit view tree of the app's windows, each screenFrame in points from the top-left of the area describe reports. The statuses below are iOS only.
148588
148885
  </flag:macos-apps>If status is restart_required: follow the message (usually restart-app), then retry. If status is service_stale: the app is already injected, so restarting it cannot help. Restart the tool-server (\`argent server stop && argent server start --detach\`) and retry. If the same status comes back after that restart, stop restarting: follow the message, which names the terminal fallback. If status is connect_pending: the app is injected and still connecting. Do not restart it, wait a few seconds and retry. If status is init_failed: follow the message (re-boot the simulator) rather than retrying.
148589
148886
  An Apple system app is rejected outright (terminal: never retry it).`,
@@ -148609,8 +148906,9 @@ An Apple system app is rejected outright (terminal: never retry it).`,
148609
148906
  (result) => ({
148610
148907
  status: "ok",
148611
148908
  windows: result.windows ?? [],
148612
- // `screen` is the screen's point size in its portrait-native space, the
148613
- // space every `screenFrame` is in, and the interface orientation on it;
148909
+ // `screen` is the screen's point size in the UI's upright space, the
148910
+ // space every `screenFrame` is in once turned (see
148911
+ // `utils/native-devtools-upright.ts`), and the interface orientation;
148614
148912
  // an older injected build reports none.
148615
148913
  ...result.screen !== void 0 ? { screen: result.screen } : {}
148616
148914
  })
@@ -148634,7 +148932,7 @@ var nativeDescribeScreenTool = {
148634
148932
  description: `Read the running app's native accessibility screen description via injected native devtools.
148635
148933
 
148636
148934
  Returns a flat list of accessibility leaf elements with:
148637
- - raw frame and tapPoint in points, on the portrait axes of the screen
148935
+ - raw frame and tapPoint in points, on the axes of the UI as the user sees it
148638
148936
  - normalizedFrame and normalizedTapPoint on the same axes. gesture-tap uses
148639
148937
  these axes, also when the UI is landscape
148640
148938
  - top-level screenFrame metadata: the screen bounds on these axes
@@ -148681,7 +148979,7 @@ init_src2();
148681
148979
  var viewAtPointParams = {
148682
148980
  ...nativeAppTarget,
148683
148981
  x: external_exports.number().describe(
148684
- "Raw X coordinate in points, on the portrait axes of the screen<flag:macos-apps>; on a Mac app, points from the top-left of the area describe reports</flag:macos-apps>. NOT normalized [0,1] tap space."
148982
+ "Raw X coordinate in points, on the axes of the UI as the user sees it (the axes of screenshots and describe frames)<flag:macos-apps>; on a Mac app, points from the top-left of the area describe reports</flag:macos-apps>. NOT normalized [0,1] tap space."
148685
148983
  ),
148686
148984
  y: external_exports.number().describe("Raw Y coordinate in points, on the same axes as x. NOT normalized [0,1] tap space."),
148687
148985
  includeAncestors: external_exports.boolean().optional().describe("Include ancestor chain for the matched view (default true)"),
@@ -148727,7 +149025,7 @@ identifier, label and layer name, plus its ancestors and subviews as requested.
148727
149025
  view is null when nothing is drawn at that point, or with hitTest when no touchable view sits under it.
148728
149026
 
148729
149027
  To get x and y from a normalized describe frame, multiply its values by the
148730
- screen size in points, also when the UI is landscape.
149028
+ screen size in points, on the same axes (landscape when the UI is).
148731
149029
  native-full-hierarchy returns that size as screen (pass maxDepth: 1 and fields: ["className"] to keep it small).<flag:macos-apps> On a Mac app,
148732
149030
  multiply them by the size of the area describe reports instead.</flag:macos-apps>
148733
149031
 
@@ -153129,7 +153427,7 @@ async function waitForHarmonyTarget(before, deadline, checkAlive, expected) {
153129
153427
  }
153130
153428
  async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153131
153429
  const probePath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-harmony-bootprobe-${process.hrtime.bigint()}.json`);
153132
- let inFlight3 = null;
153430
+ let inFlight4 = null;
153133
153431
  try {
153134
153432
  for (; ; ) {
153135
153433
  const budget = deadline - Date.now();
@@ -153145,9 +153443,9 @@ async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153145
153443
  () => true,
153146
153444
  () => false
153147
153445
  );
153148
- inFlight3 = probe4;
153446
+ inFlight4 = probe4;
153149
153447
  const answered = await withinBudget(() => probe4, deadline);
153150
- if (answered !== null) inFlight3 = null;
153448
+ if (answered !== null) inFlight4 = null;
153151
153449
  if (answered) return true;
153152
153450
  checkAlive();
153153
153451
  const remaining = deadline - Date.now();
@@ -153157,7 +153455,7 @@ async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153157
153455
  } finally {
153158
153456
  const remove = () => (0, import_promises14.rm)(probePath, { force: true }).catch(() => {
153159
153457
  });
153160
- if (inFlight3) void inFlight3.then(remove);
153458
+ if (inFlight4) void inFlight4.then(remove);
153161
153459
  else await remove();
153162
153460
  }
153163
153461
  }
@@ -154129,9 +154427,9 @@ Common Android packages: com.android.settings, com.android.chrome, com.google.an
154129
154427
  execute: dispatchByPlatform({
154130
154428
  toolId: "launch-app",
154131
154429
  capability: capability3,
154132
- ios: makeIosImpl(registry2),
154430
+ ios: forgettingUiOrientation(makeIosImpl(registry2)),
154133
154431
  iosDevice: iosDeviceImpl,
154134
- iosRemote: iosRemoteImpl,
154432
+ iosRemote: forgettingUiOrientation(iosRemoteImpl),
154135
154433
  android: androidImpl,
154136
154434
  chromium: chromiumImpl,
154137
154435
  vega: vegaImpl,
@@ -154419,9 +154717,9 @@ For Mac apps, kind is 'catalyst' or 'app'. Check appPath and args to confirm the
154419
154717
  execute: dispatchByPlatform({
154420
154718
  toolId: "restart-app",
154421
154719
  capability: capability4,
154422
- ios: makeIosImpl2(registry2),
154720
+ ios: forgettingUiOrientation(makeIosImpl2(registry2)),
154423
154721
  iosDevice: iosDeviceImpl2,
154424
- iosRemote: iosRemoteImpl2,
154722
+ iosRemote: forgettingUiOrientation(iosRemoteImpl2),
154425
154723
  android: androidImpl2,
154426
154724
  vega: vegaImpl2,
154427
154725
  harmony: harmonyImpl2,
@@ -154466,7 +154764,7 @@ Succeeds when the app is not running or not installed.`,
154466
154764
  execute: dispatchByPlatform({
154467
154765
  toolId: "terminate-app",
154468
154766
  capability: capability5,
154469
- ios: {
154767
+ ios: forgettingUiOrientation({
154470
154768
  requires: ["xcrun"],
154471
154769
  handler: async (_services, { udid, bundleId }) => {
154472
154770
  const args = await simctlArgsForUdid(udid, ["terminate", udid, bundleId]);
@@ -154490,8 +154788,8 @@ Succeeds when the app is not running or not installed.`,
154490
154788
  const terminated = await tolerateNothingToTerminate(terminate, SIMCTL_NOTHING_TO_TERMINATE);
154491
154789
  return { terminated, bundleId };
154492
154790
  }
154493
- },
154494
- iosRemote: {
154791
+ }),
154792
+ iosRemote: forgettingUiOrientation({
154495
154793
  requires: ["sim-remote"],
154496
154794
  handler: async (_services, { udid, bundleId }) => {
154497
154795
  const terminated = await tolerateNothingToTerminate(
@@ -154500,7 +154798,7 @@ Succeeds when the app is not running or not installed.`,
154500
154798
  );
154501
154799
  return { terminated, bundleId };
154502
154800
  }
154503
- },
154801
+ }),
154504
154802
  android: {
154505
154803
  requires: ["adb"],
154506
154804
  handler: async (_services, { udid, bundleId }) => {
@@ -154978,10 +155276,10 @@ Returns { reinstalled, bundleId }. Fails if \`appPath\` does not exist or is not
154978
155276
  execute: dispatchByPlatform({
154979
155277
  toolId: "reinstall-app",
154980
155278
  capability: capability6,
154981
- ios: iosImpl,
155279
+ ios: forgettingUiOrientation(iosImpl),
154982
155280
  android: androidImpl3,
154983
155281
  iosDevice: iosDeviceImpl3,
154984
- iosRemote: iosRemoteImpl3,
155282
+ iosRemote: forgettingUiOrientation(iosRemoteImpl3),
154985
155283
  vega: vegaImpl3,
154986
155284
  harmony: harmonyImpl3
154987
155285
  })
@@ -155598,11 +155896,11 @@ Returns { opened, url, note? }. \`note\` explains the routing caveat when a web
155598
155896
  execute: dispatchByPlatform({
155599
155897
  toolId: "open-url",
155600
155898
  capability: capability8,
155601
- ios: iosImpl3,
155899
+ ios: forgettingUiOrientation(iosImpl3),
155602
155900
  iosDevice: iosDeviceImpl4,
155603
155901
  android: androidImpl5,
155604
155902
  harmony: harmonyImpl4,
155605
- iosRemote: iosRemoteImpl5,
155903
+ iosRemote: forgettingUiOrientation(iosRemoteImpl5),
155606
155904
  chromium: chromiumImpl2,
155607
155905
  macos: macosImpl3
155608
155906
  })
@@ -155688,10 +155986,14 @@ function captureLooksUpright(requested, size) {
155688
155986
  }
155689
155987
 
155690
155988
  // ../tool-server/src/utils/rotation-aware-capture.ts
155989
+ init_device_info();
155691
155990
  async function captureScreenshotUpright(api, device, requestedRotation, signal, scale, capture = httpScreenshot, peek) {
155692
- if (requestedRotation !== void 0 || device.platform !== "android") {
155693
- return capture(api, requestedRotation, signal, scale);
155991
+ if (requestedRotation !== void 0) return capture(api, requestedRotation, signal, scale);
155992
+ if (isIosSimulator(device)) {
155993
+ if (inNativeCoordinates()) return capture(api, void 0, signal, scale);
155994
+ return captureIosUpright(api, device, signal, scale, capture);
155694
155995
  }
155996
+ if (device.platform !== "android") return capture(api, void 0, signal, scale);
155695
155997
  const surface = await readAndroidSurfaceRotation(device.id, peek);
155696
155998
  const rotation = captureRotationForSurface(surface);
155697
155999
  if (!rotation) return capture(api, void 0, signal, scale);
@@ -155704,6 +156006,22 @@ async function captureScreenshotUpright(api, device, requestedRotation, signal,
155704
156006
  }
155705
156007
  return result;
155706
156008
  }
156009
+ async function captureIosUpright(api, device, signal, scale, capture) {
156010
+ const read = await readUiOrientation(device.id);
156011
+ if (read.orientation === void 0) {
156012
+ const result2 = await capture(api, void 0, signal, scale);
156013
+ return read.unknownReason === void 0 ? result2 : { ...result2, note: unknownOrientationNote(read, "this screenshot is in") };
156014
+ }
156015
+ const rotation = uprightCaptureRotation(read.orientation);
156016
+ if (!rotation) return capture(api, void 0, signal, scale);
156017
+ const result = await capture(api, rotation, signal, scale);
156018
+ if (!captureLooksUpright(rotation, await readPngSize2(result.path))) {
156019
+ console.warn(
156020
+ `[screenshot] ${device.id}: requested ${rotation} for interface orientation ${read.orientation}, but the capture came back with the opposite aspect. simulator-server's rotation handling may have changed.`
156021
+ );
156022
+ }
156023
+ return result;
156024
+ }
155707
156025
 
155708
156026
  // ../tool-server/src/utils/android-devtools-rotation-peek.ts
155709
156027
  init_src2();
@@ -155916,7 +156234,7 @@ var zodSchema17 = external_exports.object({
155916
156234
  "Target device id from `list-devices` (iOS UDID, Android serial, Apple TV UDID, Vega serial, <flag:harmonyos>HarmonyOS id, </flag:harmonyos><flag:macos-apps>Mac app id, </flag:macos-apps>or Chromium id)."
155917
156235
  ),
155918
156236
  rotation: external_exports.enum(["Portrait", "LandscapeLeft", "LandscapeRight", "PortraitUpsideDown"]).optional().describe(
155919
- "Orientation override for the screenshot (on Chromium it rotates the captured image). On Android the capture already follows the device's rotation. <flag:harmonyos>Rejected on HarmonyOS, which captures the display in its current orientation and has no override. </flag:harmonyos>Ignored on physical iPhones."
156237
+ "Orientation override for the screenshot (on Chromium it rotates the captured image). Rarely needed: on Android and iOS simulators the capture already follows the UI's orientation, the space describe frames and gesture coordinates use, and an override can make the image disagree with them. <flag:harmonyos>Rejected on HarmonyOS, which captures the display in its current orientation and has no override. </flag:harmonyos>Ignored on physical iPhones."
155920
156238
  ),
155921
156239
  scale: external_exports.number().min(0.01).max(1).optional().describe(
155922
156240
  "Scale factor. Defaults to ARGENT_SCREENSHOT_SCALE env var, or 0.25 if unset for iOS/Android<flag:harmonyos>/HarmonyOS</flag:harmonyos>. On a local Apple TV simulator, an Android TV or Vega, with neither set, the capture is downscaled to a 576 px long side (0.15 of a 4K capture). On Chromium the default is 1.0 (no downscale); pass <1 to opt in. Downscaling on Chromium requires the optional `sharp` dependency.<flag:macos-apps> On a Mac app the default is one pixel per window point, downscaled to a 768 px long side for a larger window.</flag:macos-apps>"
@@ -155968,8 +156286,8 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
155968
156286
  });
155969
156287
  const requested = requestedGeometry(params);
155970
156288
  const dropped = (captured.droppedFeatures ?? []).filter((f) => requested.includes(f));
155971
- const note = chromiumDropNote(dropped, captured.dropReason);
155972
- return { image: image2, ...note ? { [RESULT_NOTE_KEY]: note } : {} };
156289
+ const note2 = chromiumDropNote(dropped, captured.dropReason);
156290
+ return { image: image2, ...note2 ? { [RESULT_NOTE_KEY]: note2 } : {} };
155973
156291
  }
155974
156292
  if (device.platform === "macos") {
155975
156293
  const app = await resolveMacosApp(registry2, device, "screenshot");
@@ -156026,7 +156344,7 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
156026
156344
  params.scale === void 0 && device.platform === "android" ? androidTvDefaultScale(device.id, apiReady) : void 0
156027
156345
  ]);
156028
156346
  const panel = await resolveCapturePanel(api);
156029
- const { path: capturedPath } = await captureScreenshotUpright(
156347
+ const { path: capturedPath, note: orientationNote } = await captureScreenshotUpright(
156030
156348
  api,
156031
156349
  device,
156032
156350
  params.rotation,
@@ -156040,9 +156358,10 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
156040
156358
  kind: "screenshot",
156041
156359
  mimeType: "image/png"
156042
156360
  });
156361
+ const note = [panel?.note, orientationNote].filter((n) => n !== void 0).join(" ");
156043
156362
  return {
156044
156363
  image,
156045
- ...panel ? { [RESULT_NOTE_KEY]: panel.note } : {},
156364
+ ...note ? { [RESULT_NOTE_KEY]: note } : {},
156046
156365
  ...panel?.warning !== void 0 ? { warning: panel.warning } : {}
156047
156366
  };
156048
156367
  }
@@ -158548,7 +158867,7 @@ async function prepareHostWindowShake(target) {
158548
158867
  if (deviceSet !== null) return inert;
158549
158868
  const needles = target.name ? [target.name] : [];
158550
158869
  const script = animationScript(needles);
158551
- let inFlight3 = null;
158870
+ let inFlight4 = null;
158552
158871
  let dead = false;
158553
158872
  let warned2 = false;
158554
158873
  const warnOnce2 = (detail) => {
@@ -158558,7 +158877,7 @@ async function prepareHostWindowShake(target) {
158558
158877
  };
158559
158878
  return {
158560
158879
  begin() {
158561
- if (dead || inFlight3 !== null) return;
158880
+ if (dead || inFlight4 !== null) return;
158562
158881
  let run2;
158563
158882
  try {
158564
158883
  run2 = runOsascript(script);
@@ -158567,9 +158886,9 @@ async function prepareHostWindowShake(target) {
158567
158886
  warnOnce2(err instanceof Error ? err.message : String(err));
158568
158887
  return;
158569
158888
  }
158570
- inFlight3 = run2.then(
158889
+ inFlight4 = run2.then(
158571
158890
  () => {
158572
- inFlight3 = null;
158891
+ inFlight4 = null;
158573
158892
  },
158574
158893
  async (err) => {
158575
158894
  dead = true;
@@ -158578,12 +158897,12 @@ async function prepareHostWindowShake(target) {
158578
158897
  await restoreOriginAfterKill(needles, failure2.rawStderr);
158579
158898
  }
158580
158899
  warnOnce2(err instanceof Error ? err.message : String(err));
158581
- inFlight3 = null;
158900
+ inFlight4 = null;
158582
158901
  }
158583
158902
  );
158584
158903
  },
158585
158904
  settle() {
158586
- return inFlight3 ?? Promise.resolve();
158905
+ return inFlight4 ?? Promise.resolve();
158587
158906
  }
158588
158907
  };
158589
158908
  } catch (err) {
@@ -159730,6 +160049,36 @@ Use when you need to verify connectivity before using other debugger tools. Neve
159730
160049
  // ../tool-server/src/tools/debugger/debugger-evaluate.ts
159731
160050
  init_zod();
159732
160051
  init_src2();
160052
+
160053
+ // ../tool-server/src/utils/debugger/scripts/guard-module-errors.ts
160054
+ function guardModuleLoadErrors(expression) {
160055
+ return `(function(source) {
160056
+ var g = typeof globalThis !== 'undefined' ? globalThis : this;
160057
+ var EU = g.ErrorUtils;
160058
+ if (!EU || typeof EU.reportFatalError !== 'function') return (0, eval)(source);
160059
+ var report = EU.reportFatalError;
160060
+ var fatal = [];
160061
+ var running = true;
160062
+ var record = function() {
160063
+ if (!running) return report.apply(this, arguments);
160064
+ fatal.push(arguments[0]);
160065
+ };
160066
+ EU.reportFatalError = record;
160067
+ var value;
160068
+ try {
160069
+ value = (0, eval)(source);
160070
+ } catch (e) {
160071
+ if (!fatal.length) throw e;
160072
+ } finally {
160073
+ running = false;
160074
+ if (EU.reportFatalError === record) EU.reportFatalError = report;
160075
+ }
160076
+ if (fatal.length) throw fatal[0];
160077
+ return value;
160078
+ })(${JSON.stringify(expression)})`;
160079
+ }
160080
+
160081
+ // ../tool-server/src/tools/debugger/debugger-evaluate.ts
159733
160082
  var zodSchema33 = external_exports.object({
159734
160083
  port: metroPortField,
159735
160084
  device_id: external_exports.string().describe(
@@ -159740,7 +160089,7 @@ var zodSchema33 = external_exports.object({
159740
160089
  var debuggerEvaluateTool = {
159741
160090
  id: "debugger-evaluate",
159742
160091
  description: `Execute arbitrary JavaScript in the app's JS runtime via CDP: Hermes on iOS / Android / Vega, V8 on Chromium.
159743
- Returns the result serialized by value as JSON, with deviceName, appName, and logicalDeviceId. Use when you need to read app state, including localStorage and sessionStorage on Chromium, call app functions, or test logic at runtime. Cyclic objects, which many RN runtime values are (fiber nodes, navigation refs, global), fail with a serialization error. Fails if the expression throws or the runtime is not connected.`,
160092
+ Returns the result serialized by value as JSON, with deviceName, appName, and logicalDeviceId. Use when you need to read app state, including localStorage and sessionStorage on Chromium, call app functions, or test logic at runtime. Cyclic objects, which many RN runtime values are (fiber nodes, navigation refs, global), fail with a serialization error. Fails if the expression throws or the runtime is not connected. On React Native, a module that fails to load while the expression runs (e.g. a lazy react-native export whose native module the app lacks) fails the call with that module's error instead of opening the app's red box.`,
159744
160093
  zodSchema: zodSchema33,
159745
160094
  searchHint: "javascript js eval expression runtime app state localstorage sessionstorage web storage",
159746
160095
  interaction: {
@@ -159756,7 +160105,8 @@ Returns the result serialized by value as JSON, with deviceName, appName, and lo
159756
160105
  const api = services.debugger;
159757
160106
  let result;
159758
160107
  try {
159759
- result = await api.cdp.evaluate(params.expression);
160108
+ const expression = isChromiumDebuggerTarget(params.device_id) ? params.expression : guardModuleLoadErrors(params.expression);
160109
+ result = await api.cdp.evaluate(expression);
159760
160110
  } catch (err) {
159761
160111
  if (err instanceof Error && getFailureSignal(err)?.error_code === FAILURE_CODES.DEBUGGER_CDP_RUNTIME_EXCEPTION) {
159762
160112
  throw new FailureError(
@@ -160271,7 +160621,6 @@ function makeComponentTreeScript(opts) {
160271
160621
  }
160272
160622
 
160273
160623
  // ../tool-server/src/tools/debugger/debugger-component-tree.ts
160274
- init_device_info();
160275
160624
  function rectsOverlap(a, b) {
160276
160625
  return Math.abs(a.x - b.x) < 8 && Math.abs(a.y - b.y) < 8 && Math.abs(a.w - b.w) < 8 && Math.abs(a.h - b.h) < 8;
160277
160626
  }
@@ -160511,49 +160860,16 @@ function buildTextTree(data, opts) {
160511
160860
  }
160512
160861
  }
160513
160862
  const lines = [];
160514
- const turn = opts.uiOrientation && opts.uiOrientation !== "unknown" && opts.uiOrientation !== "ambiguous" && opts.uiOrientation !== "mismatched" ? opts.uiOrientation : void 0;
160515
- if (canNormalize) {
160516
- lines.push(`Screen: ${screenW}x${screenH}`);
160517
- if (opts.uiOrientation === "mismatched") {
160518
- lines.push(
160519
- "Note: The udid is not the UDID of the simulator that shows this app. Thus, the tool did not use the udid. If the UI is landscape, the tap points are not correct. The describe tool gives correct tap points. This tool also gives correct tap points with the UDID of the simulator that shows this app."
160520
- );
160521
- } else if (turn && turn !== "portrait") {
160522
- lines.push(
160523
- `The UI is ${turn} on the screen. The tap points are on the screen's axes, which the gesture tools use.`
160524
- );
160525
- } else if (opts.uiOrientation === "ambiguous" && screenW > screenH) {
160526
- lines.push(
160527
- "Note: the UI is landscape, and two booted simulators have this device's name, so its orientation could not be read. The tap points are on the UI's axes, so a tap can miss. Use describe for tap points, or call again with the udid of the simulator that shows this app."
160528
- );
160529
- } else if (opts.uiOrientation === "unknown" && screenW > screenH) {
160530
- lines.push(
160531
- "Note: the UI is landscape, and its orientation could not be read. The tap points are on the UI's axes, so a tap can miss. Use describe for tap points."
160532
- );
160533
- }
160534
- if (opts.readInsteadOfUdid) {
160535
- lines.push(
160536
- `Note: the udid is not the UDID of the simulator that shows this app. The tool used ${opts.readInsteadOfUdid}, the UDID of that simulator.`
160537
- );
160538
- }
160539
- if (opts.udidUnchecked && (screenW > screenH || turn !== void 0 && turn !== "portrait")) {
160540
- lines.push(
160541
- "Note: two booted simulators have this device's name, so the tool could not check that the udid is the simulator that shows this app. If it is another simulator, a tap can miss. Use describe for tap points."
160542
- );
160543
- }
160544
- lines.push("");
160545
- }
160863
+ if (canNormalize) lines.push(`Screen: ${screenW}x${screenH}`, "");
160546
160864
  function formatLabel2(c) {
160547
160865
  let label = c.name;
160548
160866
  const displayText = c.text ?? c.accLabel;
160549
160867
  if (displayText) label += ` "${displayText}"`;
160550
160868
  if (c.testID) label += ` [testID=${c.testID}]`;
160551
160869
  if (c.rect && canNormalize) {
160552
- const tap = uiPointToNative(
160553
- { x: (c.rect.x + c.rect.w / 2) / screenW, y: (c.rect.y + c.rect.h / 2) / screenH },
160554
- turn
160555
- );
160556
- label += ` (tap: ${tap.x.toFixed(2)},${tap.y.toFixed(2)})`;
160870
+ const tapX = (c.rect.x + c.rect.w / 2) / screenW;
160871
+ const tapY = (c.rect.y + c.rect.h / 2) / screenH;
160872
+ label += ` (tap: ${tapX.toFixed(2)},${tapY.toFixed(2)})`;
160557
160873
  }
160558
160874
  return label;
160559
160875
  }
@@ -160635,115 +160951,11 @@ function buildTextTree(data, opts) {
160635
160951
  }
160636
160952
  return lines.join("\n");
160637
160953
  }
160638
- var ORIENTATION_READ_TIMEOUT_MS = 3e3;
160639
- async function debuggedBundleId(api, appName) {
160640
- const named = api.listConnectedBundleIds().filter((id) => appName === id || appName.startsWith(`${id} `));
160641
- if (named.length === 1) return named[0];
160642
- if (BUNDLE_ID_NAMED_TARGET.test(appName)) return void 0;
160643
- return (await resolveNativeTargetApp(api)).bundleId;
160644
- }
160645
- var BUNDLE_ID_NAMED_TARGET = /^[\w-]+(\.[\w-]+)+( \(|$)/;
160646
- var AMBIGUOUS_SIMULATOR = "ambiguous-simulator";
160647
- var MISMATCHED_UDID = "mismatched-udid";
160648
- var UNLISTED_UDID = "unlisted-udid";
160649
- async function iosSimulatorOf(app) {
160650
- if (!app.udid) {
160651
- const session2 = await iosSimulatorOfSession(app);
160652
- return session2 === AMBIGUOUS_SIMULATOR || !session2 ? session2 : { device: session2 };
160653
- }
160654
- const named = resolveDevice(app.udid);
160655
- const own2 = resolveDevice(canonicalDeviceId(app.deviceId) ?? app.deviceId);
160656
- if (isIosSimulator(own2)) {
160657
- if (own2.id === named.id) return { device: own2 };
160658
- if (isIosSimulator(named)) {
160659
- const [listed2, ownListed] = await Promise.all([
160660
- listedAs(named, app.deviceName),
160661
- listedAs(own2, app.deviceName)
160662
- ]);
160663
- if (listed2 === "booted" && ownListed !== "booted") return { device: named };
160664
- }
160665
- return { device: own2, readInsteadOfUdid: own2.id };
160666
- }
160667
- const [listed, session] = await Promise.all([
160668
- isIosSimulator(named) ? listedAs(named, app.deviceName) : void 0,
160669
- iosSimulatorOfSession(app)
160670
- ]);
160671
- if (listed === "booted" || listed === "twin") {
160672
- const sole = session === void 0 || session !== AMBIGUOUS_SIMULATOR && session.id === named.id;
160673
- return listed === "booted" && sole ? { device: named } : { device: named, udidUnchecked: true };
160674
- }
160675
- if (session === AMBIGUOUS_SIMULATOR) return MISMATCHED_UDID;
160676
- if (session) {
160677
- return session.id === named.id ? { device: session } : { device: session, readInsteadOfUdid: session.id };
160678
- }
160679
- return listed === "unlisted" ? UNLISTED_UDID : void 0;
160680
- }
160681
- async function listedAs(device, name) {
160682
- if (device.platform !== "ios-remote") {
160683
- const sim2 = await findIosSimulator(device.id);
160684
- if (!sim2) return "unlisted";
160685
- return sim2.state === "Booted" && sim2.name === name ? "booted" : "other";
160686
- }
160687
- const listing = Object.values(
160688
- (await simctlListDevices({ timeoutMs: ORIENTATION_READ_TIMEOUT_MS }).catch(() => ({
160689
- devices: {}
160690
- }))).devices
160691
- ).flat();
160692
- const sim = listing.find((d) => d.udid === stripRemotePrefix(device.id));
160693
- if (!sim) return "unlisted";
160694
- if (sim.state !== "Booted" || sim.name !== name) return "other";
160695
- return listing.some((d) => d !== sim && d.state === "Booted" && d.name === name) ? "twin" : "booted";
160696
- }
160697
- async function iosSimulatorOfSession(app) {
160698
- const device = resolveDevice(canonicalDeviceId(app.deviceId) ?? app.deviceId);
160699
- if (isIosSimulator(device)) return device;
160700
- const logicalKeyed = app.deviceId === app.logicalDeviceId || isLogicalKeyedDevice(app.deviceId);
160701
- if (!logicalKeyed) return void 0;
160702
- const named = (await listIosSimulators()).filter(
160703
- (sim) => sim.state === "Booted" && sim.runtimeKind === "mobile" && sim.name === app.deviceName
160704
- );
160705
- if (named.length === 1) return resolveDevice(named[0].udid);
160706
- return named.length > 1 ? AMBIGUOUS_SIMULATOR : void 0;
160707
- }
160708
- async function readTapAxes(registry2, app) {
160709
- const read = (async () => {
160710
- const pick2 = await iosSimulatorOf(app);
160711
- if (pick2 === void 0) return {};
160712
- if (pick2 === AMBIGUOUS_SIMULATOR) return { uiOrientation: "ambiguous" };
160713
- if (pick2 === MISMATCHED_UDID) return { uiOrientation: "mismatched" };
160714
- if (pick2 === UNLISTED_UDID) return { uiOrientation: "unknown" };
160715
- const { device, ...udid } = pick2;
160716
- const ref = nativeDevtoolsRef(device);
160717
- const api = await registry2.resolveService(ref.urn, ref.options);
160718
- const bundleId = await debuggedBundleId(api, app.appName);
160719
- if (!bundleId) return { uiOrientation: "unknown", ...udid };
160720
- const raw = await api.queryViewHierarchy(bundleId, "ViewHierarchy.getFullHierarchy", {
160721
- fields: ["className"],
160722
- maxDepth: 1
160723
- });
160724
- return {
160725
- uiOrientation: asUiOrientation(raw?.screen?.interfaceOrientation) ?? "unknown",
160726
- ...udid
160727
- };
160728
- })().catch(() => ({ uiOrientation: "unknown" }));
160729
- let timer;
160730
- const timeout = new Promise((resolve19) => {
160731
- timer = setTimeout(() => resolve19({ uiOrientation: "unknown" }), ORIENTATION_READ_TIMEOUT_MS);
160732
- });
160733
- try {
160734
- return await Promise.race([read, timeout]);
160735
- } finally {
160736
- clearTimeout(timer);
160737
- }
160738
- }
160739
160954
  var zodSchema35 = external_exports.object({
160740
160955
  port: metroPortField,
160741
160956
  device_id: external_exports.string().describe(
160742
160957
  "Device id from list-devices: the SAME id you passed to debugger-connect (iOS simulator UDID or Android serial)."
160743
160958
  ),
160744
- udid: external_exports.string().optional().describe(
160745
- "iOS simulator UDID from list-devices. Pass it when device_id is a logicalDeviceId (two or more devices share one Metro), so that the tap coordinates of a landscape UI are on the screen's axes. Give the UDID of the simulator that shows the app."
160746
- ),
160747
160959
  onScreenOnly: external_exports.boolean().default(true).describe(
160748
160960
  "When true, only components visible on screen are returned. Set to false to include all mounted components, including those scrolled off-screen, e.g. to understand the full page structure."
160749
160961
  ),
@@ -160754,7 +160966,7 @@ var zodSchema35 = external_exports.object({
160754
160966
  "When true, appends a summary of all filtered components: total fiber count and skip counts by component name and by filter."
160755
160967
  )
160756
160968
  });
160757
- function createDebuggerComponentTreeTool(registry2) {
160969
+ function createDebuggerComponentTreeTool() {
160758
160970
  return {
160759
160971
  id: "debugger-component-tree",
160760
160972
  description: `Fetch the current screen of a running React Native app as a compact tree of React components.
@@ -160767,8 +160979,6 @@ Use when you need what describe does not show: a testID for a selector (on Andro
160767
160979
  the testID of a view that has no label and is not tappable), or the component names and nesting
160768
160980
  behind the screen before editing code. To find what to tap, use describe.
160769
160981
 
160770
- On an iOS simulator with a landscape UI (a rotated device, or an unfolded foldable), the tap
160771
- coordinates are on the screen's axes, which the gesture tools use.
160772
160982
  Returns a compact text tree; call again after navigation. Fails if the Metro debugger is not connected.`,
160773
160983
  zodSchema: zodSchema35,
160774
160984
  searchHint: "react native component tree testID testIDs selector component names hierarchy",
@@ -160786,13 +160996,6 @@ Returns a compact text tree; call again after navigation. Fails if the Metro deb
160786
160996
  }),
160787
160997
  async execute(services, params) {
160788
160998
  const api = services.debugger;
160789
- const tapAxes = readTapAxes(registry2, {
160790
- deviceId: params.device_id,
160791
- udid: params.udid,
160792
- appName: api.appName,
160793
- deviceName: api.deviceName,
160794
- logicalDeviceId: api.logicalDeviceId
160795
- });
160796
160999
  const requestId = crypto4.randomUUID();
160797
161000
  const script = makeComponentTreeScript({
160798
161001
  includeSkipped: params.includeSkipped,
@@ -160812,8 +161015,7 @@ Returns a compact text tree; call again after navigation. Fails if the Metro deb
160812
161015
  const tree = buildTextTree(parsed2, {
160813
161016
  onScreenOnly: params.onScreenOnly,
160814
161017
  maxNodes: params.maxNodes,
160815
- includeSkipped: params.includeSkipped,
160816
- ...await tapAxes
161018
+ includeSkipped: params.includeSkipped
160817
161019
  });
160818
161020
  const deviceLine = [
160819
161021
  `device: ${api.deviceName}`,
@@ -162456,6 +162658,8 @@ function markHidden(node2, clip3) {
162456
162658
  for (const child of node2.children) markHidden(child, inner);
162457
162659
  }
162458
162660
  function adaptAxTree(response) {
162661
+ const orientation = response.interfaceOrientation;
162662
+ const turn = (frame2) => frame2 && isTurned(orientation) ? nativeFrameToUi(frame2, orientation) : frame2;
162459
162663
  const byIndex = /* @__PURE__ */ new Map();
162460
162664
  const roots = [];
162461
162665
  let keyboardVisible = false;
@@ -162470,7 +162674,7 @@ function adaptAxTree(response) {
162470
162674
  value: raw.hintShowing ? void 0 : raw.value,
162471
162675
  identifier: raw.identifier,
162472
162676
  roleDescription: raw.roleDescription,
162473
- frame: raw.frame,
162677
+ frame: turn(raw.frame),
162474
162678
  children: []
162475
162679
  };
162476
162680
  if (raw.elementType !== void 0)
@@ -162497,7 +162701,7 @@ function adaptAxTree(response) {
162497
162701
  return {
162498
162702
  schemaVersion: 1,
162499
162703
  source: "ax-service",
162500
- screen: response.screenFrame,
162704
+ screen: response.screenFrame && uiScreenSize(response.screenFrame, orientation),
162501
162705
  roots,
162502
162706
  truncated: response.truncated,
162503
162707
  alertVisible: response.alertVisible,
@@ -162510,7 +162714,9 @@ function adaptAxTree(response) {
162510
162714
  async function readIosUiTree(registry2, device) {
162511
162715
  const ref = axServiceRef(device);
162512
162716
  const ax = await registry2.resolveService(ref.urn, ref.options);
162513
- return adaptAxTree(await ax.tree());
162717
+ const response = await ax.tree();
162718
+ noteUiOrientation(device.id, response.interfaceOrientation, response.screenFrame);
162719
+ return adaptAxTree(response);
162514
162720
  }
162515
162721
 
162516
162722
  // ../tool-server/src/tools/flows/flow-android-tree.ts
@@ -174536,10 +174742,10 @@ async function disablePointer(api) {
174536
174742
  });
174537
174743
  }
174538
174744
  function startPanelFollow(api, follow, child) {
174539
- let inFlight3 = false;
174745
+ let inFlight4 = false;
174540
174746
  api.panelPollTimer = setInterval(() => {
174541
- if (inFlight3 || api.captureProcess !== child) return;
174542
- inFlight3 = true;
174747
+ if (inFlight4 || api.captureProcess !== child) return;
174748
+ inFlight4 = true;
174543
174749
  void (async () => {
174544
174750
  try {
174545
174751
  const live = await follow.resolveLivePanel();
@@ -174575,7 +174781,7 @@ function startPanelFollow(api, follow, child) {
174575
174781
  `
174576
174782
  );
174577
174783
  } finally {
174578
- inFlight3 = false;
174784
+ inFlight4 = false;
174579
174785
  }
174580
174786
  })();
174581
174787
  }, follow.pollMs ?? PANEL_POLL_MS);
@@ -178074,8 +178280,8 @@ function flowPathIn(flowsDir, name) {
178074
178280
  }
178075
178281
  async function resolveFlowKey(projectRoot, name) {
178076
178282
  const spelled = getFlowPath(projectRoot, name);
178077
- const inFlight3 = keyResolutions.get(spelled);
178078
- if (inFlight3) return inFlight3;
178283
+ const inFlight4 = keyResolutions.get(spelled);
178284
+ if (inFlight4) return inFlight4;
178079
178285
  const resolving = canonicalFlowPath2(spelled).finally(() => {
178080
178286
  if (keyResolutions.get(spelled) === resolving) keyResolutions.delete(spelled);
178081
178287
  });
@@ -179977,7 +180183,11 @@ function fromYamlStep(raw, blockDepth = 0) {
179977
180183
  }
179978
180184
  return badEntry(raw, "unrecognized step kind");
179979
180185
  }
179980
- var FLOW_FILE_VERSION = 1;
180186
+ var FLOW_FILE_VERSION = 2;
180187
+ var olderFormatVersions = /* @__PURE__ */ new WeakMap();
180188
+ function flowFormatVersion(flow) {
180189
+ return olderFormatVersions.get(flow) ?? FLOW_FILE_VERSION;
180190
+ }
179981
180191
  function requiresToYaml({ platform, runtimeKind }) {
179982
180192
  return {
179983
180193
  ...platform ? { platform: platform.length === 1 ? platform[0] : platform } : {},
@@ -180081,6 +180291,7 @@ function parseFlow(content) {
180081
180291
  steps
180082
180292
  };
180083
180293
  validateFlow(flow);
180294
+ if (version3 < FLOW_FILE_VERSION) olderFormatVersions.set(flow, version3);
180084
180295
  return flow;
180085
180296
  }
180086
180297
  var flowWriteSeq = 0;
@@ -180457,7 +180668,6 @@ var path59 = __toESM(require("node:path"));
180457
180668
  init_src2();
180458
180669
 
180459
180670
  // ../tool-server/src/tools/flows/flow-actions.ts
180460
- init_device_info();
180461
180671
  init_capability();
180462
180672
 
180463
180673
  // ../tool-server/src/tools/flows/flow-device.ts
@@ -180888,10 +181098,10 @@ function adaptFullHierarchy(raw, quotedLabel) {
180888
181098
  });
180889
181099
  if (!(screenW > 0 && screenH > 0)) return { tree };
180890
181100
  const uiOrientation = asUiOrientation(reportedScreen?.interfaceOrientation);
181101
+ if (!isTurned(uiOrientation)) return { tree, screen: { width: screenW, height: screenH } };
180891
181102
  return {
180892
- tree,
180893
- screen: { width: screenW, height: screenH },
180894
- ...uiOrientation ? { uiOrientation } : {}
181103
+ tree: nativeTreeToUi(tree, uiOrientation),
181104
+ screen: uiScreenSize({ width: screenW, height: screenH }, uiOrientation)
180895
181105
  };
180896
181106
  }
180897
181107
  var FLOW_TREE_MAX_DEPTH = 100;
@@ -181063,14 +181273,13 @@ async function queryFullHierarchyTree(registry2, device, target) {
181063
181273
  `getFullHierarchy returned no windows for ${bundleId} - it has no window attached to read (backgrounded, or its first window not attached yet), so e2e tests cannot resolve selectors against its view hierarchy; foreground or relaunch it, and if that bundle id is a com.apple.* system process the read resolved to a background system app rather than the app under test, so give this e2e test a \`launch\` step to pin reads to the right app`
181064
181274
  );
181065
181275
  }
181066
- const { tree, screen, uiOrientation } = adaptFullHierarchy(rawResult);
181276
+ const { tree, screen } = adaptFullHierarchy(rawResult);
181067
181277
  const quotableTree = secretTypedOn(device.id) ? adaptFullHierarchy(rawResult, (label) => redactTypedSecrets(device.id, label)).tree : void 0;
181068
181278
  return {
181069
181279
  tree,
181070
181280
  ...quotableTree ? { quotableTree } : {},
181071
181281
  source: "native-devtools",
181072
- ...screen ? { screen } : {},
181073
- ...uiOrientation ? { uiOrientation } : {}
181282
+ ...screen ? { screen } : {}
181074
181283
  };
181075
181284
  }
181076
181285
  function errMsg3(err) {
@@ -181525,25 +181734,22 @@ function selectorAlternatives(sel) {
181525
181734
  }
181526
181735
  return alts;
181527
181736
  }
181528
- function flowFindAll(tree, sel, orientation) {
181737
+ function flowFindAll(tree, sel) {
181529
181738
  let fallback = [];
181530
181739
  for (const s of selectorAlternatives(sel)) {
181531
- const matches2 = findAll(tree, s, orientation);
181740
+ const matches2 = findAll(tree, s);
181532
181741
  if (matches2.some(isVisible)) return matches2;
181533
181742
  if (fallback.length === 0) fallback = matches2;
181534
181743
  }
181535
181744
  return fallback;
181536
181745
  }
181537
- function flowSelectorToFrame(tree, sel, orientation) {
181746
+ function flowSelectorToFrame(tree, sel) {
181538
181747
  for (const s of selectorAlternatives(sel)) {
181539
- const frame2 = selectorToFrame(tree, s, orientation);
181748
+ const frame2 = selectorToFrame(tree, s);
181540
181749
  if (frame2) return frame2;
181541
181750
  }
181542
181751
  return void 0;
181543
181752
  }
181544
- function readingOrientation(env) {
181545
- return env.lastRead?.uiOrientation;
181546
- }
181547
181753
  function provenTreeOutage(env) {
181548
181754
  const proven = env.treeOutage?.proven;
181549
181755
  return proven && proven.deviceId === env.device.id ? proven.error : void 0;
@@ -181551,7 +181757,6 @@ function provenTreeOutage(env) {
181551
181757
  function readFlowTree(env) {
181552
181758
  return fetchFlowTree(env.registry, env.device, env.treeTarget).then((data) => {
181553
181759
  if (env.treeOutage) env.treeOutage.proven = void 0;
181554
- if (env.lastRead) env.lastRead.uiOrientation = data.uiOrientation;
181555
181760
  return data;
181556
181761
  });
181557
181762
  }
@@ -181600,10 +181805,7 @@ async function waitForFrames(env, selectors) {
181600
181805
  if (env.signal?.aborted) return "aborted";
181601
181806
  const tree = await settleTree(env);
181602
181807
  if (tree) {
181603
- const orientation = readingOrientation(env);
181604
- const frames = selectors.map(
181605
- (s) => s ? flowSelectorToFrame(tree, s, orientation) : void 0
181606
- );
181808
+ const frames = selectors.map((s) => s ? flowSelectorToFrame(tree, s) : void 0);
181607
181809
  const missing = pending.find(({ i }) => frames[i] === void 0);
181608
181810
  if (!missing) return frames;
181609
181811
  unresolved = missing.selector;
@@ -181647,9 +181849,9 @@ async function waitForFocus(env, into, tappedFrame) {
181647
181849
  for (; ; ) {
181648
181850
  if (env.signal?.aborted) return;
181649
181851
  try {
181650
- const { tree, source, uiOrientation } = await readFlowTree(env);
181852
+ const { tree, source } = await readFlowTree(env);
181651
181853
  if (!FOCUS_REPORTING_SOURCES.has(source)) return;
181652
- const target = flowSelectorToFrame(tree, into, uiOrientation) ?? tappedFrame;
181854
+ const target = flowSelectorToFrame(tree, into) ?? tappedFrame;
181653
181855
  if (collectFocused(tree, []).some((n) => framesOverlap(n.frame, target))) return;
181654
181856
  } catch {
181655
181857
  }
@@ -181706,14 +181908,12 @@ async function scrollToVisible(env, target, direction, within) {
181706
181908
  if (env.signal?.aborted) return { aborted: true };
181707
181909
  const tree = await settleTree(env);
181708
181910
  if (!tree) return { aborted: true };
181709
- const orientation = readingOrientation(env);
181710
- const axisDirection = nativeDirection(direction, orientation);
181711
- const region = within ? flowSelectorToFrame(tree, within, orientation) : FULL_SCREEN2;
181911
+ const region = within ? flowSelectorToFrame(tree, within) : FULL_SCREEN2;
181712
181912
  if (!region) {
181713
181913
  return { reason: `scroll container ${describeSelector(within)} is not visible` };
181714
181914
  }
181715
- const frame2 = flowSelectorToFrame(tree, target, orientation);
181716
- if (frame2 && axisFullyInside(frame2, axisDirection, region)) {
181915
+ const frame2 = flowSelectorToFrame(tree, target);
181916
+ if (frame2 && axisFullyInside(frame2, direction, region)) {
181717
181917
  return { frame: frame2, ...warnedBy(warning) };
181718
181918
  }
181719
181919
  const scope = within ? [region] : anchorScrollFrames(tree, getDescribeTapPoint(region));
@@ -181728,7 +181928,7 @@ async function scrollToVisible(env, target, direction, within) {
181728
181928
  }
181729
181929
  prevFp = fp;
181730
181930
  try {
181731
- warning ??= await scrollIncrement(env, axisDirection, region);
181931
+ warning ??= await scrollIncrement(env, direction, region);
181732
181932
  } catch (err) {
181733
181933
  if (!(err instanceof Error && NO_SCROLLABLE_VIEW.test(err.message))) throw err;
181734
181934
  if (frame2) return { frame: frame2, ...warnedBy(warning) };
@@ -181843,9 +182043,6 @@ function warnedBy(...warnings) {
181843
182043
  const text = warnings.filter((w) => w !== void 0).join(" ");
181844
182044
  return text.length > 0 ? { warning: text } : {};
181845
182045
  }
181846
- function unreadOrientationNote(orientation) {
181847
- return orientation ? `The direction was turned for the UI orientation an earlier read reported (${orientation}); if the UI has turned since, the finger went another way.` : `No read reported the UI's orientation, so the direction was sent in the screen's portrait space; on a landscape UI the finger went sideways.`;
181848
- }
181849
182046
  function unsettledGestureWarning(err) {
181850
182047
  const reason2 = err instanceof Error ? err.message : String(err);
181851
182048
  return `dispatched without settling the screen first: the UI tree could not be read (${reason2}), so there was no way to tell whether anything was moving. The gesture went out against whatever was in flight, and one aimed at a moving element can miss it entirely - this step passing says it was sent, not that it landed. Restore the tree source, or put an explicit \`wait:\` in front of gestures that follow a transition.`;
@@ -182048,17 +182245,13 @@ async function runSwipe(env, step) {
182048
182245
  if ("fail" in p) return p.fail;
182049
182246
  toPoint = p;
182050
182247
  }
182051
- const orientation = env.lastRead?.uiOrientation;
182052
- if (settle3.warning !== void 0 && step.direction && isIosSimulator(env.device)) {
182053
- settle3 = { ...settle3, warning: `${settle3.warning} ${unreadOrientationNote(orientation)}` };
182054
- }
182055
182248
  let start2;
182056
182249
  if (step.from) {
182057
182250
  const p = targetPointFromFrame(step.from, fromFrame);
182058
182251
  if ("fail" in p) return p.fail;
182059
182252
  start2 = p;
182060
182253
  } else if (step.direction) {
182061
- start2 = uiPointToNative(SWIPE_GEOMETRY[step.direction].start, orientation);
182254
+ start2 = { ...SWIPE_GEOMETRY[step.direction].start };
182062
182255
  } else {
182063
182256
  start2 = { x: 0.5, y: 0.5 };
182064
182257
  }
@@ -182071,16 +182264,10 @@ async function runSwipe(env, step) {
182071
182264
  let end;
182072
182265
  if (step.direction) {
182073
182266
  const g = SWIPE_GEOMETRY[step.direction];
182074
- const travelVector = uiVectorToNative(
182075
- g.axis === "x" ? { x: g.end - g.start.x, y: 0 } : { x: 0, y: g.end - g.start.y },
182076
- orientation
182077
- );
182078
- const axis = travelVector.x !== 0 ? "x" : "y";
182267
+ const travelVector = g.axis === "x" ? { x: g.end - g.start.x, y: 0 } : { x: 0, y: g.end - g.start.y };
182268
+ const axis = g.axis;
182079
182269
  const startOnTravelAxis = start2[axis];
182080
- const endOnTravelAxis = step.from ? clamp014(startOnTravelAxis + travelVector[axis]) : uiPointToNative(
182081
- g.axis === "x" ? { x: g.end, y: g.start.y } : { x: g.start.x, y: g.end },
182082
- orientation
182083
- )[axis];
182270
+ const endOnTravelAxis = step.from ? clamp014(startOnTravelAxis + travelVector[axis]) : g.end;
182084
182271
  end = axis === "x" ? { x: endOnTravelAxis, y: start2.y } : { x: start2.x, y: endOnTravelAxis };
182085
182272
  const travel2 = Math.abs(endOnTravelAxis - startOnTravelAxis);
182086
182273
  if (travel2 < SWIPE_MIN_TRAVEL) {
@@ -182198,7 +182385,7 @@ async function waitForCondition(env, step, timeoutMs) {
182198
182385
  if (env.signal?.aborted) return ABORTED_OUTCOME;
182199
182386
  try {
182200
182387
  const data = await readFlowTree(env);
182201
- lastMatches = flowFindAll(data.tree, step.selector, data.uiOrientation);
182388
+ lastMatches = flowFindAll(data.tree, step.selector);
182202
182389
  lastData = data;
182203
182390
  fetchError = void 0;
182204
182391
  everMatched ||= lastMatches.length > 0;
@@ -182211,7 +182398,6 @@ async function waitForCondition(env, step, timeoutMs) {
182211
182398
  step.expectedText,
182212
182399
  lastMatches,
182213
182400
  step.textMatch,
182214
- data.uiOrientation,
182215
182401
  env.device.platform === "macos"
182216
182402
  )) {
182217
182403
  return { ok: true };
@@ -182264,9 +182450,6 @@ async function waitForCondition(env, step, timeoutMs) {
182264
182450
  step.expectedText,
182265
182451
  step.textMatch,
182266
182452
  lastMatches,
182267
- // The read `lastMatches` came from is the last one that answered, and
182268
- // only a read that answers writes the orientation.
182269
- readingOrientation(env),
182270
182453
  env.device.platform === "macos",
182271
182454
  // The text of an element is the only part of a reason that comes off
182272
182455
  // the screen, where a field shows a typed secret.
@@ -182490,7 +182673,7 @@ async function waitForIdle(env, step) {
182490
182673
  warning: `the screen never held still for ${MIN_STILL_INTERVALS} consecutive ${IDLE_POLL_MS}ms intervals${stableFor > 0 ? ` spanning ${stableFor}ms` : ""} within ${timeoutMs}ms, and was moving again on the last one, so this step went ahead without waiting it out. Either something on it never stops (a video, a looping animation, a carousel, live-updating text) or the screen never finished loading. Look at what is moving, and make sure the next action is gated on a stable element rather than on stillness.` + blipNote
182491
182674
  };
182492
182675
  }
182493
- function assertReason(condition, selector, expectedText, textMatch, matches2, orientation, macos, quoted) {
182676
+ function assertReason(condition, selector, expectedText, textMatch, matches2, macos, quoted) {
182494
182677
  const sel = describeSelector(selector);
182495
182678
  switch (condition) {
182496
182679
  case "exists":
@@ -182500,7 +182683,7 @@ function assertReason(condition, selector, expectedText, textMatch, matches2, or
182500
182683
  case "hidden":
182501
182684
  return `an element matching ${sel} was still visible`;
182502
182685
  case "text": {
182503
- const first = textCheckTarget(matches2, orientation, macos);
182686
+ const first = textCheckTarget(matches2, macos);
182504
182687
  if (!first) return `no element matched selector ${sel}`;
182505
182688
  const wanted = describeTextExpectation(expectedText, textMatch, "infinitive");
182506
182689
  const shown = quoted(first, (node2) => macFieldText(node2, macos) ?? assertText(node2));
@@ -183343,13 +183526,13 @@ async function captureTapSelector(registry2, session, udid, point) {
183343
183526
  device,
183344
183527
  launched ? { bundleId: launched, pinned: false, probeAnswered: false } : void 0
183345
183528
  );
183346
- const { tree, uiOrientation } = data;
183529
+ const { tree } = data;
183347
183530
  const node2 = nodeAtPoint(tree, point);
183348
183531
  if (!node2) return { warning: "no element found under the tap; kept coordinates (brittle)" };
183349
183532
  const selector = deriveSelector(withoutTypedText(node2, data));
183350
183533
  if (!selector)
183351
183534
  return { warning: "tapped element has no stable text/id; kept coordinates (brittle)" };
183352
- const resolved = selectorToFrame(tree, selector, uiOrientation);
183535
+ const resolved = selectorToFrame(tree, selector);
183353
183536
  if (!resolved) {
183354
183537
  return {
183355
183538
  warning: `selector ${describeSelector(selector)} matches no element on this screen; kept coordinates (brittle)`
@@ -185595,6 +185778,67 @@ init_zod();
185595
185778
  var fs78 = __toESM(require("node:fs/promises"));
185596
185779
  var path64 = __toESM(require("node:path"));
185597
185780
  init_src2();
185781
+
185782
+ // ../tool-server/src/tools/flows/flow-legacy-points.ts
185783
+ init_device_info();
185784
+ async function uprightLegacyPoints(device, step) {
185785
+ if (!hasRawPoints(step) || !isIosSimulator(device)) return { step };
185786
+ const read = await readUiOrientation(device.id);
185787
+ if (read.orientation === void 0) {
185788
+ return read.unknownReason === void 0 ? { step } : { step, warning: unknownOrientationNote(read, "this step's points were sent in") };
185789
+ }
185790
+ if (!isTurned(read.orientation)) return { step };
185791
+ return { step: turnStep(step, read.orientation) };
185792
+ }
185793
+ function hasRawPoints(step) {
185794
+ switch (step.kind) {
185795
+ case "tap":
185796
+ case "long-press":
185797
+ return step.x !== void 0 && step.y !== void 0;
185798
+ case "swipe":
185799
+ return isPoint2(step.from) || isPoint2(step.to) || step.by !== void 0;
185800
+ default:
185801
+ return false;
185802
+ }
185803
+ }
185804
+ function isPoint2(target) {
185805
+ return target !== void 0 && "x" in target;
185806
+ }
185807
+ function turnStep(step, orientation) {
185808
+ const point = (p) => snapPoint(nativePointToUi(p, orientation));
185809
+ switch (step.kind) {
185810
+ case "tap":
185811
+ case "long-press":
185812
+ return { ...step, ...point({ x: step.x, y: step.y }) };
185813
+ case "swipe":
185814
+ return {
185815
+ ...step,
185816
+ ...isPoint2(step.from) ? { from: point(step.from) } : {},
185817
+ ...isPoint2(step.to) ? { to: point(step.to) } : {},
185818
+ ...step.by !== void 0 ? { by: turnDelta(step.by, orientation) } : {}
185819
+ };
185820
+ default:
185821
+ return step;
185822
+ }
185823
+ }
185824
+ function turnDelta(by, orientation) {
185825
+ const origin = nativePointToUi({ x: 0, y: 0 }, orientation);
185826
+ const end = nativePointToUi({ x: by.x ?? 0, y: by.y ?? 0 }, orientation);
185827
+ const dx = snap2(end.x - origin.x);
185828
+ const dy = snap2(end.y - origin.y);
185829
+ const swapped = orientation === "landscapeLeft" || orientation === "landscapeRight";
185830
+ const hasX = swapped ? by.y !== void 0 : by.x !== void 0;
185831
+ const hasY = swapped ? by.x !== void 0 : by.y !== void 0;
185832
+ return { ...hasX ? { x: dx } : {}, ...hasY ? { y: dy } : {} };
185833
+ }
185834
+ function snap2(n) {
185835
+ return Math.round(n * 1e9) / 1e9 + 0;
185836
+ }
185837
+ function snapPoint(p) {
185838
+ return { x: snap2(p.x), y: snap2(p.y) };
185839
+ }
185840
+
185841
+ // ../tool-server/src/tools/flows/flow-run.ts
185598
185842
  init_device_info();
185599
185843
  init_capability();
185600
185844
 
@@ -185605,6 +185849,7 @@ var os24 = __toESM(require("node:os"));
185605
185849
  var path63 = __toESM(require("node:path"));
185606
185850
  var import_pngjs7 = __toESM(require_png());
185607
185851
  init_src2();
185852
+ init_device_info();
185608
185853
 
185609
185854
  // ../tool-server/src/tools/screenshot-diff/screenshot-diff.ts
185610
185855
  var import_promises20 = __toESM(require("fs/promises"));
@@ -186883,7 +187128,7 @@ function formatScreenshotDiffSummary(result) {
186883
187128
  const textChanges = result.textAnalysis?.status === "ok" ? mergeTextChangesForSummary(result.textAnalysis.changes) : [];
186884
187129
  const shownTextChanges = textChanges.slice(0, MAX_SUMMARY_TEXT_CHANGES);
186885
187130
  const shownRegions = result.regions.slice(0, MAX_SUMMARY_REGIONS);
186886
- const coordinateSpace = coordinateSpaceForSummary(result.imageSize);
187131
+ const coordinateSpace2 = coordinateSpaceForSummary(result.imageSize);
186887
187132
  const lines = ["Screenshot diff summary", "", "Overall:"];
186888
187133
  lines.push(statusLine(status));
186889
187134
  if (result.sizeNormalization) {
@@ -186922,7 +187167,7 @@ function formatScreenshotDiffSummary(result) {
186922
187167
  lines.push(`- None detected.`);
186923
187168
  } else {
186924
187169
  for (const change of shownTextChanges) {
186925
- lines.push(...formatTextChange(change, coordinateSpace));
187170
+ lines.push(...formatTextChange(change, coordinateSpace2));
186926
187171
  }
186927
187172
  }
186928
187173
  } else {
@@ -186941,7 +187186,7 @@ function formatScreenshotDiffSummary(result) {
186941
187186
  lines.push(`- None detected.`);
186942
187187
  } else {
186943
187188
  for (const [index, region] of shownRegions.entries()) {
186944
- lines.push(`- Region ${index + 1}: ${formatRegion(region, coordinateSpace)}`);
187189
+ lines.push(`- Region ${index + 1}: ${formatRegion(region, coordinateSpace2)}`);
186945
187190
  }
186946
187191
  }
186947
187192
  return lines.join("\n");
@@ -186973,8 +187218,8 @@ function describeMismatch(result) {
186973
187218
  const scope = result.regions.length <= 5 ? "localized" : "broad";
186974
187219
  return `${severity} ${scope} visual change`;
186975
187220
  }
186976
- function formatRegion(region, coordinateSpace) {
186977
- return `${formatBounds(region.bounds, coordinateSpace)} - changed_pixels=${formatInteger(region.pixelCount)}`;
187221
+ function formatRegion(region, coordinateSpace2) {
187222
+ return `${formatBounds(region.bounds, coordinateSpace2)} - changed_pixels=${formatInteger(region.pixelCount)}`;
186978
187223
  }
186979
187224
  function mergeTextChangesForSummary(changes) {
186980
187225
  const merged = [];
@@ -187013,36 +187258,36 @@ function sameBounds2(left, right) {
187013
187258
  function normalizeSummaryText(text) {
187014
187259
  return text?.replace(/\s+/g, " ").trim().toLocaleLowerCase("en-US") ?? "";
187015
187260
  }
187016
- function formatTextChange(change, coordinateSpace) {
187261
+ function formatTextChange(change, coordinateSpace2) {
187017
187262
  switch (change.kind) {
187018
187263
  case "moved":
187019
187264
  return [
187020
187265
  `- ${formatMovedLabel(change)}: ${formatQuotedText(change.text)}`,
187021
- ...formatMoveBounds(change, coordinateSpace),
187022
- change.delta ? ` - delta: ${formatDelta(change.delta, coordinateSpace)}` : void 0,
187266
+ ...formatMoveBounds(change, coordinateSpace2),
187267
+ change.delta ? ` - delta: ${formatDelta(change.delta, coordinateSpace2)}` : void 0,
187023
187268
  formatAppearanceDetail(change)
187024
187269
  ].filter((line) => Boolean(line));
187025
187270
  case "appeared":
187026
187271
  return [
187027
187272
  `- Appeared: ${formatQuotedText(change.text)}`,
187028
- change.currentBounds ? ` - at ${formatBounds(change.currentBounds, coordinateSpace)}` : void 0
187273
+ change.currentBounds ? ` - at ${formatBounds(change.currentBounds, coordinateSpace2)}` : void 0
187029
187274
  ].filter((line) => Boolean(line));
187030
187275
  case "disappeared":
187031
187276
  return [
187032
187277
  `- Disappeared: ${formatQuotedText(change.text)}`,
187033
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0
187278
+ change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}` : void 0
187034
187279
  ].filter((line) => Boolean(line));
187035
187280
  case "content_changed":
187036
187281
  return [
187037
187282
  `- Changed: ${formatQuotedText(change.baselineText)} -> ${formatQuotedText(change.currentText)}`,
187038
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0,
187039
- change.currentBounds ? ` - to ${formatBounds(change.currentBounds, coordinateSpace)}` : void 0
187283
+ change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}` : void 0,
187284
+ change.currentBounds ? ` - to ${formatBounds(change.currentBounds, coordinateSpace2)}` : void 0
187040
187285
  ].filter((line) => Boolean(line));
187041
187286
  case "font_changed":
187042
187287
  return [
187043
187288
  `- Restyled: ${formatQuotedText(change.text)}${formatAppearanceLabelSuffix(change)}`,
187044
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0,
187045
- change.currentBounds ? ` - to ${formatBounds(change.currentBounds, coordinateSpace)}` : void 0
187289
+ change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}` : void 0,
187290
+ change.currentBounds ? ` - to ${formatBounds(change.currentBounds, coordinateSpace2)}` : void 0
187046
187291
  ].filter((line) => Boolean(line));
187047
187292
  default:
187048
187293
  return [
@@ -187050,13 +187295,13 @@ function formatTextChange(change, coordinateSpace) {
187050
187295
  ];
187051
187296
  }
187052
187297
  }
187053
- function formatMoveBounds(change, coordinateSpace) {
187298
+ function formatMoveBounds(change, coordinateSpace2) {
187054
187299
  const parts2 = [];
187055
187300
  if (change.baselineBounds) {
187056
- parts2.push(` - from ${formatBounds(change.baselineBounds, coordinateSpace)}`);
187301
+ parts2.push(` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}`);
187057
187302
  }
187058
187303
  if (change.currentBounds) {
187059
- parts2.push(` - to ${formatBounds(change.currentBounds, coordinateSpace)}`);
187304
+ parts2.push(` - to ${formatBounds(change.currentBounds, coordinateSpace2)}`);
187060
187305
  }
187061
187306
  return parts2;
187062
187307
  }
@@ -187104,17 +187349,17 @@ function coordinateSpaceForSummary(imageSize) {
187104
187349
  }
187105
187350
  return { imageSize };
187106
187351
  }
187107
- function formatBounds(bounds, coordinateSpace) {
187108
- if (!coordinateSpace) {
187352
+ function formatBounds(bounds, coordinateSpace2) {
187353
+ if (!coordinateSpace2) {
187109
187354
  return `x=${formatInteger(bounds.x)} y=${formatInteger(bounds.y)} w=${formatInteger(bounds.width)} h=${formatInteger(bounds.height)}`;
187110
187355
  }
187111
- return `x=${formatNormalizedPosition(bounds.x, coordinateSpace.imageSize.width)} y=${formatNormalizedPosition(bounds.y, coordinateSpace.imageSize.height)} w=${formatNormalizedPosition(bounds.width, coordinateSpace.imageSize.width)} h=${formatNormalizedPosition(bounds.height, coordinateSpace.imageSize.height)}`;
187356
+ return `x=${formatNormalizedPosition(bounds.x, coordinateSpace2.imageSize.width)} y=${formatNormalizedPosition(bounds.y, coordinateSpace2.imageSize.height)} w=${formatNormalizedPosition(bounds.width, coordinateSpace2.imageSize.width)} h=${formatNormalizedPosition(bounds.height, coordinateSpace2.imageSize.height)}`;
187112
187357
  }
187113
- function formatDelta(delta, coordinateSpace) {
187114
- if (!coordinateSpace) {
187358
+ function formatDelta(delta, coordinateSpace2) {
187359
+ if (!coordinateSpace2) {
187115
187360
  return `dx=${formatSignedNumber(delta.x)} dy=${formatSignedNumber(delta.y)} dw=${formatSignedNumber(delta.width)} dh=${formatSignedNumber(delta.height)}`;
187116
187361
  }
187117
- return `dx=${formatSignedNormalizedNumber(delta.x / coordinateSpace.imageSize.width)} dy=${formatSignedNormalizedNumber(delta.y / coordinateSpace.imageSize.height)} dw=${formatSignedNormalizedNumber(delta.width / coordinateSpace.imageSize.width)} dh=${formatSignedNormalizedNumber(delta.height / coordinateSpace.imageSize.height)}`;
187362
+ return `dx=${formatSignedNormalizedNumber(delta.x / coordinateSpace2.imageSize.width)} dy=${formatSignedNormalizedNumber(delta.y / coordinateSpace2.imageSize.height)} dw=${formatSignedNormalizedNumber(delta.width / coordinateSpace2.imageSize.width)} dh=${formatSignedNormalizedNumber(delta.height / coordinateSpace2.imageSize.height)}`;
187118
187363
  }
187119
187364
  function formatQuotedText(text) {
187120
187365
  if (!text) return '"[none]"';
@@ -187768,12 +188013,14 @@ async function runSnapshot(env, opts) {
187768
188013
  scale: 1,
187769
188014
  includeImageInContext: false
187770
188015
  });
187771
- const captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
188016
+ let captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
187772
188017
  const { w, h } = await pngDimensions(shot.image.hostPath);
187773
188018
  const cropSuffix = opts.cropOn === void 0 ? "" : `-crop-${(0, import_node_crypto19.createHash)("sha256").update(cropIdentity(opts.cropOn)).digest("hex").slice(0, 8)}`;
187774
- const snapshotKey = `${opts.name}__${authoringPlatform(env.device.platform)}-${w}x${h}${cropSuffix}`;
187775
- const key2 = `${snapshotKey}.png`;
187776
- const baselinePath = opts.clientFlowPath === void 0 ? path63.join(baselineDir(opts.flowsDir, opts.flowName), key2) : clientBaselinePath(opts.clientFlowPath, opts.flowName, key2);
188019
+ const keyFor = (width, height) => `${opts.name}__${authoringPlatform(env.device.platform)}-${width}x${height}${cropSuffix}`;
188020
+ const baselineFor = (file2) => opts.clientFlowPath === void 0 ? path63.join(baselineDir(opts.flowsDir, opts.flowName), file2) : clientBaselinePath(opts.clientFlowPath, opts.flowName, file2);
188021
+ const snapshotKey = keyFor(w, h);
188022
+ let key2 = `${snapshotKey}.png`;
188023
+ let baselinePath = baselineFor(key2);
187777
188024
  const priorApp = opts.seenKeys.get(snapshotKey);
187778
188025
  if (priorApp !== void 0 && priorApp !== opts.appIdentity) {
187779
188026
  return {
@@ -187857,12 +188104,32 @@ async function runSnapshot(env, opts) {
187857
188104
  artifacts: { baseline }
187858
188105
  };
187859
188106
  }
187860
- const stored = await opts.project.readFile(baselinePath).catch((err) => {
187861
- if (opts.project.mode !== "host" || !(err instanceof Error) || err.message.includes(baselinePath)) {
188107
+ const readBaseline = (file2) => opts.project.readFile(file2).catch((err) => {
188108
+ if (opts.project.mode !== "host" || !(err instanceof Error) || err.message.includes(file2)) {
187862
188109
  throw err;
187863
188110
  }
187864
- throw new Error(`Could not read PNG at ${baselinePath}: ${err.message}`, { cause: err });
187865
- });
188111
+ throw new Error(`Could not read PNG at ${file2}: ${err.message}`, { cause: err });
188112
+ });
188113
+ let stored = await readBaseline(baselinePath);
188114
+ const sideways = stored === null ? await sidewaysOrientation(env) : void 0;
188115
+ if (sideways !== void 0) {
188116
+ const legacyKey = `${keyFor(h, w)}.png`;
188117
+ const legacyPath = baselineFor(legacyKey);
188118
+ const legacy = await readBaseline(legacyPath);
188119
+ if (legacy !== null) {
188120
+ cropDir ??= await fs77.mkdtemp(path63.join(os24.tmpdir(), "argent-e2e-crop-"));
188121
+ const turnedPath = path63.join(cropDir, `native-${legacyKey}`);
188122
+ await turnPngToNative(currentPath, turnedPath, sideways);
188123
+ currentPath = turnedPath;
188124
+ stored = legacy;
188125
+ key2 = legacyKey;
188126
+ baselinePath = legacyPath;
188127
+ const note = `compared against ${legacyKey}, a baseline an older Argent took in the screen's portrait-native space, with the capture turned to match. Run with updateBaselines (--update-baselines) to store an upright one as ${snapshotKey}.png`;
188128
+ captureWarned = {
188129
+ warning: captureWarned.warning ? `${captureWarned.warning} ${note}` : note
188130
+ };
188131
+ }
188132
+ }
187866
188133
  if (stored === null) {
187867
188134
  return {
187868
188135
  ...captureWarned,
@@ -187925,7 +188192,7 @@ async function runSnapshot(env, opts) {
187925
188192
  });
187926
188193
  keepInOutputDir = result.contextDiffPath;
187927
188194
  }
187928
- return { status: "fail", reason: reason2, snapshotKey, artifacts };
188195
+ return { ...captureWarned, status: "fail", reason: reason2, snapshotKey, artifacts };
187929
188196
  } finally {
187930
188197
  await cleanupDiffDir(outputDir, keepInOutputDir);
187931
188198
  }
@@ -187941,6 +188208,32 @@ async function runSnapshot(env, opts) {
187941
188208
  }
187942
188209
  }
187943
188210
  }
188211
+ async function sidewaysOrientation(env) {
188212
+ if (!isIosSimulator(env.device)) return void 0;
188213
+ const { orientation } = await readUiOrientation(env.device.id);
188214
+ return orientation === "landscapeLeft" || orientation === "landscapeRight" ? orientation : void 0;
188215
+ }
188216
+ async function turnPngToNative(src, dest, orientation) {
188217
+ const upright = import_pngjs7.PNG.sync.read(await fs77.readFile(src));
188218
+ const native = new import_pngjs7.PNG({ width: upright.height, height: upright.width });
188219
+ for (let y = 0; y < native.height; y++) {
188220
+ for (let x = 0; x < native.width; x++) {
188221
+ const p = nativePointToUi(
188222
+ { x: (x + 0.5) / native.width, y: (y + 0.5) / native.height },
188223
+ orientation
188224
+ );
188225
+ const ux = Math.min(upright.width - 1, Math.floor(p.x * upright.width));
188226
+ const uy = Math.min(upright.height - 1, Math.floor(p.y * upright.height));
188227
+ upright.data.copy(
188228
+ native.data,
188229
+ (y * native.width + x) * 4,
188230
+ (uy * upright.width + ux) * 4,
188231
+ (uy * upright.width + ux) * 4 + 4
188232
+ );
188233
+ }
188234
+ }
188235
+ await fs77.writeFile(dest, import_pngjs7.PNG.sync.write(native));
188236
+ }
187944
188237
 
187945
188238
  // ../tool-server/src/utils/status-bar.ts
187946
188239
  var import_node_child_process53 = require("node:child_process");
@@ -188715,9 +189008,6 @@ Without a link, every step kind runs.`,
188715
189008
  // its own, which is why that step spends this verdict rather than
188716
189009
  // inheriting whatever the sub-run proved.
188717
189010
  treeOutage: {},
188718
- // Same shape and sharing as `treeOutage`: what the last read said about
188719
- // the UI's orientation, for the directives that turn a direction.
188720
- lastRead: {},
188721
189011
  flowsDir,
188722
189012
  viaUpload,
188723
189013
  project,
@@ -188749,7 +189039,8 @@ Without a link, every step kind runs.`,
188749
189039
  await execSteps(state3, flow.steps, {
188750
189040
  runStack: seed,
188751
189041
  rootDisplay: rootEntry.display,
188752
- depth: 0
189042
+ depth: 0,
189043
+ legacyPoints: flowFormatVersion(flow) < 2
188753
189044
  });
188754
189045
  } finally {
188755
189046
  aborted2 = state3.signal?.aborted === true;
@@ -189081,7 +189372,10 @@ async function execSteps(state3, steps, scope) {
189081
189372
  state3.hoistedBootMs = void 0;
189082
189373
  }
189083
189374
  if (JSON.stringify(step).includes(SECRET_PLACEHOLDER_MARKER)) state3.secretTyped = true;
189084
- const report = await execLeafStep(state3, step, index, scope);
189375
+ const report = await inCoordinateSpace(
189376
+ scope.legacyPoints && step.kind === "tool" ? "native" : "upright",
189377
+ () => execLeafStep(state3, step, index, scope)
189378
+ );
189085
189379
  if (report.status !== "skip") report.durationMs = Date.now() - startedAt;
189086
189380
  if ((report.status === "fail" || report.status === "error") && !report.artifacts) {
189087
189381
  const screen = await captureFailureScreen(state3);
@@ -189259,7 +189553,10 @@ async function execRunStep(state3, step, scope) {
189259
189553
  await execSteps(
189260
189554
  state3,
189261
189555
  fragment.steps,
189262
- childScope(scope, { runStack: [...scope.runStack, { canonical, display }] })
189556
+ childScope(scope, {
189557
+ runStack: [...scope.runStack, { canonical, display }],
189558
+ legacyPoints: flowFormatVersion(fragment) < 2
189559
+ })
189263
189560
  );
189264
189561
  }
189265
189562
  function oneLineReason(text) {
@@ -189275,13 +189572,11 @@ async function runScriptStep(state3, step, scope) {
189275
189572
  });
189276
189573
  return outcome.reason === void 0 ? outcome : { ...outcome, reason: oneLineReason(outcome.reason) };
189277
189574
  }
189278
- var UI_TURNING_TOOLS = /* @__PURE__ */ new Set(["rotate", "fold"]);
189279
189575
  async function runFold(state3, step) {
189280
189576
  const { registry: registry2, ctx, signal } = state3;
189281
189577
  const device = deviceEnv(state3).device;
189282
189578
  if (signal?.aborted) return ABORTED_OUTCOME;
189283
189579
  if (state3.treeOutage) state3.treeOutage.proven = void 0;
189284
- if (state3.lastRead) state3.lastRead.uiOrientation = void 0;
189285
189580
  const args = bindDeviceArgs(registry2, "fold", device.id, {
189286
189581
  ...step.posture !== void 0 ? { posture: step.posture } : {},
189287
189582
  ...step.angle !== void 0 ? { angle: step.angle } : {}
@@ -189337,7 +189632,10 @@ async function execLeafStep(state3, step, index, scope) {
189337
189632
  case "pinch":
189338
189633
  case "rotate": {
189339
189634
  try {
189340
- const r = await runDirective(deviceEnv(state3), step);
189635
+ const env = deviceEnv(state3);
189636
+ const legacy = scope.legacyPoints ? await uprightLegacyPoints(env.device, step) : { step, warning: void 0 };
189637
+ const r = await runDirective(env, legacy.step);
189638
+ const warning = [legacy.warning, r.warning].filter((w) => w !== void 0).join(" ");
189341
189639
  if (r.aborted) return { ...base, status: "skip", reason: r.reason };
189342
189640
  if (!r.ok && r.indeterminate && (step.kind === "idle" || device !== null && !supportsFlowTree(device.platform))) {
189343
189641
  return { ...base, status: "error", reason: r.reason };
@@ -189346,7 +189644,7 @@ async function execLeafStep(state3, step, index, scope) {
189346
189644
  ...base,
189347
189645
  status: r.ok ? "pass" : "fail",
189348
189646
  reason: r.reason,
189349
- ...r.warning !== void 0 ? { warning: r.warning } : {}
189647
+ ...warning ? { warning } : {}
189350
189648
  };
189351
189649
  } catch (err) {
189352
189650
  return { ...base, status: "error", reason: errMsg5(err) };
@@ -189417,9 +189715,6 @@ async function execLeafStep(state3, step, index, scope) {
189417
189715
  if (isNestedOrchestratorTool(step.name) && state3.treeOutage) {
189418
189716
  state3.treeOutage.proven = void 0;
189419
189717
  }
189420
- if (UI_TURNING_TOOLS.has(step.name) && state3.lastRead) {
189421
- state3.lastRead.uiOrientation = void 0;
189422
- }
189423
189718
  let prepared;
189424
189719
  try {
189425
189720
  if (device?.platform === "macos") {
@@ -190371,7 +190666,7 @@ async function executeScreenshotDiffTool(services, params, options, captureScree
190371
190666
  });
190372
190667
  let summary = result.summary;
190373
190668
  for (const warning of new Set(warnings)) summary = `${summary}
190374
- - panel: ${warning}`;
190669
+ - capture: ${warning}`;
190375
190670
  if (result.dimensionMismatch) {
190376
190671
  const posture = await foldablePostureHint(
190377
190672
  params.udid,
@@ -190579,10 +190874,8 @@ async function captureLiveInput(params) {
190579
190874
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
190580
190875
  await import_promises22.default.mkdir(params.outputDir, { recursive: true });
190581
190876
  await import_promises22.default.copyFile(capture.path, destination);
190582
- return {
190583
- path: destination,
190584
- ...panel?.warning !== void 0 ? { warning: panel.warning } : {}
190585
- };
190877
+ const warning = [panel?.warning, capture.note].filter((w) => w !== void 0).join(" ");
190878
+ return { path: destination, ...warning ? { warning } : {} };
190586
190879
  }
190587
190880
 
190588
190881
  // ../tool-server/src/tools/variants/propose-variant.ts
@@ -191529,6 +191822,10 @@ function createRegistry() {
191529
191822
  const ref = axServiceRef(resolveDevice(udid));
191530
191823
  return registry2.resolveService(ref.urn, ref.options);
191531
191824
  });
191825
+ setUiOrientationSourceProvider((udid) => {
191826
+ const ref = axServiceRef(resolveDevice(udid));
191827
+ return registry2.resolveService(ref.urn, ref.options);
191828
+ });
191532
191829
  registry2.registerBlueprint(simulatorServerBlueprint);
191533
191830
  registry2.registerBlueprint(iosDeviceRunnerBlueprint);
191534
191831
  registry2.registerBlueprint(jsRuntimeDebuggerBlueprint);
@@ -191583,7 +191880,7 @@ function createRegistry() {
191583
191880
  registry2.registerTool(createDebuggerStatusTool(registry2));
191584
191881
  registry2.registerTool(debuggerEvaluateTool);
191585
191882
  registry2.registerTool(debuggerReloadMetroTool);
191586
- registry2.registerTool(createDebuggerComponentTreeTool(registry2));
191883
+ registry2.registerTool(createDebuggerComponentTreeTool());
191587
191884
  registry2.registerTool(debuggerInspectElementTool);
191588
191885
  registry2.registerTool(createDebuggerLogRegistryTool(registry2));
191589
191886
  registry2.registerTool(networkLogsTool);