peachsim 0.1.2241 → 0.1.2243

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.
Files changed (92) hide show
  1. package/cli/bridge-flow-runner.ts +10 -9
  2. package/cli/commands/flow.ts +4 -0
  3. package/cli/commands/inspect/settling.ts +496 -515
  4. package/cli/commands/platform.ts +2 -0
  5. package/dist-lib/agent-daemon-client.cjs +1 -1
  6. package/dist-lib/agent-events.cjs +1 -1
  7. package/dist-lib/attached-projects.cjs +1 -1
  8. package/dist-lib/auth/shared-session.cjs +1 -1
  9. package/dist-lib/backend-origin.cjs +1 -1
  10. package/dist-lib/beta.cjs +1 -1
  11. package/dist-lib/beta.mjs +1 -1
  12. package/dist-lib/bridge-constants.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.cjs +1 -1
  14. package/dist-lib/bridge-contract-input.mjs +1 -1
  15. package/dist-lib/bridge-contract.cjs +1 -1
  16. package/dist-lib/bridge-contract.mjs +1 -1
  17. package/dist-lib/bundle-channel.cjs +115 -28
  18. package/dist-lib/capture-contract.cjs +1 -1
  19. package/dist-lib/capture-contract.mjs +1 -1
  20. package/dist-lib/cloud-contract.cjs +1 -1
  21. package/dist-lib/cloud-contract.mjs +1 -1
  22. package/dist-lib/cloud-test-args.cjs +1 -1
  23. package/dist-lib/cloud-test-args.mjs +1 -1
  24. package/dist-lib/cloud.cjs +1 -1
  25. package/dist-lib/cloud.mjs +1 -1
  26. package/dist-lib/config.cjs +1 -1
  27. package/dist-lib/config.mjs +1 -1
  28. package/dist-lib/detox/index.cjs +498 -518
  29. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  30. package/dist-lib/expo-swift-bundle.cjs +114 -27
  31. package/dist-lib/expo-swift-metadata.cjs +1 -1
  32. package/dist-lib/expo-swift-metadata.mjs +1 -1
  33. package/dist-lib/home-paths.cjs +1 -1
  34. package/dist-lib/host/bridge-host.cjs +122 -40
  35. package/dist-lib/host/fetch-proxy-handler.cjs +3 -3
  36. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  37. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  38. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  39. package/dist-lib/host/websocket-proxy.cjs +1 -1
  40. package/dist-lib/index.cjs +496 -516
  41. package/dist-lib/jump-to-source-babel.cjs +1 -1
  42. package/dist-lib/jump-to-source-native.cjs +1 -1
  43. package/dist-lib/kotlin-host.cjs +1 -1
  44. package/dist-lib/menu.cjs +1 -1
  45. package/dist-lib/menu.mjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  47. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  48. package/dist-lib/metro-production-bundle.cjs +1 -1
  49. package/dist-lib/metro-production-bundle.mjs +1 -1
  50. package/dist-lib/metro.cjs +3 -3
  51. package/dist-lib/native-app-identity-project.cjs +2 -2
  52. package/dist-lib/native-app-identity-project.mjs +2 -2
  53. package/dist-lib/native-app-identity.cjs +1 -1
  54. package/dist-lib/native-app-identity.mjs +1 -1
  55. package/dist-lib/native-firebase-metadata.cjs +1 -1
  56. package/dist-lib/native-firebase-metadata.mjs +1 -1
  57. package/dist-lib/pdfium-raster.cjs +1 -1
  58. package/dist-lib/pdfium-raster.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/public-origins-lib-esm.json +24 -24
  64. package/dist-lib/public-origins-lib.json +53 -53
  65. package/dist-lib/react-native-host-modules.cjs +1 -1
  66. package/dist-lib/react-native-host-modules.mjs +1 -1
  67. package/dist-lib/reap-browser.cjs +1 -1
  68. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  69. package/dist-lib/sdk.cjs +492 -512
  70. package/dist-lib/sdk.mjs +492 -512
  71. package/dist-lib/skills.cjs +632 -569
  72. package/dist-lib/swift-compile.cjs +13 -4
  73. package/dist-lib/swift-compile.mjs +13 -4
  74. package/dist-lib/swift-package.cjs +1 -1
  75. package/dist-lib/swift-package.mjs +1 -1
  76. package/dist-lib/swift-submit.cjs +2 -2
  77. package/dist-lib/swift-submit.mjs +2 -2
  78. package/dist-lib/swift-toolchain.cjs +1 -1
  79. package/dist-lib/swift.cjs +1 -1
  80. package/dist-lib/vite-swift.cjs +507 -419
  81. package/dist-lib/vite.cjs +3 -3
  82. package/dist-lib/worklet-executable.cjs +1 -1
  83. package/dist-lib/worklet-executable.mjs +1 -1
  84. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +3 -0
  85. package/kotlin/sdk.tar.gz +0 -0
  86. package/package.json +1 -1
  87. package/src/host/bridge-host.ts +12 -13
  88. package/src/native-static-libraries.ts +98 -17
  89. package/src/swift-shared-sdk.ts +6 -1
  90. package/src/swift-standins.ts +11 -4
  91. package/src/swift-submit.ts +3 -1
  92. package/src/swift-wasm-prune.ts +28 -0
