@swmansion/argent 0.34.1-next.23 → 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) {
@@ -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";
@@ -147401,10 +147598,10 @@ function createInspector(serial, packageName, initialMetroPort) {
147401
147598
  log(`the agent dropped ${conn.droppedEvents} events while it was disconnected`);
147402
147599
  }
147403
147600
  if (Array.isArray(r.inFlight)) {
147404
- const inFlight3 = new Set(r.inFlight.filter((id) => typeof id === "string"));
147601
+ const inFlight4 = new Set(r.inFlight.filter((id) => typeof id === "string"));
147405
147602
  for (let c = conn; c; c = c.resumes) {
147406
147603
  for (const record2 of c.byLayerId.values()) {
147407
- if (inFlight3.has(record2.layerId)) revive(record2);
147604
+ if (inFlight4.has(record2.layerId)) revive(record2);
147408
147605
  else if (isOpen(record2)) markLost(record2, LOST_WHILE_DISCONNECTED);
147409
147606
  }
147410
147607
  }
@@ -148258,6 +148455,93 @@ init_zod();
148258
148455
  init_src2();
148259
148456
  init_capability();
148260
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
148261
148545
  var nativeAppTarget = {
148262
148546
  udid: external_exports.string().describe(
148263
148547
  "Simulator UDID<flag:macos-apps>, or a Mac app id (macos-app-<bundle id>)</flag:macos-apps>"
@@ -148298,7 +148582,17 @@ async function queryViewHierarchyFor(services, params, toolId, method, errorCode
148298
148582
  const api = services.nativeDevtools;
148299
148583
  const blocked = await precheckNativeDevtools(api, udid, bundleId);
148300
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
+ }
148301
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);
148302
148596
  }
148303
148597
  if (errorCode2 && result.error) {
148304
148598
  throw new FailureError(result.error, {
@@ -148525,7 +148819,7 @@ var nativeFindViewsTool = {
148525
148819
  id: "native-find-views",
148526
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.
148527
148821
  Use when you need to locate a specific view by its properties without dumping the entire native-full-hierarchy.
148528
- 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.
148529
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.
148530
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.
148531
148825
  An Apple system app is rejected outright (terminal: never retry it).`,
@@ -148586,7 +148880,7 @@ var nativeFullHierarchyTool = {
148586
148880
  WARNING: Output can be extremely large (100KB\u2013500KB+) for complex apps, especially those built with SwiftUI. Prefer native-find-views for targeted queries.
148587
148881
  Reduce the output with skipClasses / skipClassPrefixes, fields and maxDepth.
148588
148882
  Use when you need deep layout debugging, finding views with no accessibility labels, or verifying view structure not exposed through the accessibility tree.
148589
- 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.
148590
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.
148591
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.
148592
148886
  An Apple system app is rejected outright (terminal: never retry it).`,
@@ -148612,8 +148906,9 @@ An Apple system app is rejected outright (terminal: never retry it).`,
148612
148906
  (result) => ({
148613
148907
  status: "ok",
148614
148908
  windows: result.windows ?? [],
148615
- // `screen` is the screen's point size in its portrait-native space, the
148616
- // 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;
148617
148912
  // an older injected build reports none.
148618
148913
  ...result.screen !== void 0 ? { screen: result.screen } : {}
148619
148914
  })
@@ -148637,7 +148932,7 @@ var nativeDescribeScreenTool = {
148637
148932
  description: `Read the running app's native accessibility screen description via injected native devtools.
148638
148933
 
148639
148934
  Returns a flat list of accessibility leaf elements with:
148640
- - 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
148641
148936
  - normalizedFrame and normalizedTapPoint on the same axes. gesture-tap uses
148642
148937
  these axes, also when the UI is landscape
148643
148938
  - top-level screenFrame metadata: the screen bounds on these axes
@@ -148684,7 +148979,7 @@ init_src2();
148684
148979
  var viewAtPointParams = {
148685
148980
  ...nativeAppTarget,
148686
148981
  x: external_exports.number().describe(
148687
- "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."
148688
148983
  ),
148689
148984
  y: external_exports.number().describe("Raw Y coordinate in points, on the same axes as x. NOT normalized [0,1] tap space."),
148690
148985
  includeAncestors: external_exports.boolean().optional().describe("Include ancestor chain for the matched view (default true)"),
@@ -148730,7 +149025,7 @@ identifier, label and layer name, plus its ancestors and subviews as requested.
148730
149025
  view is null when nothing is drawn at that point, or with hitTest when no touchable view sits under it.
148731
149026
 
148732
149027
  To get x and y from a normalized describe frame, multiply its values by the
148733
- screen size in points, also when the UI is landscape.
149028
+ screen size in points, on the same axes (landscape when the UI is).
148734
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,
148735
149030
  multiply them by the size of the area describe reports instead.</flag:macos-apps>
148736
149031
 
@@ -153132,7 +153427,7 @@ async function waitForHarmonyTarget(before, deadline, checkAlive, expected) {
153132
153427
  }
153133
153428
  async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153134
153429
  const probePath = (0, import_node_path19.join)((0, import_node_os14.tmpdir)(), `argent-harmony-bootprobe-${process.hrtime.bigint()}.json`);
153135
- let inFlight3 = null;
153430
+ let inFlight4 = null;
153136
153431
  try {
153137
153432
  for (; ; ) {
153138
153433
  const budget = deadline - Date.now();
@@ -153148,9 +153443,9 @@ async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153148
153443
  () => true,
153149
153444
  () => false
153150
153445
  );
153151
- inFlight3 = probe4;
153446
+ inFlight4 = probe4;
153152
153447
  const answered = await withinBudget(() => probe4, deadline);
153153
- if (answered !== null) inFlight3 = null;
153448
+ if (answered !== null) inFlight4 = null;
153154
153449
  if (answered) return true;
153155
153450
  checkAlive();
153156
153451
  const remaining = deadline - Date.now();
@@ -153160,7 +153455,7 @@ async function waitForHarmonyDrivable(connectKey, deadline, checkAlive) {
153160
153455
  } finally {
153161
153456
  const remove = () => (0, import_promises14.rm)(probePath, { force: true }).catch(() => {
153162
153457
  });
153163
- if (inFlight3) void inFlight3.then(remove);
153458
+ if (inFlight4) void inFlight4.then(remove);
153164
153459
  else await remove();
153165
153460
  }
153166
153461
  }
@@ -154132,9 +154427,9 @@ Common Android packages: com.android.settings, com.android.chrome, com.google.an
154132
154427
  execute: dispatchByPlatform({
154133
154428
  toolId: "launch-app",
154134
154429
  capability: capability3,
154135
- ios: makeIosImpl(registry2),
154430
+ ios: forgettingUiOrientation(makeIosImpl(registry2)),
154136
154431
  iosDevice: iosDeviceImpl,
154137
- iosRemote: iosRemoteImpl,
154432
+ iosRemote: forgettingUiOrientation(iosRemoteImpl),
154138
154433
  android: androidImpl,
154139
154434
  chromium: chromiumImpl,
154140
154435
  vega: vegaImpl,
@@ -154422,9 +154717,9 @@ For Mac apps, kind is 'catalyst' or 'app'. Check appPath and args to confirm the
154422
154717
  execute: dispatchByPlatform({
154423
154718
  toolId: "restart-app",
154424
154719
  capability: capability4,
154425
- ios: makeIosImpl2(registry2),
154720
+ ios: forgettingUiOrientation(makeIosImpl2(registry2)),
154426
154721
  iosDevice: iosDeviceImpl2,
154427
- iosRemote: iosRemoteImpl2,
154722
+ iosRemote: forgettingUiOrientation(iosRemoteImpl2),
154428
154723
  android: androidImpl2,
154429
154724
  vega: vegaImpl2,
154430
154725
  harmony: harmonyImpl2,
@@ -154469,7 +154764,7 @@ Succeeds when the app is not running or not installed.`,
154469
154764
  execute: dispatchByPlatform({
154470
154765
  toolId: "terminate-app",
154471
154766
  capability: capability5,
154472
- ios: {
154767
+ ios: forgettingUiOrientation({
154473
154768
  requires: ["xcrun"],
154474
154769
  handler: async (_services, { udid, bundleId }) => {
154475
154770
  const args = await simctlArgsForUdid(udid, ["terminate", udid, bundleId]);
@@ -154493,8 +154788,8 @@ Succeeds when the app is not running or not installed.`,
154493
154788
  const terminated = await tolerateNothingToTerminate(terminate, SIMCTL_NOTHING_TO_TERMINATE);
154494
154789
  return { terminated, bundleId };
154495
154790
  }
154496
- },
154497
- iosRemote: {
154791
+ }),
154792
+ iosRemote: forgettingUiOrientation({
154498
154793
  requires: ["sim-remote"],
154499
154794
  handler: async (_services, { udid, bundleId }) => {
154500
154795
  const terminated = await tolerateNothingToTerminate(
@@ -154503,7 +154798,7 @@ Succeeds when the app is not running or not installed.`,
154503
154798
  );
154504
154799
  return { terminated, bundleId };
154505
154800
  }
154506
- },
154801
+ }),
154507
154802
  android: {
154508
154803
  requires: ["adb"],
154509
154804
  handler: async (_services, { udid, bundleId }) => {
@@ -154981,10 +155276,10 @@ Returns { reinstalled, bundleId }. Fails if \`appPath\` does not exist or is not
154981
155276
  execute: dispatchByPlatform({
154982
155277
  toolId: "reinstall-app",
154983
155278
  capability: capability6,
154984
- ios: iosImpl,
155279
+ ios: forgettingUiOrientation(iosImpl),
154985
155280
  android: androidImpl3,
154986
155281
  iosDevice: iosDeviceImpl3,
154987
- iosRemote: iosRemoteImpl3,
155282
+ iosRemote: forgettingUiOrientation(iosRemoteImpl3),
154988
155283
  vega: vegaImpl3,
154989
155284
  harmony: harmonyImpl3
154990
155285
  })
@@ -155601,11 +155896,11 @@ Returns { opened, url, note? }. \`note\` explains the routing caveat when a web
155601
155896
  execute: dispatchByPlatform({
155602
155897
  toolId: "open-url",
155603
155898
  capability: capability8,
155604
- ios: iosImpl3,
155899
+ ios: forgettingUiOrientation(iosImpl3),
155605
155900
  iosDevice: iosDeviceImpl4,
155606
155901
  android: androidImpl5,
155607
155902
  harmony: harmonyImpl4,
155608
- iosRemote: iosRemoteImpl5,
155903
+ iosRemote: forgettingUiOrientation(iosRemoteImpl5),
155609
155904
  chromium: chromiumImpl2,
155610
155905
  macos: macosImpl3
155611
155906
  })
@@ -155691,10 +155986,14 @@ function captureLooksUpright(requested, size) {
155691
155986
  }
155692
155987
 
155693
155988
  // ../tool-server/src/utils/rotation-aware-capture.ts
155989
+ init_device_info();
155694
155990
  async function captureScreenshotUpright(api, device, requestedRotation, signal, scale, capture = httpScreenshot, peek) {
155695
- if (requestedRotation !== void 0 || device.platform !== "android") {
155696
- 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);
155697
155995
  }
155996
+ if (device.platform !== "android") return capture(api, void 0, signal, scale);
155698
155997
  const surface = await readAndroidSurfaceRotation(device.id, peek);
155699
155998
  const rotation = captureRotationForSurface(surface);
155700
155999
  if (!rotation) return capture(api, void 0, signal, scale);
@@ -155707,6 +156006,22 @@ async function captureScreenshotUpright(api, device, requestedRotation, signal,
155707
156006
  }
155708
156007
  return result;
155709
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
+ }
155710
156025
 
155711
156026
  // ../tool-server/src/utils/android-devtools-rotation-peek.ts
155712
156027
  init_src2();
@@ -155919,7 +156234,7 @@ var zodSchema17 = external_exports.object({
155919
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)."
155920
156235
  ),
155921
156236
  rotation: external_exports.enum(["Portrait", "LandscapeLeft", "LandscapeRight", "PortraitUpsideDown"]).optional().describe(
155922
- "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."
155923
156238
  ),
155924
156239
  scale: external_exports.number().min(0.01).max(1).optional().describe(
155925
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>"
@@ -155971,8 +156286,8 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
155971
156286
  });
155972
156287
  const requested = requestedGeometry(params);
155973
156288
  const dropped = (captured.droppedFeatures ?? []).filter((f) => requested.includes(f));
155974
- const note = chromiumDropNote(dropped, captured.dropReason);
155975
- return { image: image2, ...note ? { [RESULT_NOTE_KEY]: note } : {} };
156289
+ const note2 = chromiumDropNote(dropped, captured.dropReason);
156290
+ return { image: image2, ...note2 ? { [RESULT_NOTE_KEY]: note2 } : {} };
155976
156291
  }
155977
156292
  if (device.platform === "macos") {
155978
156293
  const app = await resolveMacosApp(registry2, device, "screenshot");
@@ -156029,7 +156344,7 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
156029
156344
  params.scale === void 0 && device.platform === "android" ? androidTvDefaultScale(device.id, apiReady) : void 0
156030
156345
  ]);
156031
156346
  const panel = await resolveCapturePanel(api);
156032
- const { path: capturedPath } = await captureScreenshotUpright(
156347
+ const { path: capturedPath, note: orientationNote } = await captureScreenshotUpright(
156033
156348
  api,
156034
156349
  device,
156035
156350
  params.rotation,
@@ -156043,9 +156358,10 @@ Fails if the capture backend (simulator-server, emulator, Chromium CDP<flag:harm
156043
156358
  kind: "screenshot",
156044
156359
  mimeType: "image/png"
156045
156360
  });
156361
+ const note = [panel?.note, orientationNote].filter((n) => n !== void 0).join(" ");
156046
156362
  return {
156047
156363
  image,
156048
- ...panel ? { [RESULT_NOTE_KEY]: panel.note } : {},
156364
+ ...note ? { [RESULT_NOTE_KEY]: note } : {},
156049
156365
  ...panel?.warning !== void 0 ? { warning: panel.warning } : {}
156050
156366
  };
156051
156367
  }
@@ -158551,7 +158867,7 @@ async function prepareHostWindowShake(target) {
158551
158867
  if (deviceSet !== null) return inert;
158552
158868
  const needles = target.name ? [target.name] : [];
158553
158869
  const script = animationScript(needles);
158554
- let inFlight3 = null;
158870
+ let inFlight4 = null;
158555
158871
  let dead = false;
158556
158872
  let warned2 = false;
158557
158873
  const warnOnce2 = (detail) => {
@@ -158561,7 +158877,7 @@ async function prepareHostWindowShake(target) {
158561
158877
  };
158562
158878
  return {
158563
158879
  begin() {
158564
- if (dead || inFlight3 !== null) return;
158880
+ if (dead || inFlight4 !== null) return;
158565
158881
  let run2;
158566
158882
  try {
158567
158883
  run2 = runOsascript(script);
@@ -158570,9 +158886,9 @@ async function prepareHostWindowShake(target) {
158570
158886
  warnOnce2(err instanceof Error ? err.message : String(err));
158571
158887
  return;
158572
158888
  }
158573
- inFlight3 = run2.then(
158889
+ inFlight4 = run2.then(
158574
158890
  () => {
158575
- inFlight3 = null;
158891
+ inFlight4 = null;
158576
158892
  },
158577
158893
  async (err) => {
158578
158894
  dead = true;
@@ -158581,12 +158897,12 @@ async function prepareHostWindowShake(target) {
158581
158897
  await restoreOriginAfterKill(needles, failure2.rawStderr);
158582
158898
  }
158583
158899
  warnOnce2(err instanceof Error ? err.message : String(err));
158584
- inFlight3 = null;
158900
+ inFlight4 = null;
158585
158901
  }
158586
158902
  );
158587
158903
  },
158588
158904
  settle() {
158589
- return inFlight3 ?? Promise.resolve();
158905
+ return inFlight4 ?? Promise.resolve();
158590
158906
  }
158591
158907
  };
158592
158908
  } catch (err) {
@@ -160305,7 +160621,6 @@ function makeComponentTreeScript(opts) {
160305
160621
  }
160306
160622
 
160307
160623
  // ../tool-server/src/tools/debugger/debugger-component-tree.ts
160308
- init_device_info();
160309
160624
  function rectsOverlap(a, b) {
160310
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;
160311
160626
  }
@@ -160545,49 +160860,16 @@ function buildTextTree(data, opts) {
160545
160860
  }
160546
160861
  }
160547
160862
  const lines = [];
160548
- const turn = opts.uiOrientation && opts.uiOrientation !== "unknown" && opts.uiOrientation !== "ambiguous" && opts.uiOrientation !== "mismatched" ? opts.uiOrientation : void 0;
160549
- if (canNormalize) {
160550
- lines.push(`Screen: ${screenW}x${screenH}`);
160551
- if (opts.uiOrientation === "mismatched") {
160552
- lines.push(
160553
- "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."
160554
- );
160555
- } else if (turn && turn !== "portrait") {
160556
- lines.push(
160557
- `The UI is ${turn} on the screen. The tap points are on the screen's axes, which the gesture tools use.`
160558
- );
160559
- } else if (opts.uiOrientation === "ambiguous" && screenW > screenH) {
160560
- lines.push(
160561
- "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."
160562
- );
160563
- } else if (opts.uiOrientation === "unknown" && screenW > screenH) {
160564
- lines.push(
160565
- "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."
160566
- );
160567
- }
160568
- if (opts.readInsteadOfUdid) {
160569
- lines.push(
160570
- `Note: the udid is not the UDID of the simulator that shows this app. The tool used ${opts.readInsteadOfUdid}, the UDID of that simulator.`
160571
- );
160572
- }
160573
- if (opts.udidUnchecked && (screenW > screenH || turn !== void 0 && turn !== "portrait")) {
160574
- lines.push(
160575
- "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."
160576
- );
160577
- }
160578
- lines.push("");
160579
- }
160863
+ if (canNormalize) lines.push(`Screen: ${screenW}x${screenH}`, "");
160580
160864
  function formatLabel2(c) {
160581
160865
  let label = c.name;
160582
160866
  const displayText = c.text ?? c.accLabel;
160583
160867
  if (displayText) label += ` "${displayText}"`;
160584
160868
  if (c.testID) label += ` [testID=${c.testID}]`;
160585
160869
  if (c.rect && canNormalize) {
160586
- const tap = uiPointToNative(
160587
- { x: (c.rect.x + c.rect.w / 2) / screenW, y: (c.rect.y + c.rect.h / 2) / screenH },
160588
- turn
160589
- );
160590
- 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)})`;
160591
160873
  }
160592
160874
  return label;
160593
160875
  }
@@ -160669,115 +160951,11 @@ function buildTextTree(data, opts) {
160669
160951
  }
160670
160952
  return lines.join("\n");
160671
160953
  }
160672
- var ORIENTATION_READ_TIMEOUT_MS = 3e3;
160673
- async function debuggedBundleId(api, appName) {
160674
- const named = api.listConnectedBundleIds().filter((id) => appName === id || appName.startsWith(`${id} `));
160675
- if (named.length === 1) return named[0];
160676
- if (BUNDLE_ID_NAMED_TARGET.test(appName)) return void 0;
160677
- return (await resolveNativeTargetApp(api)).bundleId;
160678
- }
160679
- var BUNDLE_ID_NAMED_TARGET = /^[\w-]+(\.[\w-]+)+( \(|$)/;
160680
- var AMBIGUOUS_SIMULATOR = "ambiguous-simulator";
160681
- var MISMATCHED_UDID = "mismatched-udid";
160682
- var UNLISTED_UDID = "unlisted-udid";
160683
- async function iosSimulatorOf(app) {
160684
- if (!app.udid) {
160685
- const session2 = await iosSimulatorOfSession(app);
160686
- return session2 === AMBIGUOUS_SIMULATOR || !session2 ? session2 : { device: session2 };
160687
- }
160688
- const named = resolveDevice(app.udid);
160689
- const own2 = resolveDevice(canonicalDeviceId(app.deviceId) ?? app.deviceId);
160690
- if (isIosSimulator(own2)) {
160691
- if (own2.id === named.id) return { device: own2 };
160692
- if (isIosSimulator(named)) {
160693
- const [listed2, ownListed] = await Promise.all([
160694
- listedAs(named, app.deviceName),
160695
- listedAs(own2, app.deviceName)
160696
- ]);
160697
- if (listed2 === "booted" && ownListed !== "booted") return { device: named };
160698
- }
160699
- return { device: own2, readInsteadOfUdid: own2.id };
160700
- }
160701
- const [listed, session] = await Promise.all([
160702
- isIosSimulator(named) ? listedAs(named, app.deviceName) : void 0,
160703
- iosSimulatorOfSession(app)
160704
- ]);
160705
- if (listed === "booted" || listed === "twin") {
160706
- const sole = session === void 0 || session !== AMBIGUOUS_SIMULATOR && session.id === named.id;
160707
- return listed === "booted" && sole ? { device: named } : { device: named, udidUnchecked: true };
160708
- }
160709
- if (session === AMBIGUOUS_SIMULATOR) return MISMATCHED_UDID;
160710
- if (session) {
160711
- return session.id === named.id ? { device: session } : { device: session, readInsteadOfUdid: session.id };
160712
- }
160713
- return listed === "unlisted" ? UNLISTED_UDID : void 0;
160714
- }
160715
- async function listedAs(device, name) {
160716
- if (device.platform !== "ios-remote") {
160717
- const sim2 = await findIosSimulator(device.id);
160718
- if (!sim2) return "unlisted";
160719
- return sim2.state === "Booted" && sim2.name === name ? "booted" : "other";
160720
- }
160721
- const listing = Object.values(
160722
- (await simctlListDevices({ timeoutMs: ORIENTATION_READ_TIMEOUT_MS }).catch(() => ({
160723
- devices: {}
160724
- }))).devices
160725
- ).flat();
160726
- const sim = listing.find((d) => d.udid === stripRemotePrefix(device.id));
160727
- if (!sim) return "unlisted";
160728
- if (sim.state !== "Booted" || sim.name !== name) return "other";
160729
- return listing.some((d) => d !== sim && d.state === "Booted" && d.name === name) ? "twin" : "booted";
160730
- }
160731
- async function iosSimulatorOfSession(app) {
160732
- const device = resolveDevice(canonicalDeviceId(app.deviceId) ?? app.deviceId);
160733
- if (isIosSimulator(device)) return device;
160734
- const logicalKeyed = app.deviceId === app.logicalDeviceId || isLogicalKeyedDevice(app.deviceId);
160735
- if (!logicalKeyed) return void 0;
160736
- const named = (await listIosSimulators()).filter(
160737
- (sim) => sim.state === "Booted" && sim.runtimeKind === "mobile" && sim.name === app.deviceName
160738
- );
160739
- if (named.length === 1) return resolveDevice(named[0].udid);
160740
- return named.length > 1 ? AMBIGUOUS_SIMULATOR : void 0;
160741
- }
160742
- async function readTapAxes(registry2, app) {
160743
- const read = (async () => {
160744
- const pick2 = await iosSimulatorOf(app);
160745
- if (pick2 === void 0) return {};
160746
- if (pick2 === AMBIGUOUS_SIMULATOR) return { uiOrientation: "ambiguous" };
160747
- if (pick2 === MISMATCHED_UDID) return { uiOrientation: "mismatched" };
160748
- if (pick2 === UNLISTED_UDID) return { uiOrientation: "unknown" };
160749
- const { device, ...udid } = pick2;
160750
- const ref = nativeDevtoolsRef(device);
160751
- const api = await registry2.resolveService(ref.urn, ref.options);
160752
- const bundleId = await debuggedBundleId(api, app.appName);
160753
- if (!bundleId) return { uiOrientation: "unknown", ...udid };
160754
- const raw = await api.queryViewHierarchy(bundleId, "ViewHierarchy.getFullHierarchy", {
160755
- fields: ["className"],
160756
- maxDepth: 1
160757
- });
160758
- return {
160759
- uiOrientation: asUiOrientation(raw?.screen?.interfaceOrientation) ?? "unknown",
160760
- ...udid
160761
- };
160762
- })().catch(() => ({ uiOrientation: "unknown" }));
160763
- let timer;
160764
- const timeout = new Promise((resolve19) => {
160765
- timer = setTimeout(() => resolve19({ uiOrientation: "unknown" }), ORIENTATION_READ_TIMEOUT_MS);
160766
- });
160767
- try {
160768
- return await Promise.race([read, timeout]);
160769
- } finally {
160770
- clearTimeout(timer);
160771
- }
160772
- }
160773
160954
  var zodSchema35 = external_exports.object({
160774
160955
  port: metroPortField,
160775
160956
  device_id: external_exports.string().describe(
160776
160957
  "Device id from list-devices: the SAME id you passed to debugger-connect (iOS simulator UDID or Android serial)."
160777
160958
  ),
160778
- udid: external_exports.string().optional().describe(
160779
- "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."
160780
- ),
160781
160959
  onScreenOnly: external_exports.boolean().default(true).describe(
160782
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."
160783
160961
  ),
@@ -160788,7 +160966,7 @@ var zodSchema35 = external_exports.object({
160788
160966
  "When true, appends a summary of all filtered components: total fiber count and skip counts by component name and by filter."
160789
160967
  )
160790
160968
  });
160791
- function createDebuggerComponentTreeTool(registry2) {
160969
+ function createDebuggerComponentTreeTool() {
160792
160970
  return {
160793
160971
  id: "debugger-component-tree",
160794
160972
  description: `Fetch the current screen of a running React Native app as a compact tree of React components.
@@ -160801,8 +160979,6 @@ Use when you need what describe does not show: a testID for a selector (on Andro
160801
160979
  the testID of a view that has no label and is not tappable), or the component names and nesting
160802
160980
  behind the screen before editing code. To find what to tap, use describe.
160803
160981
 
160804
- On an iOS simulator with a landscape UI (a rotated device, or an unfolded foldable), the tap
160805
- coordinates are on the screen's axes, which the gesture tools use.
160806
160982
  Returns a compact text tree; call again after navigation. Fails if the Metro debugger is not connected.`,
160807
160983
  zodSchema: zodSchema35,
160808
160984
  searchHint: "react native component tree testID testIDs selector component names hierarchy",
@@ -160820,13 +160996,6 @@ Returns a compact text tree; call again after navigation. Fails if the Metro deb
160820
160996
  }),
160821
160997
  async execute(services, params) {
160822
160998
  const api = services.debugger;
160823
- const tapAxes = readTapAxes(registry2, {
160824
- deviceId: params.device_id,
160825
- udid: params.udid,
160826
- appName: api.appName,
160827
- deviceName: api.deviceName,
160828
- logicalDeviceId: api.logicalDeviceId
160829
- });
160830
160999
  const requestId = crypto4.randomUUID();
160831
161000
  const script = makeComponentTreeScript({
160832
161001
  includeSkipped: params.includeSkipped,
@@ -160846,8 +161015,7 @@ Returns a compact text tree; call again after navigation. Fails if the Metro deb
160846
161015
  const tree = buildTextTree(parsed2, {
160847
161016
  onScreenOnly: params.onScreenOnly,
160848
161017
  maxNodes: params.maxNodes,
160849
- includeSkipped: params.includeSkipped,
160850
- ...await tapAxes
161018
+ includeSkipped: params.includeSkipped
160851
161019
  });
160852
161020
  const deviceLine = [
160853
161021
  `device: ${api.deviceName}`,
@@ -162490,6 +162658,8 @@ function markHidden(node2, clip3) {
162490
162658
  for (const child of node2.children) markHidden(child, inner);
162491
162659
  }
162492
162660
  function adaptAxTree(response) {
162661
+ const orientation = response.interfaceOrientation;
162662
+ const turn = (frame2) => frame2 && isTurned(orientation) ? nativeFrameToUi(frame2, orientation) : frame2;
162493
162663
  const byIndex = /* @__PURE__ */ new Map();
162494
162664
  const roots = [];
162495
162665
  let keyboardVisible = false;
@@ -162504,7 +162674,7 @@ function adaptAxTree(response) {
162504
162674
  value: raw.hintShowing ? void 0 : raw.value,
162505
162675
  identifier: raw.identifier,
162506
162676
  roleDescription: raw.roleDescription,
162507
- frame: raw.frame,
162677
+ frame: turn(raw.frame),
162508
162678
  children: []
162509
162679
  };
162510
162680
  if (raw.elementType !== void 0)
@@ -162531,7 +162701,7 @@ function adaptAxTree(response) {
162531
162701
  return {
162532
162702
  schemaVersion: 1,
162533
162703
  source: "ax-service",
162534
- screen: response.screenFrame,
162704
+ screen: response.screenFrame && uiScreenSize(response.screenFrame, orientation),
162535
162705
  roots,
162536
162706
  truncated: response.truncated,
162537
162707
  alertVisible: response.alertVisible,
@@ -162544,7 +162714,9 @@ function adaptAxTree(response) {
162544
162714
  async function readIosUiTree(registry2, device) {
162545
162715
  const ref = axServiceRef(device);
162546
162716
  const ax = await registry2.resolveService(ref.urn, ref.options);
162547
- return adaptAxTree(await ax.tree());
162717
+ const response = await ax.tree();
162718
+ noteUiOrientation(device.id, response.interfaceOrientation, response.screenFrame);
162719
+ return adaptAxTree(response);
162548
162720
  }
162549
162721
 
162550
162722
  // ../tool-server/src/tools/flows/flow-android-tree.ts
@@ -174570,10 +174742,10 @@ async function disablePointer(api) {
174570
174742
  });
174571
174743
  }
174572
174744
  function startPanelFollow(api, follow, child) {
174573
- let inFlight3 = false;
174745
+ let inFlight4 = false;
174574
174746
  api.panelPollTimer = setInterval(() => {
174575
- if (inFlight3 || api.captureProcess !== child) return;
174576
- inFlight3 = true;
174747
+ if (inFlight4 || api.captureProcess !== child) return;
174748
+ inFlight4 = true;
174577
174749
  void (async () => {
174578
174750
  try {
174579
174751
  const live = await follow.resolveLivePanel();
@@ -174609,7 +174781,7 @@ function startPanelFollow(api, follow, child) {
174609
174781
  `
174610
174782
  );
174611
174783
  } finally {
174612
- inFlight3 = false;
174784
+ inFlight4 = false;
174613
174785
  }
174614
174786
  })();
174615
174787
  }, follow.pollMs ?? PANEL_POLL_MS);
@@ -178108,8 +178280,8 @@ function flowPathIn(flowsDir, name) {
178108
178280
  }
178109
178281
  async function resolveFlowKey(projectRoot, name) {
178110
178282
  const spelled = getFlowPath(projectRoot, name);
178111
- const inFlight3 = keyResolutions.get(spelled);
178112
- if (inFlight3) return inFlight3;
178283
+ const inFlight4 = keyResolutions.get(spelled);
178284
+ if (inFlight4) return inFlight4;
178113
178285
  const resolving = canonicalFlowPath2(spelled).finally(() => {
178114
178286
  if (keyResolutions.get(spelled) === resolving) keyResolutions.delete(spelled);
178115
178287
  });
@@ -180011,7 +180183,11 @@ function fromYamlStep(raw, blockDepth = 0) {
180011
180183
  }
180012
180184
  return badEntry(raw, "unrecognized step kind");
180013
180185
  }
180014
- 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
+ }
180015
180191
  function requiresToYaml({ platform, runtimeKind }) {
180016
180192
  return {
180017
180193
  ...platform ? { platform: platform.length === 1 ? platform[0] : platform } : {},
@@ -180115,6 +180291,7 @@ function parseFlow(content) {
180115
180291
  steps
180116
180292
  };
180117
180293
  validateFlow(flow);
180294
+ if (version3 < FLOW_FILE_VERSION) olderFormatVersions.set(flow, version3);
180118
180295
  return flow;
180119
180296
  }
180120
180297
  var flowWriteSeq = 0;
@@ -180491,7 +180668,6 @@ var path59 = __toESM(require("node:path"));
180491
180668
  init_src2();
180492
180669
 
180493
180670
  // ../tool-server/src/tools/flows/flow-actions.ts
180494
- init_device_info();
180495
180671
  init_capability();
180496
180672
 
180497
180673
  // ../tool-server/src/tools/flows/flow-device.ts
@@ -180922,10 +181098,10 @@ function adaptFullHierarchy(raw, quotedLabel) {
180922
181098
  });
180923
181099
  if (!(screenW > 0 && screenH > 0)) return { tree };
180924
181100
  const uiOrientation = asUiOrientation(reportedScreen?.interfaceOrientation);
181101
+ if (!isTurned(uiOrientation)) return { tree, screen: { width: screenW, height: screenH } };
180925
181102
  return {
180926
- tree,
180927
- screen: { width: screenW, height: screenH },
180928
- ...uiOrientation ? { uiOrientation } : {}
181103
+ tree: nativeTreeToUi(tree, uiOrientation),
181104
+ screen: uiScreenSize({ width: screenW, height: screenH }, uiOrientation)
180929
181105
  };
180930
181106
  }