@@ -21,10 +21,11 @@ export type WaitForSootsimIdleOptions = {
21
21
  // in fewer polls instead of paying the count at its slower rate.
22
22
  stablePolls?: number
23
23
  strict?: boolean
24
- // compare consecutive full-screen pixels; explicit animation waits use this.
25
- // frame publications and caret blinks do not require a continuous window.
26
- paintStill?: boolean
27
- // native maestro ios: pixel stability first, then native hierarchy equality.
24
+ // settle when nothing on screen moves: visible motion, including loops and
25
+ // low-priority animations, mounts, commits and hierarchy changes all count.
26
+ // the engine knows each of these, so no wait reads presented pixels.
27
+ screenStill?: boolean
28
+ // native maestro ios: screen stability first, then native hierarchy equality.
28
29
  maestro?: boolean
29
30
  // settle on motion alone, for the waits around a gesture: image loads and
30
31
  // network traffic move nothing on screen. it waits on pushed render
@@ -200,7 +201,7 @@ export async function waitForSootsimIdle({
200
201
  pollMs = 50,
201
202
  stablePolls = 3,
202
203
  strict = false,
203
- paintStill = false,
204
+ screenStill = false,
204
205
  maestro = false,
205
206
  motionOnly = false,
206
207
  readyPlayback = false,
@@ -243,7 +244,7 @@ export async function waitForSootsimIdle({
243
244
  let deadline = start + budgetMs
244
245
  const pollMs = ${Math.max(1, Math.round(pollMs))}
245
246
  const strict = ${strict ? 'true' : 'false'}
246
- const paintStill = ${paintStill ? 'true' : 'false'}
247
+ const screenStill = ${screenStill ? 'true' : 'false'}
247
248
  const maestro = ${maestro ? 'true' : 'false'}
248
249
  const accessibilityBounds = ${accessibilityBounds.toString()}
249
250
  const sameNativeAccessibilityShape = ${sameNativeAccessibilityShape.toString()}
@@ -253,550 +254,530 @@ export async function waitForSootsimIdle({
253
254
  // tight budgets (auto-wait) settle on worker stillness plus root
254
255
  // membership, generous ones confirm the geometry too.
255
256
  const fullGeometry = ${!maestro && maxMs >= 1000 ? 'true' : 'false'}
256
- const requiredStillMs = paintStill ? 0 : ${Math.max(1, Math.round(stablePolls)) * Math.max(1, Math.round(pollMs))}
257
- const minimumStablePolls = paintStill ? 1 : ${Math.min(2, Math.max(1, Math.round(stablePolls)))}
258
- const composite = paintStill ? globalThis.SootSim?.bridges?.liveComposite : null
259
- if (paintStill && !composite) {
260
- return { settled: false, elapsed: clockNow() - start, blockedBy: 'screen pixels unavailable' }
261
- }
262
- // subscribe to presented frames; authoritative screenshots force a
263
- // worker render, which changes the very counter we used to inspect.
264
- // pixels only decide stillness once motion and layout work drain, so the
265
- // subscription holds only then: a headless host otherwise reads back
266
- // every motion frame for a comparison that cannot pass.
267
- let unsubscribe = null
257
+ const requiredStillMs = screenStill ? 0 : ${Math.max(1, Math.round(stablePolls)) * Math.max(1, Math.round(pollMs))}
258
+ const minimumStablePolls = screenStill ? 1 : ${Math.min(2, Math.max(1, Math.round(stablePolls)))}
268
259
  let transitionEndedAt = null
269
- let pixelFrameToken = -1
270
- let screenPixels = null
271
260
  // the hierarchy read last taken and the geometry revision it answered.
272
261
  // it outlives this wait: a revision still current when a later wait
273
262
  // polls names the same geometry, so a step that follows a settled one
274
263
  // proves an unchanged screen without walking the tree again.
275
264
  const geometry = (globalThis.__peachSettleGeometry ??= { revision: null, hierarchy: null })
276
- try {
277
-
278
- // discover transitions while observing layout. when motion starts,
279
- // observations from before its completion cannot prove the new screen;
280
- // those that began after it drained still can. a loaded host runs a
281
- // push past a tap's budget, so the transition gets its own timeout and
282
- // the budget restarts once it drains.
283
- let transitionWait = (async () => {
284
- try {
285
- const wfst = globalThis.__sootsimTest?.waitForScreenTransitions
286
- if (typeof wfst === 'function' && budgetMs > 120) {
287
- const transition = await wfst({
288
- timeoutMs: ${Math.max(0, Math.round(transitionTimeoutMs))},
289
- settleMs: 64,
290
- startWindowMs: ${Math.max(0, Math.round(transitionStartWindowMs))},
291
- })
292
- if (transition?.started !== true) return false
293
- // a loaded worker replies long after the motion stopped; it
294
- // reports how long ago, so polls begun since still count. a
295
- // runtime without the field ends the transition at the reply.
296
- const rested = typeof transition.restedMs === 'number' ? Math.max(0, transition.restedMs) : 0
297
- transitionEndedAt = clockNow() - rested
298
- deadline = Math.max(deadline, transitionEndedAt + budgetMs)
299
- return true
300
- }
301
- } catch {}
302
- return false
303
- })()
265
+ // discover transitions while observing layout. when motion starts,
266
+ // observations from before its completion cannot prove the new screen;
267
+ // those that began after it drained still can. a loaded host runs a
268
+ // push past a tap's budget, so the transition gets its own timeout and
269
+ // the budget restarts once it drains.
270
+ let transitionWait = (async () => {
271
+ try {
272
+ const wfst = globalThis.__sootsimTest?.waitForScreenTransitions
273
+ if (typeof wfst === 'function' && budgetMs > 120) {
274
+ const transition = await wfst({
275
+ timeoutMs: ${Math.max(0, Math.round(transitionTimeoutMs))},
276
+ settleMs: 64,
277
+ startWindowMs: ${Math.max(0, Math.round(transitionStartWindowMs))},
278
+ })
279
+ if (transition?.started !== true) return false
280
+ // a loaded worker replies long after the motion stopped; it
281
+ // reports how long ago, so polls begun since still count. a
282
+ // runtime without the field ends the transition at the reply.
283
+ const rested = typeof transition.restedMs === 'number' ? Math.max(0, transition.restedMs) : 0
284
+ transitionEndedAt = clockNow() - rested
285
+ deadline = Math.max(deadline, transitionEndedAt + budgetMs)
286
+ return true
287
+ }
288
+ } catch {}
289
+ return false
290
+ })()
304
291
 
305
- // a worker that cannot answer within the remaining budget is busy, not
306
- // idle: its poll reads as unsettled. bounding each read by the budget
307
- // keeps a busy worker from holding a poll past the deadline.
308
- const BUSY = { busy: true }
309
- const answer = (read) =>
310
- Promise.race([
311
- Promise.resolve().then(read),
312
- new Promise((resolve) =>
313
- setTimeout(() => resolve(BUSY), Math.max(deadline - clockNow(), 100)),
314
- ),
315
- ])
292
+ // a worker that cannot answer within the remaining budget is busy, not
293
+ // idle: its poll reads as unsettled. bounding each read by the budget
294
+ // keeps a busy worker from holding a poll past the deadline.
295
+ const BUSY = { busy: true }
296
+ const answer = (read) =>
297
+ Promise.race([
298
+ Promise.resolve().then(read),
299
+ new Promise((resolve) =>
300
+ setTimeout(() => resolve(BUSY), Math.max(deadline - clockNow(), 100)),
301
+ ),
302
+ ])
316
303
 
317
- const readSnapshot = async () => {
318
- let animating = false
319
- let animatingBy = ''
320
- let layoutDirty = false
321
- let pendingFetches = 0
322
- let workerBusy = false
323
- let requestTotal = 0
324
- let requestInFlight = 0
325
- let appCommits = null
326
- let nodeCount = null
327
- let renderStatsAvailable = false
328
- let shellAnimating = false
329
- let shellBlockers = ''
330
- let webViewStarting = false
331
- let webViewBlocker = ''
332
- // the reads are independent, so they run concurrently: a loaded sim
333
- // answers each one late, and a poll that waits for them in turn
334
- // costs their sum, which fits too few polls in the budget to settle.
335
- // the window node count is the exception: it launches after the
336
- // motion read, so a poll motion already fails skips that walk.
337
- // strict reads also wait out shell motion. pixel reads inspect finite
338
- // animations in both realms: a worklet can move the app while the
339
- // tenant's basic animation flag and last presented pixels read still.
340
- const accessibilityRead = maestro
341
- ? answer(() => globalThis.__sootsimTest.captureAccessibilityTree()).catch(() => null)
342
- : null
343
- const motionRead = strict || paintStill
344
- ? answer(() => globalThis.__sootsimTest?.listAnimations?.()).catch(() => null)
304
+ const readSnapshot = async () => {
305
+ let animating = false
306
+ let animatingBy = ''
307
+ let layoutDirty = false
308
+ let pendingFetches = 0
309
+ let workerBusy = false
310
+ let requestTotal = 0
311
+ let requestInFlight = 0
312
+ let appCommits = null
313
+ let nodeCount = null
314
+ let renderStatsAvailable = false
315
+ let shellAnimating = false
316
+ let shellBlockers = ''
317
+ let webViewStarting = false
318
+ let webViewBlocker = ''
319
+ let visibleMotion = false
320
+ let visibleMotionBy = ''
321
+ let motionUnavailable = false
322
+ // the reads are independent, so they run concurrently: a loaded sim
323
+ // answers each one late, and a poll that waits for them in turn
324
+ // costs their sum, which fits too few polls in the budget to settle.
325
+ // the window node count is the exception: it launches after the
326
+ // motion read, so a poll motion already fails skips that walk.
327
+ // strict reads also wait out shell motion. pixel reads inspect finite
328
+ // animations in both realms: a worklet can move the app while the
329
+ // tenant's basic animation flag and last presented pixels read still.
330
+ const accessibilityRead = maestro
331
+ ? answer(() => globalThis.__sootsimTest.captureAccessibilityTree()).catch(() => null)
332
+ : null
333
+ const motionRead = strict || screenStill
334
+ ? answer(() => globalThis.__sootsimTest?.listAnimations?.()).catch(() => null)
335
+ : null
336
+ const statsRead = answer(() => globalThis.__sootsimRenderHost?.queryStats?.()).catch(() => null)
337
+ // image preparation ends in the tenant before the compositor decodes
338
+ // and realizes its pixels. both owners must finish before settling.
339
+ // the compositor rejects a stats request it is too busy to answer.
340
+ const compositorRead = answer(() => globalThis.__sootsimCompositor.getStats({ detail: 'readiness' })).catch(() => BUSY)
341
+ const countsRead = answer(() => globalThis.__sootsimTest?.getRequestCounts?.()).catch(() => null)
342
+ // the mounted hierarchy in render-worker mode comes from the test
343
+ // bridge: globalThis.__sootsimRoot is an empty placeholder there, so a
344
+ // walk over it hashes every screen to the same empty string while
345
+ // it moves. listInspectable is the worker-backed read describe
346
+ // uses; a worker too busy to answer it reads as unsettled. tight
347
+ // budgets skip this read and settle on the cheaper signals above.
348
+ // it walks every node, so a poll whose geometry revision matches the
349
+ // last read, in this wait or an earlier one, reuses that read.
350
+ const hierarchyRead =
351
+ fullGeometry && typeof globalThis.__sootsimTest?.listInspectable === 'function'
352
+ ? answer(() => globalThis.__sootsimTest.getGeometryRevision?.())
353
+ .catch(() => null)
354
+ .then((revision) => {
355
+ if (revision === BUSY) return BUSY
356
+ if (typeof revision === 'string' && geometry.revision === revision) return geometry.hierarchy
357
+ return answer(() => globalThis.__sootsimTest.listInspectable({}))
358
+ .catch(() => null)
359
+ .then((hierarchy) => {
360
+ const kept = typeof revision === 'string' && Array.isArray(hierarchy)
361
+ geometry.revision = kept ? revision : null
362
+ geometry.hierarchy = kept ? hierarchy : null
363
+ return hierarchy
364
+ })
365
+ })
345
366
  : null
346
- const statsRead = answer(() => globalThis.__sootsimRenderHost?.queryStats?.()).catch(() => null)
347
- // image preparation ends in the tenant before the compositor decodes
348
- // and realizes its pixels. both owners must finish before settling.
349
- // the compositor rejects a stats request it is too busy to answer.
350
- const compositorRead = answer(() => globalThis.__sootsimCompositor.getStats({ detail: 'readiness' })).catch(() => BUSY)
351
- const countsRead = answer(() => globalThis.__sootsimTest?.getRequestCounts?.()).catch(() => null)
352
- // the mounted hierarchy in render-worker mode comes from the test
353
- // bridge: globalThis.__sootsimRoot is an empty placeholder there, so a
354
- // walk over it hashes every screen to the same empty string while
355
- // it moves. listInspectable is the worker-backed read describe
356
- // uses; a worker too busy to answer it reads as unsettled. tight
357
- // budgets skip this read and settle on the cheaper signals above.
358
- // it walks every node, so a poll whose geometry revision matches the
359
- // last read, in this wait or an earlier one, reuses that read.
360
- const hierarchyRead =
361
- fullGeometry && typeof globalThis.__sootsimTest?.listInspectable === 'function'
362
- ? answer(() => globalThis.__sootsimTest.getGeometryRevision?.())
363
- .catch(() => null)
364
- .then((revision) => {
365
- if (revision === BUSY) return BUSY
366
- if (typeof revision === 'string' && geometry.revision === revision) return geometry.hierarchy
367
- return answer(() => globalThis.__sootsimTest.listInspectable({}))
368
- .catch(() => null)
369
- .then((hierarchy) => {
370
- const kept = typeof revision === 'string' && Array.isArray(hierarchy)
371
- geometry.revision = kept ? revision : null
372
- geometry.hierarchy = kept ? hierarchy : null
373
- return hierarchy
374
- })
375
- })
376
- : null
377
- if (motionRead) {
378
- const motion = await motionRead
379
- if (motion === BUSY) workerBusy = true
380
- else if (Array.isArray(motion)) {
381
- const blocking = motion.filter((anim) =>
382
- (anim.realm === 'shell' || paintStill) &&
383
- anim.priority !== 'low' && anim.visible !== false &&
384
- (!paintStill || anim.loop !== true))
385
- shellAnimating = blocking.length > 0
386
- // name what holds the settle so a timeout points at its owner.
387
- shellBlockers = blocking
388
- .slice(0, 4)
389
- .map((anim) => anim.source + '/' + anim.kind + '#' + anim.id + ' at ' + anim.current + (anim.loop ? ' loop' : ''))
390
- .join(', ')
391
- }
392
- }
393
- const stats = await statsRead
394
- if (stats === BUSY) {
367
+ if (motionRead) {
368
+ const motion = await motionRead
369
+ if (motion === BUSY) workerBusy = true
370
+ else if (Array.isArray(motion)) {
371
+ const blocking = motion.filter((anim) =>
372
+ (anim.realm === 'shell' || screenStill) &&
373
+ anim.priority !== 'low' && anim.visible !== false &&
374
+ (!screenStill || anim.loop !== true))
375
+ shellAnimating = blocking.length > 0
376
+ // what blocking leaves out still moves the screen while visible;
377
+ // it ends a screen-still wait only at maestro's hierarchy check
378
+ // or the deadline, as a screen that never holds still does on ios.
379
+ const moving = screenStill
380
+ ? motion.filter((anim) => anim.visible !== false && !blocking.includes(anim))
381
+ : []
382
+ visibleMotion = moving.length > 0
383
+ visibleMotionBy = moving
384
+ .slice(0, 4)
385
+ .map((anim) => anim.source + '/' + anim.kind + '#' + anim.id + (anim.loop ? ' loop' : '') + (anim.priority === 'low' ? ' low' : ''))
386
+ .join(', ')
387
+ // name what holds the settle so a timeout points at its owner.
388
+ shellBlockers = blocking
389
+ .slice(0, 4)
390
+ .map((anim) => anim.source + '/' + anim.kind + '#' + anim.id + ' at ' + anim.current + (anim.loop ? ' loop' : ''))
391
+ .join(', ')
392
+ } else if (screenStill) {
393
+ motionUnavailable = true
395
394
  workerBusy = true
396
- } else if (!stats && readyPlayback) {
397
- workerBusy = true
398
- } else if (stats) {
399
- renderStatsAvailable = true
400
- const missingFields = ['hasActiveBlockingNativeAnimations', 'hasPendingBlockingAnimationFrames']
401
- .filter((field) => typeof stats[field] !== 'boolean')
402
- if (readyPlayback && typeof stats.hasPendingReadinessAnimationFrames !== 'boolean') missingFields.push('hasPendingReadinessAnimationFrames')
403
- if ((strict || readyPlayback) && missingFields.length > 0) {
404
- return {
405
- runtimeUnsupported: {
406
- error: 'runtime_readiness_unsupported',
407
- runtimeVersion: globalThis.__sootsimRuntimeVersion || 'unknown',
408
- missingFields,
409
- },
410
- }
411
- }
412
- // positive checks only: an older runtime without the blocking
413
- // fields reads as still, and strict rejects that runtime above
414
- // instead of ever settling on unknown motion.
415
- animating =
416
- stats.hasActiveAnims === true ||
417
- stats.hasActiveBlockingNativeAnimations === true ||
418
- (!paintStill && (readyPlayback ? stats.hasPendingReadinessAnimationFrames : stats.hasPendingBlockingAnimationFrames) === true)
419
- if (animating)
420
- animatingBy = [
421
- stats.hasActiveAnims === true && 'activeAnims',
422
- stats.hasActiveBlockingNativeAnimations === true && 'blockingNative',
423
- !paintStill && stats.hasPendingBlockingAnimationFrames === true && 'pendingFrames',
424
- !paintStill && stats.hasPendingReadinessAnimationFrames === true && 'pendingReadinessFrames',
425
- ].filter(Boolean).join('+')
426
- // the runtime reports only layout work that can reach the window:
427
- // a covered screen or inactive tab committing does not hold it.
428
- layoutDirty =
429
- stats.layoutDirty === true && stats.renderRequested === true
430
- // a freshly-pushed screen showing a skeleton is layout-stable
431
- // but not actually settled — its data/images are still in
432
- // flight. treat bounded image-loader fetches as not-idle so
433
- // settle waits for real content, capped by the budget.
434
- const pf = stats.memory && stats.memory.imageLoader
435
- ? stats.memory.imageLoader.pendingFetches
436
- : 0
437
- pendingFetches = typeof pf === 'number' ? pf : 0
438
- // tenant layout commits: a screen that keeps committing is still
439
- // mounting or remounting, even with no animation flag raised.
440
- appCommits = typeof stats.appCommitCount === 'number' ? stats.appCommitCount : null
441
395
  }
442
- // mounted-root membership: the count of nodes that can reach the
443
- // window moves while the screen mounts, unmounts or recycles, in
444
- // either render mode. a screen a pushed one covers or an inactive
445
- // tab stays mounted out of the window, so what it mounts is not
446
- // screen motion. the worker rebuilds the membership set while the
447
- // wire moves on every animated frame, so a poll the motion read
448
- // already fails skips it: the motion flags alone prove this poll
449
- // unsettled, and the carried count hands the first still poll the
450
- // pre-motion baseline to compare against.
451
- const motionStill = !workerBusy && !animating && !layoutDirty && !shellAnimating
452
- const nodeCountRead = motionStill
453
- ? answer(() => globalThis.__sootsimTest?.getWindowNodeCount?.()).catch(() => null)
454
- : null
455
- const compositor = await compositorRead
456
- if (compositor === BUSY) {
457
- workerBusy = true
458
- } else {
459
- pendingFetches += compositor.images.pendingFetches
460
- pendingFetches += compositor.imageRealization.pending
461
- if (compositor.webViewCaptureSettled === false) {
462
- webViewStarting = true
463
- webViewBlocker = 'compositor webView capture not settled'
396
+ }
397
+ const stats = await statsRead
398
+ if (stats === BUSY) {
399
+ workerBusy = true
400
+ } else if (!stats && readyPlayback) {
401
+ workerBusy = true
402
+ } else if (stats) {
403
+ renderStatsAvailable = true
404
+ const missingFields = ['hasActiveBlockingNativeAnimations', 'hasPendingBlockingAnimationFrames']
405
+ .filter((field) => typeof stats[field] !== 'boolean')
406
+ if (readyPlayback && typeof stats.hasPendingReadinessAnimationFrames !== 'boolean') missingFields.push('hasPendingReadinessAnimationFrames')
407
+ if ((strict || readyPlayback) && missingFields.length > 0) {
408
+ return {
409
+ runtimeUnsupported: {
410
+ error: 'runtime_readiness_unsupported',
411
+ runtimeVersion: globalThis.__sootsimRuntimeVersion || 'unknown',
412
+ missingFields,
413
+ },
464
414
  }
465
415
  }
466
- const counts = await countsRead
467
- if (counts === BUSY) workerBusy = true
468
- // <Image> loads are left to the image loader, which counts only those
469
- // that can reach the window. a runtime older than the CLI reports none.
470
- const imageLoads = counts?.imageLoads ?? { total: 0, inFlight: 0 }
471
- requestTotal = typeof counts?.total === 'number' ? counts.total - imageLoads.total : 0
472
- requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight - imageLoads.inFlight : 0
473
- // a skipped read carries the last count: mounts during motion still
474
- // break the first still poll after it, instead of a blank baseline
475
- // reading them as stable.
476
- const total = nodeCountRead ? await nodeCountRead : lastNodeCount
477
- if (total === BUSY) workerBusy = true
478
- nodeCount = typeof total === 'number' ? total : null
479
- const accessibility = accessibilityRead ? await accessibilityRead : null
480
- const nativeHierarchy = Array.isArray(accessibility) && accessibility.length > 0
481
- ? accessibility
482
- : null
483
- if (accessibility === BUSY) workerBusy = true
484
- let hierarchy = hierarchyRead ? await hierarchyRead : null
485
- if (hierarchy === BUSY) {
486
- workerBusy = true
487
- hierarchy = null
488
- } else if (!Array.isArray(hierarchy)) {
489
- hierarchy = null
416
+ // positive checks only: an older runtime without the blocking
417
+ // fields reads as still, and strict rejects that runtime above
418
+ // instead of ever settling on unknown motion.
419
+ animating =
420
+ stats.hasActiveAnims === true ||
421
+ stats.hasActiveBlockingNativeAnimations === true ||
422
+ (!screenStill && (readyPlayback ? stats.hasPendingReadinessAnimationFrames : stats.hasPendingBlockingAnimationFrames) === true)
423
+ if (animating)
424
+ animatingBy = [
425
+ stats.hasActiveAnims === true && 'activeAnims',
426
+ stats.hasActiveBlockingNativeAnimations === true && 'blockingNative',
427
+ !screenStill && stats.hasPendingBlockingAnimationFrames === true && 'pendingFrames',
428
+ !screenStill && stats.hasPendingReadinessAnimationFrames === true && 'pendingReadinessFrames',
429
+ ].filter(Boolean).join('+')
430
+ // the runtime reports only layout work that can reach the window:
431
+ // a covered screen or inactive tab committing does not hold it.
432
+ layoutDirty =
433
+ stats.layoutDirty === true && stats.renderRequested === true
434
+ // a freshly-pushed screen showing a skeleton is layout-stable
435
+ // but not actually settled — its data/images are still in
436
+ // flight. treat bounded image-loader fetches as not-idle so
437
+ // settle waits for real content, capped by the budget.
438
+ const pf = stats.memory && stats.memory.imageLoader
439
+ ? stats.memory.imageLoader.pendingFetches
440
+ : 0
441
+ pendingFetches = typeof pf === 'number' ? pf : 0
442
+ // tenant layout commits: a screen that keeps committing is still
443
+ // mounting or remounting, even with no animation flag raised.
444
+ appCommits = typeof stats.appCommitCount === 'number' ? stats.appCommitCount : null
445
+ }
446
+ // mounted-root membership: the count of nodes that can reach the
447
+ // window moves while the screen mounts, unmounts or recycles, in
448
+ // either render mode. a screen a pushed one covers or an inactive
449
+ // tab stays mounted out of the window, so what it mounts is not
450
+ // screen motion. the worker rebuilds the membership set while the
451
+ // wire moves on every animated frame, so a poll the motion read
452
+ // already fails skips it: the motion flags alone prove this poll
453
+ // unsettled, and the carried count hands the first still poll the
454
+ // pre-motion baseline to compare against.
455
+ const motionStill = !workerBusy && !animating && !layoutDirty && !shellAnimating
456
+ const nodeCountRead = motionStill
457
+ ? answer(() => globalThis.__sootsimTest?.getWindowNodeCount?.()).catch(() => null)
458
+ : null
459
+ const compositor = await compositorRead
460
+ if (compositor === BUSY) {
461
+ workerBusy = true
462
+ } else {
463
+ pendingFetches += compositor.images.pendingFetches
464
+ pendingFetches += compositor.imageRealization.pending
465
+ if (compositor.webViewCaptureSettled === false) {
466
+ webViewStarting = true
467
+ webViewBlocker = 'compositor webView capture not settled'
490
468
  }
491
- const nodes = []
492
- // identity beside each geometry entry, from the rows already read,
493
- // so a changed layout can name the nodes that moved.
494
- const nodeRows = []
495
- const LOADING_TEXT_REGEX = /^(creating webview|loading html|fetching bundle|waiting for first render|starting preview|loading simulator|fetching app code|waiting for native preview|starting design|loading canvas|fetching screens|painting the canvas|waiting for webview|waiting for preview|waiting for canvas|preview stalled)/i
496
- const noteLoading = (state, text) => {
497
- if (state?.busy === true) {
498
- webViewStarting = true
499
- if (!webViewBlocker) webViewBlocker = 'accessibility busy state active'
500
- }
501
- if (typeof text === 'string' && LOADING_TEXT_REGEX.test(text.trim())) {
502
- webViewStarting = true
503
- if (!webViewBlocker) webViewBlocker = 'webView startup in progress ("' + text.trim() + '")'
469
+ }
470
+ const counts = await countsRead
471
+ if (counts === BUSY) workerBusy = true
472
+ // <Image> loads are left to the image loader, which counts only those
473
+ // that can reach the window. a runtime older than the CLI reports none.
474
+ const imageLoads = counts?.imageLoads ?? { total: 0, inFlight: 0 }
475
+ requestTotal = typeof counts?.total === 'number' ? counts.total - imageLoads.total : 0
476
+ requestInFlight = typeof counts?.inFlight === 'number' ? counts.inFlight - imageLoads.inFlight : 0
477
+ // a skipped read carries the last count: mounts during motion still
478
+ // break the first still poll after it, instead of a blank baseline
479
+ // reading them as stable.
480
+ const total = nodeCountRead ? await nodeCountRead : lastNodeCount
481
+ if (total === BUSY) workerBusy = true
482
+ nodeCount = typeof total === 'number' ? total : null
483
+ const accessibility = accessibilityRead ? await accessibilityRead : null
484
+ const nativeHierarchy = Array.isArray(accessibility) && accessibility.length > 0
485
+ ? accessibility
486
+ : null
487
+ if (accessibility === BUSY) workerBusy = true
488
+ let hierarchy = hierarchyRead ? await hierarchyRead : null
489
+ if (hierarchy === BUSY) {
490
+ workerBusy = true
491
+ hierarchy = null
492
+ } else if (!Array.isArray(hierarchy)) {
493
+ hierarchy = null
494
+ }
495
+ const nodes = []
496
+ // identity beside each geometry entry, from the rows already read,
497
+ // so a changed layout can name the nodes that moved.
498
+ const nodeRows = []
499
+ const LOADING_TEXT_REGEX = /^(creating webview|loading html|fetching bundle|waiting for first render|starting preview|loading simulator|fetching app code|waiting for native preview|starting design|loading canvas|fetching screens|painting the canvas|waiting for webview|waiting for preview|waiting for canvas|preview stalled)/i
500
+ const noteLoading = (state, text) => {
501
+ if (state?.busy === true) {
502
+ webViewStarting = true
503
+ if (!webViewBlocker) webViewBlocker = 'accessibility busy state active'
504
+ }
505
+ if (typeof text === 'string' && LOADING_TEXT_REGEX.test(text.trim())) {
506
+ webViewStarting = true
507
+ if (!webViewBlocker) webViewBlocker = 'webView startup in progress ("' + text.trim() + '")'
508
+ }
509
+ }
510
+ if (hierarchy) {
511
+ for (const n of hierarchy) {
512
+ const layout = n && n.layout
513
+ if (layout && layout.width > 0) {
514
+ // painted bounds catch a scroll fling. background playback
515
+ // keeps a view's painted bounds moving forever, so it and its
516
+ // subtree count by their own layout; the rest of the screen
517
+ // still catches the fling.
518
+ const abs = n.backgroundPlayback ? layout : n.absolute || n.absolutePosition || layout
519
+ const geometry = Math.round(abs.x) + ',' + Math.round(abs.y) + ',' + Math.round(layout.width)
520
+ nodes.push(geometry)
521
+ nodeRows.push([String(n.nodeId ?? nodes.length - 1), (n.type || '?') + (n.testId ? '#' + n.testId : ''), geometry])
504
522
  }
523
+ noteLoading(
524
+ n.accessibilityState,
525
+ typeof n.text === 'string' ? n.text : '',
526
+ )
505
527
  }
506
- if (hierarchy) {
507
- for (const n of hierarchy) {
508
- const layout = n && n.layout
509
- if (layout && layout.width > 0) {
510
- // painted bounds catch a scroll fling. background playback
511
- // keeps a view's painted bounds moving forever, so it and its
512
- // subtree count by their own layout; the rest of the screen
513
- // still catches the fling.
514
- const abs = n.backgroundPlayback ? layout : n.absolute || n.absolutePosition || layout
515
- const geometry = Math.round(abs.x) + ',' + Math.round(abs.y) + ',' + Math.round(layout.width)
528
+ } else {
529
+ const root = globalThis.__sootsimRoot
530
+ if (root) {
531
+ const walk = (n) => {
532
+ if (n.layout && n.layout.width > 0) {
533
+ const geometry = Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width)
516
534
  nodes.push(geometry)
517
- nodeRows.push([String(n.nodeId ?? nodes.length - 1), (n.type || '?') + (n.testId ? '#' + n.testId : ''), geometry])
535
+ nodeRows.push([String(n.id ?? nodes.length - 1), (n.type || '?') + (n.props?.testID ? '#' + n.props.testID : ''), geometry])
518
536
  }
519
537
  noteLoading(
520
- n.accessibilityState,
521
- typeof n.text === 'string' ? n.text : '',
538
+ n.props?.accessibilityState,
539
+ n.textContent || (typeof n.props?.children === 'string' ? n.props.children : ''),
522
540
  )
541
+ for (const c of n.children || []) walk(c)
523
542
  }
524
- } else {
525
- const root = globalThis.__sootsimRoot
526
- if (root) {
527
- const walk = (n) => {
528
- if (n.layout && n.layout.width > 0) {
529
- const geometry = Math.round(n.layout.x) + ',' + Math.round(n.layout.y) + ',' + Math.round(n.layout.width)
530
- nodes.push(geometry)
531
- nodeRows.push([String(n.id ?? nodes.length - 1), (n.type || '?') + (n.props?.testID ? '#' + n.props.testID : ''), geometry])
532
- }
533
- noteLoading(
534
- n.props?.accessibilityState,
535
- n.textContent || (typeof n.props?.children === 'string' ? n.props.children : ''),
536
- )
537
- for (const c of n.children || []) walk(c)
538
- }
539
- walk(root)
540
- }
543
+ walk(root)
541
544
  }
542
- if (!webViewStarting && typeof document !== 'undefined') {
543
- const busyEl = [...document.querySelectorAll('[aria-busy="true"]')].find((element) => {
544
- const bounds = element.getBoundingClientRect()
545
- return element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) &&
546
- bounds.width > 0 && bounds.height > 0 && bounds.right > 0 && bounds.bottom > 0 &&
547
- bounds.left < globalThis.innerWidth && bounds.top < globalThis.innerHeight
545
+ }
546
+ if (!webViewStarting && typeof document !== 'undefined') {
547
+ const busyEl = [...document.querySelectorAll('[aria-busy="true"]')].find((element) => {
548
+ const bounds = element.getBoundingClientRect()
549
+ return element.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }) &&
550
+ bounds.width > 0 && bounds.height > 0 && bounds.right > 0 && bounds.bottom > 0 &&
551
+ bounds.left < globalThis.innerWidth && bounds.top < globalThis.innerHeight
552
+ })
553
+ if (busyEl) {
554
+ webViewStarting = true
555
+ webViewBlocker = 'accessibility busy element displayed'
556
+ } else {
557
+ // a loading document with no area (an app's hidden worker or
558
+ // executor frame) paints nothing, and a screenshot on device
559
+ // does not wait for it.
560
+ const unreadyWebView = [...document.querySelectorAll(
561
+ '[data-sootsim-webview-loading="true"], [data-sootsim-webview-mode="placeholder"]'
562
+ )].find((view) => {
563
+ const frame = view.querySelector('iframe')
564
+ return !frame || frame.clientWidth > 0 || frame.clientHeight > 0
548
565
  })
549
- if (busyEl) {
566
+ if (unreadyWebView) {
550
567
  webViewStarting = true
551
- webViewBlocker = 'accessibility busy element displayed'
552
- } else {
553
- // a loading document with no area (an app's hidden worker or
554
- // executor frame) paints nothing, and a screenshot on device
555
- // does not wait for it.
556
- const unreadyWebView = [...document.querySelectorAll(
557
- '[data-sootsim-webview-loading="true"], [data-sootsim-webview-mode="placeholder"]'
558
- )].find((view) => {
559
- const frame = view.querySelector('iframe')
560
- return !frame || frame.clientWidth > 0 || frame.clientHeight > 0
561
- })
562
- if (unreadyWebView) {
563
- webViewStarting = true
564
- webViewBlocker = 'webView document still loading'
565
- }
566
- }
567
- }
568
- const pixelsDecide = !workerBusy && !animating && !shellAnimating && !layoutDirty && pendingFetches === 0 && !webViewStarting
569
- if (paintStill && !pixelsDecide && unsubscribe) {
570
- unsubscribe()
571
- unsubscribe = null
572
- }
573
- if (paintStill && pixelsDecide && !unsubscribe) unsubscribe = composite.subscribe(() => {})
574
- if (paintStill && pixelsDecide) {
575
- const canvas = composite.getCanvas()
576
- const token = composite.getFrameToken()
577
- if (!canvas || canvas.width <= 1 || canvas.height <= 1) {
578
- screenPixels = null
579
- } else if (token !== pixelFrameToken || canvas.width !== screenPixels?.width || canvas.height !== screenPixels?.height) {
580
- const context = canvas.getContext('2d')
581
- const image = context?.getImageData(0, 0, canvas.width, canvas.height)
582
- screenPixels = image ? { width: image.width, height: image.height, data: new Uint32Array(image.data.buffer) } : null
583
- pixelFrameToken = token
568
+ webViewBlocker = 'webView document still loading'
584
569
  }
585
570
  }
586
- return { layout: nodes.join(';'), nodeRows, nativeHierarchy, screenPixels, animating, animatingBy, shellAnimating, shellBlockers, layoutDirty, pendingFetches, workerBusy, webViewStarting, webViewBlocker, renderStatsAvailable, requestTotal, requestInFlight, appCommits, nodeCount }
587
571
  }
572
+ return { layout: nodes.join(';'), nodeRows, nativeHierarchy, visibleMotion, visibleMotionBy, animating, animatingBy, shellAnimating, shellBlockers, layoutDirty, pendingFetches, workerBusy, motionUnavailable, webViewStarting, webViewBlocker, renderStatsAvailable, requestTotal, requestInFlight, appCommits, nodeCount }
573
+ }
588
574
 
589
- // how long generic background network is allowed to keep us waiting AFTER
590
- // the screen is otherwise visually settled. apps with continuous traffic
591
- // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
592
- // requestInFlight===0 / a stable requestTotal, so requiring full network
593
- // quiet burns the ENTIRE budget on every command — the leading idle that
594
- // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
595
- // layout-stability + the image-loader already prove visible content
596
- // loaded (a data load changes layout; an image load shows in the loader),
597
- // so the generic request counters are a courtesy, not a gate: honor them
598
- // only within this grace once the screen is visually still.
599
- const networkQuietGraceMs = 1200
600
- let lastNativeHierarchy = null
601
- let lastLayout = ''
602
- let lastNodeRows = []
603
- // what moved between the last two differing polls, bounded; names the
604
- // nodes behind "layout changed" without keeping any poll history.
605
- let lastLayoutChange = null
606
- const describeLayoutChange = (before, after) => {
607
- const previous = new Map(before.map(([key, label, geometry]) => [key, [label, geometry]]))
608
- const moved = []
609
- const added = []
610
- const short = (label, key) => String(label).slice(0, 48) + ' [' + String(key).slice(0, 24) + ']'
611
- for (const [key, label, geometry] of after) {
612
- const was = previous.get(key)
613
- previous.delete(key)
614
- if (!was) added.push(short(label, key) + ' ' + geometry)
615
- else if (was[1] !== geometry) moved.push(short(label, key) + ' ' + was[1] + '->' + geometry)
616
- }
617
- const removed = [...previous].map(([key, [label, geometry]]) => short(label, key) + ' ' + geometry)
618
- return {
619
- moved: moved.length, added: added.length, removed: removed.length,
620
- movedSample: moved.slice(0, 3), addedSample: added.slice(0, 3), removedSample: removed.slice(0, 3),
621
- }
575
+ // how long generic background network is allowed to keep us waiting AFTER
576
+ // the screen is otherwise visually settled. apps with continuous traffic
577
+ // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
578
+ // requestInFlight===0 / a stable requestTotal, so requiring full network
579
+ // quiet burns the ENTIRE budget on every command — the leading idle that
580
+ // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
581
+ // layout-stability + the image-loader already prove visible content
582
+ // loaded (a data load changes layout; an image load shows in the loader),
583
+ // so the generic request counters are a courtesy, not a gate: honor them
584
+ // only within this grace once the screen is visually still.
585
+ const networkQuietGraceMs = 1200
586
+ let lastNativeHierarchy = null
587
+ let lastLayout = ''
588
+ let lastNodeRows = []
589
+ // what moved between the last two differing polls, bounded; names the
590
+ // nodes behind "layout changed" without keeping any poll history.
591
+ let lastLayoutChange = null
592
+ const describeLayoutChange = (before, after) => {
593
+ const previous = new Map(before.map(([key, label, geometry]) => [key, [label, geometry]]))
594
+ const moved = []
595
+ const added = []
596
+ const short = (label, key) => String(label).slice(0, 48) + ' [' + String(key).slice(0, 24) + ']'
597
+ for (const [key, label, geometry] of after) {
598
+ const was = previous.get(key)
599
+ previous.delete(key)
600
+ if (!was) added.push(short(label, key) + ' ' + geometry)
601
+ else if (was[1] !== geometry) moved.push(short(label, key) + ' ' + was[1] + '->' + geometry)
622
602
  }
623
- let lastScreenPixels = null
624
- let screenChangedPolls = 0
625
- let lastRequestTotal = -1
626
- let lastAppCommits = null
627
- let lastNodeCount = null
628
- // the last completed poll and the values it was compared against.
629
- let report = null
630
- // the still polls of the current run, when each began and answered
631
- let stillPolls = []
632
- let lastIdlePoll = null
633
- let visuallyStillSince = 0
634
- // counts across the whole budget: a flag that is true on every poll is a
635
- // different bug from one that is true intermittently, and the two need
636
- // opposite fixes (engine vs budget).
637
- let polls = 0
638
- let dirtyPolls = 0
639
- let animatingPolls = 0
640
- let layoutChangedPolls = 0
641
- let webViewStartingPolls = 0
642
- const screenUnchanged = (pixels, previous) => {
643
- if (!pixels || !previous || pixels.width !== previous.width || pixels.height !== previous.height) return false
644
- if (pixels === previous) return true
645
- for (let i = 0; i < pixels.data.length; i++) {
646
- if (pixels.data[i] !== previous.data[i]) return false
647
- }
648
- return true
603
+ const removed = [...previous].map(([key, [label, geometry]]) => short(label, key) + ' ' + geometry)
604
+ return {
605
+ moved: moved.length, added: added.length, removed: removed.length,
606
+ movedSample: moved.slice(0, 3), addedSample: added.slice(0, 3), removedSample: removed.slice(0, 3),
649
607
  }
650
- const hierarchyUnchanged = (current, previous) =>
651
- current !== null && previous !== null && current.length === previous.length &&
652
- current.every((node, index) => sameNativeAccessibilityShape(node, previous[index], accessibilityBounds))
653
- while (true) {
654
- if (clockNow() >= deadline) {
655
- if (!transitionWait) break
656
- await transitionWait
657
- transitionWait = null
658
- // nothing polled while parked on the transition, and a loaded
659
- // worker's late reply would spend the restarted budget unobserved.
660
- if (transitionEndedAt !== null) deadline = Math.max(deadline, clockNow() + budgetMs)
661
- if (clockNow() >= deadline) break
662
- }
663
- const pollStarted = clockNow()
664
- const snapshot = await readSnapshot()
665
- if (snapshot.runtimeUnsupported) return snapshot.runtimeUnsupported
666
- // a read the deadline cut short observed nothing: the last full poll
667
- // names what held the settle, not a worker that ran out of budget.
668
- // the loop head drains a transition still in flight before it ends.
669
- if (snapshot.workerBusy && clockNow() >= deadline && report) continue
670
- polls++
671
- report = { snapshot, nativeHierarchy: lastNativeHierarchy, layout: lastLayout, screenPixels: lastScreenPixels, requestTotal: lastRequestTotal, appCommits: lastAppCommits, nodeCount: lastNodeCount }
672
- if (snapshot.layoutDirty) dirtyPolls++
673
- if (snapshot.animating || snapshot.shellAnimating) animatingPolls++
674
- if (snapshot.webViewStarting) webViewStartingPolls++
675
- if (polls > 1 && snapshot.layout !== lastLayout) {
676
- layoutChangedPolls++
677
- lastLayoutChange = describeLayoutChange(lastNodeRows, snapshot.nodeRows)
678
- }
679
- const screenChanged = paintStill && !screenUnchanged(snapshot.screenPixels, lastScreenPixels)
680
- if (polls > 1 && screenChanged) screenChangedPolls++
681
- const strictOk =
682
- !strict ||
683
- (snapshot.renderStatsAvailable &&
684
- !snapshot.animating &&
685
- !snapshot.shellAnimating &&
686
- !snapshot.layoutDirty)
687
- // visually settled: no worker motion or layout work, no new layout
688
- // commits, a stable mounted node count, no image content loading
689
- // (unless motion alone is asked), no webview startup in progress,
690
- // layout unchanged since the last poll. both modes wait out finite
691
- // worker motion now; strict additionally implies the flags through
692
- // strictOk and adds shell motion plus the blocking-stats floor. a
693
- // null count or commit reading means the runtime does not report
694
- // it, which reads as stable the way a missing stats block does.
695
- // equal presented pixels can precede pending worker motion or layout.
696
- // after that work drains, iOS's 3 s pixel phase may accept two equal
697
- // native TreeNodes while paint-only playback continues. overlap
698
- // hierarchy reads so neither the gesture nor screenshot deadline grows.
699
- const maestroStill = snapshot.screenPixels !== null && !snapshot.workerBusy && snapshot.pendingFetches === 0 && snapshot.requestInFlight === 0 && !snapshot.webViewStarting &&
700
- !snapshot.animating && !snapshot.shellAnimating && !snapshot.layoutDirty && (
701
- !screenChanged || (clockNow() - start >= 3000 &&
702
- hierarchyUnchanged(snapshot.nativeHierarchy, lastNativeHierarchy))
703
- )
704
- const idleSnapshot =
705
- strictOk &&
608
+ }
609
+ let screenChangedPolls = 0
610
+ let lastRequestTotal = -1
611
+ let lastAppCommits = null
612
+ let lastNodeCount = null
613
+ // the last completed poll and the values it was compared against.
614
+ let report = null
615
+ // the still polls of the current run, when each began and answered
616
+ let stillPolls = []
617
+ let lastIdlePoll = null
618
+ let visuallyStillSince = 0
619
+ // counts across the whole budget: a flag that is true on every poll is a
620
+ // different bug from one that is true intermittently, and the two need
621
+ // opposite fixes (engine vs budget).
622
+ let polls = 0
623
+ let dirtyPolls = 0
624
+ let animatingPolls = 0
625
+ let layoutChangedPolls = 0
626
+ let webViewStartingPolls = 0
627
+ const hierarchyUnchanged = (current, previous) =>
628
+ current !== null && previous !== null && current.length === previous.length &&
629
+ current.every((node, index) => sameNativeAccessibilityShape(node, previous[index], accessibilityBounds))
630
+ while (true) {
631
+ if (clockNow() >= deadline) {
632
+ if (!transitionWait) break
633
+ await transitionWait
634
+ transitionWait = null
635
+ // nothing polled while parked on the transition, and a loaded
636
+ // worker's late reply would spend the restarted budget unobserved.
637
+ if (transitionEndedAt !== null) deadline = Math.max(deadline, clockNow() + budgetMs)
638
+ if (clockNow() >= deadline) break
639
+ }
640
+ const pollStarted = clockNow()
641
+ const snapshot = await readSnapshot()
642
+ if (snapshot.runtimeUnsupported) return snapshot.runtimeUnsupported
643
+ // a read the deadline cut short observed nothing: the last full poll
644
+ // names what held the settle, not a worker that ran out of budget.
645
+ // the loop head drains a transition still in flight before it ends.
646
+ if (snapshot.workerBusy && clockNow() >= deadline && report) continue
647
+ polls++
648
+ report = { snapshot, nativeHierarchy: lastNativeHierarchy, layout: lastLayout, requestTotal: lastRequestTotal, appCommits: lastAppCommits, nodeCount: lastNodeCount }
649
+ if (snapshot.layoutDirty) dirtyPolls++
650
+ if (snapshot.animating || snapshot.shellAnimating) animatingPolls++
651
+ if (snapshot.webViewStarting) webViewStartingPolls++
652
+ if (polls > 1 && snapshot.layout !== lastLayout) {
653
+ layoutChangedPolls++
654
+ lastLayoutChange = describeLayoutChange(lastNodeRows, snapshot.nodeRows)
655
+ }
656
+ // the first poll has nothing to compare, so it cannot prove a still screen
657
+ const screenChanged = screenStill && (
658
+ polls === 1 ||
659
+ snapshot.visibleMotion ||
660
+ (snapshot.appCommits !== null && lastAppCommits !== null && snapshot.appCommits !== lastAppCommits) ||
661
+ (snapshot.nodeCount !== null && lastNodeCount !== null && snapshot.nodeCount !== lastNodeCount) ||
662
+ snapshot.layout !== lastLayout ||
663
+ (maestro && !hierarchyUnchanged(snapshot.nativeHierarchy, lastNativeHierarchy))
664
+ )
665
+ if (polls > 1 && screenChanged) screenChangedPolls++
666
+ const strictOk =
667
+ !strict ||
668
+ (snapshot.renderStatsAvailable &&
706
669
  !snapshot.animating &&
707
670
  !snapshot.shellAnimating &&
708
- !snapshot.layoutDirty &&
709
- snapshot.pendingFetches === 0 &&
710
- !snapshot.workerBusy &&
711
- !snapshot.webViewStarting
712
- const visuallyStill = maestro ? maestroStill :
713
- idleSnapshot &&
714
- (snapshot.appCommits === null || lastAppCommits === null || snapshot.appCommits === lastAppCommits) &&
715
- (snapshot.nodeCount === null || lastNodeCount === null || snapshot.nodeCount === lastNodeCount) &&
716
- !screenChanged &&
717
- snapshot.layout === lastLayout
718
- // generic network quiet: nothing in flight and no new requests issued.
719
- const networkQuiet =
720
- snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
721
- if (visuallyStill) {
722
- if (visuallyStillSince === 0) visuallyStillSince = clockNow()
723
- // two equal idle observations prove the interval between them.
724
- // discarding the first requires a third worker round trip, which
725
- // can exhaust the budget after a late image on a loaded host.
726
- if (!maestro && !paintStill && stillPolls.length === 0 && lastIdlePoll) {
727
- stillPolls.push(lastIdlePoll)
728
- }
729
- stillPolls.push({ started: pollStarted, answered: clockNow() })
730
- // still long enough, counting only polls that began after a started
731
- // transition drained.
732
- const stillProven = () => {
733
- const proving = stillPolls.filter((poll) => transitionEndedAt === null || poll.started >= transitionEndedAt)
734
- return proving.length >= minimumStablePolls && clockNow() - proving[0].answered >= requiredStillMs
735
- }
736
- // settle once the screen has held still long enough AND either the
737
- // network is genuinely quiet OR it has refused to quiet within the
738
- // grace (continuous background traffic must not block forever).
739
- if (
740
- stillProven() &&
741
- (maestro || networkQuiet || clockNow() - visuallyStillSince >= networkQuietGraceMs)
742
- ) {
743
- if (transitionWait) {
744
- await transitionWait
745
- transitionWait = null
746
- }
747
- if (stillProven()) return { settled: true, elapsed: clockNow() - start, blockedBy: '' }
671
+ !snapshot.layoutDirty)
672
+ // visually settled: no worker motion or layout work, no new layout
673
+ // commits, a stable mounted node count, no image content loading
674
+ // (unless motion alone is asked), no webview startup in progress,
675
+ // layout unchanged since the last poll. both modes wait out finite
676
+ // worker motion now; strict additionally implies the flags through
677
+ // strictOk and adds shell motion plus the blocking-stats floor. a
678
+ // null count or commit reading means the runtime does not report
679
+ // it, which reads as stable the way a missing stats block does.
680
+ // equal presented pixels can precede pending worker motion or layout.
681
+ // after that work drains, iOS's 3 s pixel phase may accept two equal
682
+ // native TreeNodes while paint-only playback continues. overlap
683
+ // hierarchy reads so neither the gesture nor screenshot deadline grows.
684
+ const maestroStill = !snapshot.workerBusy && snapshot.pendingFetches === 0 && snapshot.requestInFlight === 0 && !snapshot.webViewStarting &&
685
+ !snapshot.animating && !snapshot.shellAnimating && !snapshot.layoutDirty && (
686
+ !screenChanged || (clockNow() - start >= 3000 &&
687
+ hierarchyUnchanged(snapshot.nativeHierarchy, lastNativeHierarchy))
688
+ )
689
+ const idleSnapshot =
690
+ strictOk &&
691
+ !snapshot.animating &&
692
+ !snapshot.shellAnimating &&
693
+ !snapshot.layoutDirty &&
694
+ snapshot.pendingFetches === 0 &&
695
+ !snapshot.workerBusy &&
696
+ !snapshot.webViewStarting
697
+ const visuallyStill = maestro ? maestroStill :
698
+ idleSnapshot &&
699
+ (snapshot.appCommits === null || lastAppCommits === null || snapshot.appCommits === lastAppCommits) &&
700
+ (snapshot.nodeCount === null || lastNodeCount === null || snapshot.nodeCount === lastNodeCount) &&
701
+ !screenChanged &&
702
+ snapshot.layout === lastLayout
703
+ // generic network quiet: nothing in flight and no new requests issued.
704
+ const networkQuiet =
705
+ snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
706
+ if (visuallyStill) {
707
+ if (visuallyStillSince === 0) visuallyStillSince = clockNow()
708
+ // two equal idle observations prove the interval between them.
709
+ // discarding the first requires a third worker round trip, which
710
+ // can exhaust the budget after a late image on a loaded host.
711
+ if (!maestro && !screenStill && stillPolls.length === 0 && lastIdlePoll) {
712
+ stillPolls.push(lastIdlePoll)
713
+ }
714
+ stillPolls.push({ started: pollStarted, answered: clockNow() })
715
+ // still long enough, counting only polls that began after a started
716
+ // transition drained.
717
+ const stillProven = () => {
718
+ const proving = stillPolls.filter((poll) => transitionEndedAt === null || poll.started >= transitionEndedAt)
719
+ return proving.length >= minimumStablePolls && clockNow() - proving[0].answered >= requiredStillMs
720
+ }
721
+ // settle once the screen has held still long enough AND either the
722
+ // network is genuinely quiet OR it has refused to quiet within the
723
+ // grace (continuous background traffic must not block forever).
724
+ if (
725
+ stillProven() &&
726
+ (maestro || networkQuiet || clockNow() - visuallyStillSince >= networkQuietGraceMs)
727
+ ) {
728
+ if (transitionWait) {
729
+ await transitionWait
730
+ transitionWait = null
748
731
  }
749
- } else {
750
- stillPolls = []
751
- visuallyStillSince = 0
732
+ if (stillProven()) return { settled: true, elapsed: clockNow() - start, blockedBy: '' }
752
733
  }
753
- lastIdlePoll = idleSnapshot ? { started: pollStarted, answered: clockNow() } : null
754
- lastNativeHierarchy = snapshot.nativeHierarchy
755
- lastLayout = snapshot.layout
756
- lastNodeRows = snapshot.nodeRows
757
- lastScreenPixels = snapshot.screenPixels
758
- lastRequestTotal = snapshot.requestTotal
759
- lastAppCommits = snapshot.appCommits
760
- lastNodeCount = snapshot.nodeCount
761
- // reply latency belongs inside the poll interval; the stillness window
762
- // above remains measured from completed observations.
763
- const remainingPollMs = pollMs - (clockNow() - pollStarted)
764
- if (remainingPollMs > 0) await clockSleep(remainingPollMs)
734
+ } else {
735
+ stillPolls = []
736
+ visuallyStillSince = 0
765
737
  }
766
- if (!report) {
767
- return { settled: false, elapsed: clockNow() - start, blockedBy: 'no poll fit the budget' }
768
- }
769
- const last = report.snapshot
770
- const blockers = []
771
- if (!maestro && strict && !last.renderStatsAvailable) blockers.push('render stats unavailable')
772
- if (!maestro && last.animating) blockers.push('animations still running' + (last.animatingBy ? ' (' + last.animatingBy + ')' : ''))
773
- if (last.shellAnimating) blockers.push('animations still running (' + last.shellBlockers + ')')
774
- if (!maestro && last.layoutDirty) blockers.push('layout still dirty')
775
- if (!maestro && last.appCommits !== null && report.appCommits !== null && last.appCommits !== report.appCommits) blockers.push('layout commits still landing')
776
- if (!maestro && last.nodeCount !== null && report.nodeCount !== null && last.nodeCount !== report.nodeCount) blockers.push('node count still changing')
777
- if (last.pendingFetches > 0) blockers.push(last.pendingFetches + ' image fetches pending')
778
- if (last.workerBusy) blockers.push('a render worker too busy to report')
779
- if (last.webViewStarting) blockers.push(last.webViewBlocker || 'webView still starting')
780
- if (!maestro && last.layout !== report.layout) blockers.push('layout still changing')
781
- if (maestro && !hierarchyUnchanged(last.nativeHierarchy, report.nativeHierarchy)) blockers.push(last.nativeHierarchy === null ? 'native accessibility hierarchy unavailable' : 'native accessibility hierarchy still changing')
782
- if (paintStill && !last.screenPixels) blockers.push('screen pixels unavailable')
783
- else if (paintStill && !screenUnchanged(last.screenPixels, report.screenPixels)) blockers.push('screen pixels still changing')
784
- if (last.requestInFlight > 0) blockers.push(last.requestInFlight + ' requests in flight')
785
- else if (!maestro && last.requestTotal !== report.requestTotal) blockers.push('new requests issued')
786
- if (polls < 2) blockers.push('sim too busy to poll twice')
787
- // the last read is still: motion ended too near the deadline for the
788
- // stillness window to hold before it.
789
- if (!blockers.length) blockers.push('motion ended before stillness was proven')
790
- return {
791
- settled: false,
792
- elapsed: clockNow() - start,
793
- blockedBy:
794
- blockers.join(', ') + ' over ' + polls + ' polls (layout changed ' + layoutChangedPolls +
795
- 'x, layoutDirty ' + dirtyPolls + 'x, animating ' + animatingPolls + 'x, webViewStarting ' + webViewStartingPolls + 'x, screen changed ' + screenChangedPolls + 'x)' +
796
- (lastLayoutChange ? '; last layout change ' + JSON.stringify(lastLayoutChange) : ''),
797
- }
798
- } finally {
799
- unsubscribe?.()
738
+ lastIdlePoll = idleSnapshot ? { started: pollStarted, answered: clockNow() } : null
739
+ lastNativeHierarchy = snapshot.nativeHierarchy
740
+ lastLayout = snapshot.layout
741
+ lastNodeRows = snapshot.nodeRows
742
+ lastRequestTotal = snapshot.requestTotal
743
+ lastAppCommits = snapshot.appCommits
744
+ lastNodeCount = snapshot.nodeCount
745
+ // reply latency belongs inside the poll interval; the stillness window
746
+ // above remains measured from completed observations.
747
+ const remainingPollMs = pollMs - (clockNow() - pollStarted)
748
+ if (remainingPollMs > 0) await clockSleep(remainingPollMs)
749
+ }
750
+ if (!report) {
751
+ return { settled: false, elapsed: clockNow() - start, blockedBy: 'no poll fit the budget' }
752
+ }
753
+ const last = report.snapshot
754
+ const blockers = []
755
+ if (!maestro && strict && !last.renderStatsAvailable) blockers.push('render stats unavailable')
756
+ if (!maestro && last.animating) blockers.push('animations still running' + (last.animatingBy ? ' (' + last.animatingBy + ')' : ''))
757
+ if (last.shellAnimating) blockers.push('animations still running (' + last.shellBlockers + ')')
758
+ if (!maestro && last.layoutDirty) blockers.push('layout still dirty')
759
+ if (!maestro && last.appCommits !== null && report.appCommits !== null && last.appCommits !== report.appCommits) blockers.push('layout commits still landing')
760
+ if (!maestro && last.nodeCount !== null && report.nodeCount !== null && last.nodeCount !== report.nodeCount) blockers.push('node count still changing')
761
+ if (last.pendingFetches > 0) blockers.push(last.pendingFetches + ' image fetches pending')
762
+ if (last.motionUnavailable) blockers.push('animation reporting unavailable')
763
+ if (last.workerBusy && !last.motionUnavailable) blockers.push('a render worker too busy to report')
764
+ if (last.webViewStarting) blockers.push(last.webViewBlocker || 'webView still starting')
765
+ if (!maestro && last.layout !== report.layout) blockers.push('layout still changing')
766
+ if (maestro && !hierarchyUnchanged(last.nativeHierarchy, report.nativeHierarchy)) blockers.push(last.nativeHierarchy === null ? 'native accessibility hierarchy unavailable' : 'native accessibility hierarchy still changing')
767
+ if (screenStill && last.visibleMotion) blockers.push('visible motion continues (' + last.visibleMotionBy + ')')
768
+ if (last.requestInFlight > 0) blockers.push(last.requestInFlight + ' requests in flight')
769
+ else if (!maestro && last.requestTotal !== report.requestTotal) blockers.push('new requests issued')
770
+ if (polls < 2) blockers.push('sim too busy to poll twice')
771
+ // the last read is still: motion ended too near the deadline for the
772
+ // stillness window to hold before it.
773
+ if (!blockers.length) blockers.push('motion ended before stillness was proven')
774
+ return {
775
+ settled: false,
776
+ elapsed: clockNow() - start,
777
+ blockedBy:
778
+ blockers.join(', ') + ' over ' + polls + ' polls (layout changed ' + layoutChangedPolls +
779
+ 'x, layoutDirty ' + dirtyPolls + 'x, animating ' + animatingPolls + 'x, webViewStarting ' + webViewStartingPolls + 'x, screen changed ' + screenChangedPolls + 'x)' +
780
+ (lastLayoutChange ? '; last layout change ' + JSON.stringify(lastLayoutChange) : ''),
800
781
  }
801
782
  })()`,
802
783
  },