180931
181107
  var FLOW_TREE_MAX_DEPTH = 100;
@@ -181097,14 +181273,13 @@ async function queryFullHierarchyTree(registry2, device, target) {
181097
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`
181098
181274
  );
181099
181275
  }
181100
- const { tree, screen, uiOrientation } = adaptFullHierarchy(rawResult);
181276
+ const { tree, screen } = adaptFullHierarchy(rawResult);
181101
181277
  const quotableTree = secretTypedOn(device.id) ? adaptFullHierarchy(rawResult, (label) => redactTypedSecrets(device.id, label)).tree : void 0;
181102
181278
  return {
181103
181279
  tree,
181104
181280
  ...quotableTree ? { quotableTree } : {},
181105
181281
  source: "native-devtools",
181106
- ...screen ? { screen } : {},
181107
- ...uiOrientation ? { uiOrientation } : {}
181282
+ ...screen ? { screen } : {}
181108
181283
  };
181109
181284
  }
181110
181285
  function errMsg3(err) {
@@ -181559,25 +181734,22 @@ function selectorAlternatives(sel) {
181559
181734
  }
181560
181735
  return alts;
181561
181736
  }
181562
- function flowFindAll(tree, sel, orientation) {
181737
+ function flowFindAll(tree, sel) {
181563
181738
  let fallback = [];
181564
181739
  for (const s of selectorAlternatives(sel)) {
181565
- const matches2 = findAll(tree, s, orientation);
181740
+ const matches2 = findAll(tree, s);
181566
181741
  if (matches2.some(isVisible)) return matches2;
181567
181742
  if (fallback.length === 0) fallback = matches2;
181568
181743
  }
181569
181744
  return fallback;
181570
181745
  }
181571
- function flowSelectorToFrame(tree, sel, orientation) {
181746
+ function flowSelectorToFrame(tree, sel) {
181572
181747
  for (const s of selectorAlternatives(sel)) {
181573
- const frame2 = selectorToFrame(tree, s, orientation);
181748
+ const frame2 = selectorToFrame(tree, s);
181574
181749
  if (frame2) return frame2;
181575
181750
  }
181576
181751
  return void 0;
181577
181752
  }
181578
- function readingOrientation(env) {
181579
- return env.lastRead?.uiOrientation;
181580
- }
181581
181753
  function provenTreeOutage(env) {
181582
181754
  const proven = env.treeOutage?.proven;
181583
181755
  return proven && proven.deviceId === env.device.id ? proven.error : void 0;
@@ -181585,7 +181757,6 @@ function provenTreeOutage(env) {
181585
181757
  function readFlowTree(env) {
181586
181758
  return fetchFlowTree(env.registry, env.device, env.treeTarget).then((data) => {
181587
181759
  if (env.treeOutage) env.treeOutage.proven = void 0;
181588
- if (env.lastRead) env.lastRead.uiOrientation = data.uiOrientation;
181589
181760
  return data;
181590
181761
  });
181591
181762
  }
@@ -181634,10 +181805,7 @@ async function waitForFrames(env, selectors) {
181634
181805
  if (env.signal?.aborted) return "aborted";
181635
181806
  const tree = await settleTree(env);
181636
181807
  if (tree) {
181637
- const orientation = readingOrientation(env);
181638
- const frames = selectors.map(
181639
- (s) => s ? flowSelectorToFrame(tree, s, orientation) : void 0
181640
- );
181808
+ const frames = selectors.map((s) => s ? flowSelectorToFrame(tree, s) : void 0);
181641
181809
  const missing = pending.find(({ i }) => frames[i] === void 0);
181642
181810
  if (!missing) return frames;
181643
181811
  unresolved = missing.selector;
@@ -181681,9 +181849,9 @@ async function waitForFocus(env, into, tappedFrame) {
181681
181849
  for (; ; ) {
181682
181850
  if (env.signal?.aborted) return;
181683
181851
  try {
181684
- const { tree, source, uiOrientation } = await readFlowTree(env);
181852
+ const { tree, source } = await readFlowTree(env);
181685
181853
  if (!FOCUS_REPORTING_SOURCES.has(source)) return;
181686
- const target = flowSelectorToFrame(tree, into, uiOrientation) ?? tappedFrame;
181854
+ const target = flowSelectorToFrame(tree, into) ?? tappedFrame;
181687
181855
  if (collectFocused(tree, []).some((n) => framesOverlap(n.frame, target))) return;
181688
181856
  } catch {
181689
181857
  }
@@ -181740,14 +181908,12 @@ async function scrollToVisible(env, target, direction, within) {
181740
181908
  if (env.signal?.aborted) return { aborted: true };
181741
181909
  const tree = await settleTree(env);
181742
181910
  if (!tree) return { aborted: true };
181743
- const orientation = readingOrientation(env);
181744
- const axisDirection = nativeDirection(direction, orientation);
181745
- const region = within ? flowSelectorToFrame(tree, within, orientation) : FULL_SCREEN2;
181911
+ const region = within ? flowSelectorToFrame(tree, within) : FULL_SCREEN2;
181746
181912
  if (!region) {
181747
181913
  return { reason: `scroll container ${describeSelector(within)} is not visible` };
181748
181914
  }
181749
- const frame2 = flowSelectorToFrame(tree, target, orientation);
181750
- if (frame2 && axisFullyInside(frame2, axisDirection, region)) {
181915
+ const frame2 = flowSelectorToFrame(tree, target);
181916
+ if (frame2 && axisFullyInside(frame2, direction, region)) {
181751
181917
  return { frame: frame2, ...warnedBy(warning) };
181752
181918
  }
181753
181919
  const scope = within ? [region] : anchorScrollFrames(tree, getDescribeTapPoint(region));
@@ -181762,7 +181928,7 @@ async function scrollToVisible(env, target, direction, within) {
181762
181928
  }
181763
181929
  prevFp = fp;
181764
181930
  try {
181765
- warning ??= await scrollIncrement(env, axisDirection, region);
181931
+ warning ??= await scrollIncrement(env, direction, region);
181766
181932
  } catch (err) {
181767
181933
  if (!(err instanceof Error && NO_SCROLLABLE_VIEW.test(err.message))) throw err;
181768
181934
  if (frame2) return { frame: frame2, ...warnedBy(warning) };
@@ -181877,9 +182043,6 @@ function warnedBy(...warnings) {
181877
182043
  const text = warnings.filter((w) => w !== void 0).join(" ");
181878
182044
  return text.length > 0 ? { warning: text } : {};
181879
182045
  }
181880
- function unreadOrientationNote(orientation) {
181881
- 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.`;
181882
- }
181883
182046
  function unsettledGestureWarning(err) {
181884
182047
  const reason2 = err instanceof Error ? err.message : String(err);
181885
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.`;
@@ -182082,17 +182245,13 @@ async function runSwipe(env, step) {
182082
182245
  if ("fail" in p) return p.fail;
182083
182246
  toPoint = p;
182084
182247
  }
182085
- const orientation = env.lastRead?.uiOrientation;
182086
- if (settle3.warning !== void 0 && step.direction && isIosSimulator(env.device)) {
182087
- settle3 = { ...settle3, warning: `${settle3.warning} ${unreadOrientationNote(orientation)}` };
182088
- }
182089
182248
  let start2;
182090
182249
  if (step.from) {
182091
182250
  const p = targetPointFromFrame(step.from, fromFrame);
182092
182251
  if ("fail" in p) return p.fail;
182093
182252
  start2 = p;
182094
182253
  } else if (step.direction) {
182095
- start2 = uiPointToNative(SWIPE_GEOMETRY[step.direction].start, orientation);
182254
+ start2 = { ...SWIPE_GEOMETRY[step.direction].start };
182096
182255
  } else {
182097
182256
  start2 = { x: 0.5, y: 0.5 };
182098
182257
  }
@@ -182105,16 +182264,10 @@ async function runSwipe(env, step) {
182105
182264
  let end;
182106
182265
  if (step.direction) {
182107
182266
  const g = SWIPE_GEOMETRY[step.direction];
182108
- const travelVector = uiVectorToNative(
182109
- g.axis === "x" ? { x: g.end - g.start.x, y: 0 } : { x: 0, y: g.end - g.start.y },
182110
- orientation
182111
- );
182112
- 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;
182113
182269
  const startOnTravelAxis = start2[axis];
182114
- const endOnTravelAxis = step.from ? clamp014(startOnTravelAxis + travelVector[axis]) : uiPointToNative(
182115
- g.axis === "x" ? { x: g.end, y: g.start.y } : { x: g.start.x, y: g.end },
182116
- orientation
182117
- )[axis];
182270
+ const endOnTravelAxis = step.from ? clamp014(startOnTravelAxis + travelVector[axis]) : g.end;
182118
182271
  end = axis === "x" ? { x: endOnTravelAxis, y: start2.y } : { x: start2.x, y: endOnTravelAxis };
182119
182272
  const travel2 = Math.abs(endOnTravelAxis - startOnTravelAxis);
182120
182273
  if (travel2 < SWIPE_MIN_TRAVEL) {
@@ -182232,7 +182385,7 @@ async function waitForCondition(env, step, timeoutMs) {
182232
182385
  if (env.signal?.aborted) return ABORTED_OUTCOME;
182233
182386
  try {
182234
182387
  const data = await readFlowTree(env);
182235
- lastMatches = flowFindAll(data.tree, step.selector, data.uiOrientation);
182388
+ lastMatches = flowFindAll(data.tree, step.selector);
182236
182389
  lastData = data;
182237
182390
  fetchError = void 0;
182238
182391
  everMatched ||= lastMatches.length > 0;
@@ -182245,7 +182398,6 @@ async function waitForCondition(env, step, timeoutMs) {
182245
182398
  step.expectedText,
182246
182399
  lastMatches,
182247
182400
  step.textMatch,
182248
- data.uiOrientation,
182249
182401
  env.device.platform === "macos"
182250
182402
  )) {
182251
182403
  return { ok: true };
@@ -182298,9 +182450,6 @@ async function waitForCondition(env, step, timeoutMs) {
182298
182450
  step.expectedText,
182299
182451
  step.textMatch,
182300
182452
  lastMatches,
182301
- // The read `lastMatches` came from is the last one that answered, and
182302
- // only a read that answers writes the orientation.
182303
- readingOrientation(env),
182304
182453
  env.device.platform === "macos",
182305
182454
  // The text of an element is the only part of a reason that comes off
182306
182455
  // the screen, where a field shows a typed secret.
@@ -182524,7 +182673,7 @@ async function waitForIdle(env, step) {
182524
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
182525
182674
  };
182526
182675
  }
182527
- function assertReason(condition, selector, expectedText, textMatch, matches2, orientation, macos, quoted) {
182676
+ function assertReason(condition, selector, expectedText, textMatch, matches2, macos, quoted) {
182528
182677
  const sel = describeSelector(selector);
182529
182678
  switch (condition) {
182530
182679
  case "exists":
@@ -182534,7 +182683,7 @@ function assertReason(condition, selector, expectedText, textMatch, matches2, or
182534
182683
  case "hidden":
182535
182684
  return `an element matching ${sel} was still visible`;
182536
182685
  case "text": {
182537
- const first = textCheckTarget(matches2, orientation, macos);
182686
+ const first = textCheckTarget(matches2, macos);
182538
182687
  if (!first) return `no element matched selector ${sel}`;
182539
182688
  const wanted = describeTextExpectation(expectedText, textMatch, "infinitive");
182540
182689
  const shown = quoted(first, (node2) => macFieldText(node2, macos) ?? assertText(node2));
@@ -183377,13 +183526,13 @@ async function captureTapSelector(registry2, session, udid, point) {
183377
183526
  device,
183378
183527
  launched ? { bundleId: launched, pinned: false, probeAnswered: false } : void 0
183379
183528
  );
183380
- const { tree, uiOrientation } = data;
183529
+ const { tree } = data;
183381
183530
  const node2 = nodeAtPoint(tree, point);
183382
183531
  if (!node2) return { warning: "no element found under the tap; kept coordinates (brittle)" };
183383
183532
  const selector = deriveSelector(withoutTypedText(node2, data));
183384
183533
  if (!selector)
183385
183534
  return { warning: "tapped element has no stable text/id; kept coordinates (brittle)" };
183386
- const resolved = selectorToFrame(tree, selector, uiOrientation);
183535
+ const resolved = selectorToFrame(tree, selector);
183387
183536
  if (!resolved) {
183388
183537
  return {
183389
183538
  warning: `selector ${describeSelector(selector)} matches no element on this screen; kept coordinates (brittle)`
@@ -185629,6 +185778,67 @@ init_zod();
185629
185778
  var fs78 = __toESM(require("node:fs/promises"));
185630
185779
  var path64 = __toESM(require("node:path"));
185631
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
185632
185842
  init_device_info();
185633
185843
  init_capability();
185634
185844
 
@@ -185639,6 +185849,7 @@ var os24 = __toESM(require("node:os"));
185639
185849
  var path63 = __toESM(require("node:path"));
185640
185850
  var import_pngjs7 = __toESM(require_png());
185641
185851
  init_src2();
185852
+ init_device_info();
185642
185853
 
185643
185854
  // ../tool-server/src/tools/screenshot-diff/screenshot-diff.ts
185644
185855
  var import_promises20 = __toESM(require("fs/promises"));
@@ -186917,7 +187128,7 @@ function formatScreenshotDiffSummary(result) {
186917
187128
  const textChanges = result.textAnalysis?.status === "ok" ? mergeTextChangesForSummary(result.textAnalysis.changes) : [];
186918
187129
  const shownTextChanges = textChanges.slice(0, MAX_SUMMARY_TEXT_CHANGES);
186919
187130
  const shownRegions = result.regions.slice(0, MAX_SUMMARY_REGIONS);
186920
- const coordinateSpace = coordinateSpaceForSummary(result.imageSize);
187131
+ const coordinateSpace2 = coordinateSpaceForSummary(result.imageSize);
186921
187132
  const lines = ["Screenshot diff summary", "", "Overall:"];
186922
187133
  lines.push(statusLine(status));
186923
187134
  if (result.sizeNormalization) {
@@ -186956,7 +187167,7 @@ function formatScreenshotDiffSummary(result) {
186956
187167
  lines.push(`- None detected.`);
186957
187168
  } else {
186958
187169
  for (const change of shownTextChanges) {
186959
- lines.push(...formatTextChange(change, coordinateSpace));
187170
+ lines.push(...formatTextChange(change, coordinateSpace2));
186960
187171
  }
186961
187172
  }
186962
187173
  } else {
@@ -186975,7 +187186,7 @@ function formatScreenshotDiffSummary(result) {
186975
187186
  lines.push(`- None detected.`);
186976
187187
  } else {
186977
187188
  for (const [index, region] of shownRegions.entries()) {
186978
- lines.push(`- Region ${index + 1}: ${formatRegion(region, coordinateSpace)}`);
187189
+ lines.push(`- Region ${index + 1}: ${formatRegion(region, coordinateSpace2)}`);
186979
187190
  }
186980
187191
  }
186981
187192
  return lines.join("\n");
@@ -187007,8 +187218,8 @@ function describeMismatch(result) {
187007
187218
  const scope = result.regions.length <= 5 ? "localized" : "broad";
187008
187219
  return `${severity} ${scope} visual change`;
187009
187220
  }
187010
- function formatRegion(region, coordinateSpace) {
187011
- 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)}`;
187012
187223
  }
187013
187224
  function mergeTextChangesForSummary(changes) {
187014
187225
  const merged = [];
@@ -187047,36 +187258,36 @@ function sameBounds2(left, right) {
187047
187258
  function normalizeSummaryText(text) {
187048
187259
  return text?.replace(/\s+/g, " ").trim().toLocaleLowerCase("en-US") ?? "";
187049
187260
  }
187050
- function formatTextChange(change, coordinateSpace) {
187261
+ function formatTextChange(change, coordinateSpace2) {
187051
187262
  switch (change.kind) {
187052
187263
  case "moved":
187053
187264
  return [
187054
187265
  `- ${formatMovedLabel(change)}: ${formatQuotedText(change.text)}`,
187055
- ...formatMoveBounds(change, coordinateSpace),
187056
- change.delta ? ` - delta: ${formatDelta(change.delta, coordinateSpace)}` : void 0,
187266
+ ...formatMoveBounds(change, coordinateSpace2),
187267
+ change.delta ? ` - delta: ${formatDelta(change.delta, coordinateSpace2)}` : void 0,
187057
187268
  formatAppearanceDetail(change)
187058
187269
  ].filter((line) => Boolean(line));
187059
187270
  case "appeared":
187060
187271
  return [
187061
187272
  `- Appeared: ${formatQuotedText(change.text)}`,
187062
- change.currentBounds ? ` - at ${formatBounds(change.currentBounds, coordinateSpace)}` : void 0
187273
+ change.currentBounds ? ` - at ${formatBounds(change.currentBounds, coordinateSpace2)}` : void 0
187063
187274
  ].filter((line) => Boolean(line));
187064
187275
  case "disappeared":
187065
187276
  return [
187066
187277
  `- Disappeared: ${formatQuotedText(change.text)}`,
187067
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0
187278
+ change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}` : void 0
187068
187279
  ].filter((line) => Boolean(line));
187069
187280
  case "content_changed":
187070
187281
  return [
187071
187282
  `- Changed: ${formatQuotedText(change.baselineText)} -> ${formatQuotedText(change.currentText)}`,
187072
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0,
187073
- 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
187074
187285
  ].filter((line) => Boolean(line));
187075
187286
  case "font_changed":
187076
187287
  return [
187077
187288
  `- Restyled: ${formatQuotedText(change.text)}${formatAppearanceLabelSuffix(change)}`,
187078
- change.baselineBounds ? ` - from ${formatBounds(change.baselineBounds, coordinateSpace)}` : void 0,
187079
- 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
187080
187291
  ].filter((line) => Boolean(line));
187081
187292
  default:
187082
187293
  return [
@@ -187084,13 +187295,13 @@ function formatTextChange(change, coordinateSpace) {
187084
187295
  ];
187085
187296
  }
187086
187297
  }
187087
- function formatMoveBounds(change, coordinateSpace) {
187298
+ function formatMoveBounds(change, coordinateSpace2) {
187088
187299
  const parts2 = [];
187089
187300
  if (change.baselineBounds) {
187090
- parts2.push(` - from ${formatBounds(change.baselineBounds, coordinateSpace)}`);
187301
+ parts2.push(` - from ${formatBounds(change.baselineBounds, coordinateSpace2)}`);
187091
187302
  }
187092
187303
  if (change.currentBounds) {
187093
- parts2.push(` - to ${formatBounds(change.currentBounds, coordinateSpace)}`);
187304
+ parts2.push(` - to ${formatBounds(change.currentBounds, coordinateSpace2)}`);
187094
187305
  }
187095
187306
  return parts2;
187096
187307
  }
@@ -187138,17 +187349,17 @@ function coordinateSpaceForSummary(imageSize) {
187138
187349
  }
187139
187350
  return { imageSize };
187140
187351
  }
187141
- function formatBounds(bounds, coordinateSpace) {
187142
- if (!coordinateSpace) {
187352
+ function formatBounds(bounds, coordinateSpace2) {
187353
+ if (!coordinateSpace2) {
187143
187354
  return `x=${formatInteger(bounds.x)} y=${formatInteger(bounds.y)} w=${formatInteger(bounds.width)} h=${formatInteger(bounds.height)}`;
187144
187355
  }
187145
- 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)}`;
187146
187357
  }
187147
- function formatDelta(delta, coordinateSpace) {
187148
- if (!coordinateSpace) {
187358
+ function formatDelta(delta, coordinateSpace2) {
187359
+ if (!coordinateSpace2) {
187149
187360
  return `dx=${formatSignedNumber(delta.x)} dy=${formatSignedNumber(delta.y)} dw=${formatSignedNumber(delta.width)} dh=${formatSignedNumber(delta.height)}`;
187150
187361
  }
187151
- 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)}`;
187152
187363
  }
187153
187364
  function formatQuotedText(text) {
187154
187365
  if (!text) return '"[none]"';
@@ -187802,12 +188013,14 @@ async function runSnapshot(env, opts) {
187802
188013
  scale: 1,
187803
188014
  includeImageInContext: false
187804
188015
  });
187805
- const captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
188016
+ let captureWarned = shot.warning !== void 0 ? { warning: shot.warning } : {};
187806
188017
  const { w, h } = await pngDimensions(shot.image.hostPath);
187807
188018
  const cropSuffix = opts.cropOn === void 0 ? "" : `-crop-${(0, import_node_crypto19.createHash)("sha256").update(cropIdentity(opts.cropOn)).digest("hex").slice(0, 8)}`;
187808
- const snapshotKey = `${opts.name}__${authoringPlatform(env.device.platform)}-${w}x${h}${cropSuffix}`;
187809
- const key2 = `${snapshotKey}.png`;
187810
- 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);
187811
188024
  const priorApp = opts.seenKeys.get(snapshotKey);
187812
188025
  if (priorApp !== void 0 && priorApp !== opts.appIdentity) {
187813
188026
  return {
@@ -187891,12 +188104,32 @@ async function runSnapshot(env, opts) {
187891
188104
  artifacts: { baseline }
187892
188105
  };
187893
188106
  }
187894
- const stored = await opts.project.readFile(baselinePath).catch((err) => {
187895
- 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)) {
187896
188109
  throw err;
187897
188110
  }
187898
- throw new Error(`Could not read PNG at ${baselinePath}: ${err.message}`, { cause: err });
187899
- });
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
+ }
187900
188133
  if (stored === null) {
187901
188134
  return {
187902
188135
  ...captureWarned,
@@ -187959,7 +188192,7 @@ async function runSnapshot(env, opts) {
187959
188192
  });
187960
188193
  keepInOutputDir = result.contextDiffPath;
187961
188194
  }
187962
- return { status: "fail", reason: reason2, snapshotKey, artifacts };
188195
+ return { ...captureWarned, status: "fail", reason: reason2, snapshotKey, artifacts };
187963
188196
  } finally {
187964
188197
  await cleanupDiffDir(outputDir, keepInOutputDir);
187965
188198
  }
@@ -187975,6 +188208,32 @@ async function runSnapshot(env, opts) {
187975
188208
  }
187976
188209
  }
187977
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
+ }
187978
188237
 
187979
188238
  // ../tool-server/src/utils/status-bar.ts
187980
188239
  var import_node_child_process53 = require("node:child_process");
@@ -188749,9 +189008,6 @@ Without a link, every step kind runs.`,
188749
189008
  // its own, which is why that step spends this verdict rather than
188750
189009
  // inheriting whatever the sub-run proved.
188751
189010
  treeOutage: {},
188752
- // Same shape and sharing as `treeOutage`: what the last read said about
188753
- // the UI's orientation, for the directives that turn a direction.
188754
- lastRead: {},
188755
189011
  flowsDir,
188756
189012
  viaUpload,
188757
189013
  project,
@@ -188783,7 +189039,8 @@ Without a link, every step kind runs.`,
188783
189039
  await execSteps(state3, flow.steps, {
188784
189040
  runStack: seed,
188785
189041
  rootDisplay: rootEntry.display,
188786
- depth: 0
189042
+ depth: 0,
189043
+ legacyPoints: flowFormatVersion(flow) < 2
188787
189044
  });
188788
189045
  } finally {
188789
189046
  aborted2 = state3.signal?.aborted === true;
@@ -189115,7 +189372,10 @@ async function execSteps(state3, steps, scope) {
189115
189372
  state3.hoistedBootMs = void 0;
189116
189373
  }
189117
189374
  if (JSON.stringify(step).includes(SECRET_PLACEHOLDER_MARKER)) state3.secretTyped = true;
189118
- 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
+ );
189119
189379
  if (report.status !== "skip") report.durationMs = Date.now() - startedAt;
189120
189380
  if ((report.status === "fail" || report.status === "error") && !report.artifacts) {
189121
189381
  const screen = await captureFailureScreen(state3);
@@ -189293,7 +189553,10 @@ async function execRunStep(state3, step, scope) {
189293
189553
  await execSteps(
189294
189554
  state3,
189295
189555
  fragment.steps,
189296
- childScope(scope, { runStack: [...scope.runStack, { canonical, display }] })
189556
+ childScope(scope, {
189557
+ runStack: [...scope.runStack, { canonical, display }],
189558
+ legacyPoints: flowFormatVersion(fragment) < 2
189559
+ })
189297
189560
  );
189298
189561
  }
189299
189562
  function oneLineReason(text) {
@@ -189309,13 +189572,11 @@ async function runScriptStep(state3, step, scope) {
189309
189572
  });
189310
189573
  return outcome.reason === void 0 ? outcome : { ...outcome, reason: oneLineReason(outcome.reason) };
189311
189574
  }
189312
- var UI_TURNING_TOOLS = /* @__PURE__ */ new Set(["rotate", "fold"]);
189313
189575
  async function runFold(state3, step) {
189314
189576
  const { registry: registry2, ctx, signal } = state3;
189315
189577
  const device = deviceEnv(state3).device;
189316
189578
  if (signal?.aborted) return ABORTED_OUTCOME;
189317
189579
  if (state3.treeOutage) state3.treeOutage.proven = void 0;
189318
- if (state3.lastRead) state3.lastRead.uiOrientation = void 0;
189319
189580
  const args = bindDeviceArgs(registry2, "fold", device.id, {
189320
189581
  ...step.posture !== void 0 ? { posture: step.posture } : {},
189321
189582
  ...step.angle !== void 0 ? { angle: step.angle } : {}
@@ -189371,7 +189632,10 @@ async function execLeafStep(state3, step, index, scope) {
189371
189632
  case "pinch":
189372
189633
  case "rotate": {
189373
189634
  try {
189374
- 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(" ");
189375
189639
  if (r.aborted) return { ...base, status: "skip", reason: r.reason };
189376
189640
  if (!r.ok && r.indeterminate && (step.kind === "idle" || device !== null && !supportsFlowTree(device.platform))) {
189377
189641
  return { ...base, status: "error", reason: r.reason };
@@ -189380,7 +189644,7 @@ async function execLeafStep(state3, step, index, scope) {
189380
189644
  ...base,
189381
189645
  status: r.ok ? "pass" : "fail",
189382
189646
  reason: r.reason,
189383
- ...r.warning !== void 0 ? { warning: r.warning } : {}
189647
+ ...warning ? { warning } : {}
189384
189648
  };
189385
189649
  } catch (err) {
189386
189650
  return { ...base, status: "error", reason: errMsg5(err) };
@@ -189451,9 +189715,6 @@ async function execLeafStep(state3, step, index, scope) {
189451
189715
  if (isNestedOrchestratorTool(step.name) && state3.treeOutage) {
189452
189716
  state3.treeOutage.proven = void 0;
189453
189717
  }
189454
- if (UI_TURNING_TOOLS.has(step.name) && state3.lastRead) {
189455
- state3.lastRead.uiOrientation = void 0;
189456
- }
189457
189718
  let prepared;
189458
189719
  try {
189459
189720
  if (device?.platform === "macos") {
@@ -190405,7 +190666,7 @@ async function executeScreenshotDiffTool(services, params, options, captureScree
190405
190666
  });
190406
190667
  let summary = result.summary;
190407
190668
  for (const warning of new Set(warnings)) summary = `${summary}
190408
- - panel: ${warning}`;
190669
+ - capture: ${warning}`;
190409
190670
  if (result.dimensionMismatch) {
190410
190671
  const posture = await foldablePostureHint(
190411
190672
  params.udid,
@@ -190613,10 +190874,8 @@ async function captureLiveInput(params) {
190613
190874
  const destination = import_path9.default.join(params.outputDir, `${params.name}-${suffix}.live.png`);
190614
190875
  await import_promises22.default.mkdir(params.outputDir, { recursive: true });
190615
190876
  await import_promises22.default.copyFile(capture.path, destination);
190616
- return {
190617
- path: destination,
190618
- ...panel?.warning !== void 0 ? { warning: panel.warning } : {}
190619
- };
190877
+ const warning = [panel?.warning, capture.note].filter((w) => w !== void 0).join(" ");
190878
+ return { path: destination, ...warning ? { warning } : {} };
190620
190879
  }
190621
190880
 
190622
190881
  // ../tool-server/src/tools/variants/propose-variant.ts
@@ -191563,6 +191822,10 @@ function createRegistry() {
191563
191822
  const ref = axServiceRef(resolveDevice(udid));
191564
191823
  return registry2.resolveService(ref.urn, ref.options);
191565
191824
  });
191825
+ setUiOrientationSourceProvider((udid) => {
191826
+ const ref = axServiceRef(resolveDevice(udid));
191827
+ return registry2.resolveService(ref.urn, ref.options);
191828
+ });
191566
191829
  registry2.registerBlueprint(simulatorServerBlueprint);
191567
191830
  registry2.registerBlueprint(iosDeviceRunnerBlueprint);
191568
191831
  registry2.registerBlueprint(jsRuntimeDebuggerBlueprint);
@@ -191617,7 +191880,7 @@ function createRegistry() {
191617
191880
  registry2.registerTool(createDebuggerStatusTool(registry2));
191618
191881
  registry2.registerTool(debuggerEvaluateTool);
191619
191882
  registry2.registerTool(debuggerReloadMetroTool);
191620
- registry2.registerTool(createDebuggerComponentTreeTool(registry2));
191883
+ registry2.registerTool(createDebuggerComponentTreeTool());
191621
191884
  registry2.registerTool(debuggerInspectElementTool);
191622
191885
  registry2.registerTool(createDebuggerLogRegistryTool(registry2));
191623
191886
  registry2.registerTool(networkLogsTool);