peachsim 0.1.2241 → 0.1.2242

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 (88) hide show
  1. package/cli/bridge-flow-runner.ts +10 -9
  2. package/cli/commands/inspect/settling.ts +491 -515
  3. package/cli/commands/platform.ts +2 -0
  4. package/dist-lib/agent-daemon-client.cjs +1 -1
  5. package/dist-lib/agent-events.cjs +1 -1
  6. package/dist-lib/attached-projects.cjs +1 -1
  7. package/dist-lib/auth/shared-session.cjs +1 -1
  8. package/dist-lib/backend-origin.cjs +1 -1
  9. package/dist-lib/beta.cjs +1 -1
  10. package/dist-lib/beta.mjs +1 -1
  11. package/dist-lib/bridge-constants.cjs +1 -1
  12. package/dist-lib/bridge-contract-input.cjs +1 -1
  13. package/dist-lib/bridge-contract-input.mjs +1 -1
  14. package/dist-lib/bridge-contract.cjs +1 -1
  15. package/dist-lib/bridge-contract.mjs +1 -1
  16. package/dist-lib/bundle-channel.cjs +30 -22
  17. package/dist-lib/capture-contract.cjs +1 -1
  18. package/dist-lib/capture-contract.mjs +1 -1
  19. package/dist-lib/cloud-contract.cjs +1 -1
  20. package/dist-lib/cloud-contract.mjs +1 -1
  21. package/dist-lib/cloud-test-args.cjs +1 -1
  22. package/dist-lib/cloud-test-args.mjs +1 -1
  23. package/dist-lib/cloud.cjs +1 -1
  24. package/dist-lib/cloud.mjs +1 -1
  25. package/dist-lib/config.cjs +1 -1
  26. package/dist-lib/config.mjs +1 -1
  27. package/dist-lib/detox/index.cjs +493 -518
  28. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  29. package/dist-lib/expo-swift-bundle.cjs +29 -21
  30. package/dist-lib/expo-swift-metadata.cjs +1 -1
  31. package/dist-lib/expo-swift-metadata.mjs +1 -1
  32. package/dist-lib/home-paths.cjs +1 -1
  33. package/dist-lib/host/bridge-host.cjs +30 -22
  34. package/dist-lib/host/fetch-proxy-handler.cjs +3 -3
  35. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  36. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  37. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  38. package/dist-lib/host/websocket-proxy.cjs +1 -1
  39. package/dist-lib/index.cjs +491 -516
  40. package/dist-lib/jump-to-source-babel.cjs +1 -1
  41. package/dist-lib/jump-to-source-native.cjs +1 -1
  42. package/dist-lib/kotlin-host.cjs +1 -1
  43. package/dist-lib/menu.cjs +1 -1
  44. package/dist-lib/menu.mjs +1 -1
  45. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  46. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  47. package/dist-lib/metro-production-bundle.cjs +1 -1
  48. package/dist-lib/metro-production-bundle.mjs +1 -1
  49. package/dist-lib/metro.cjs +3 -3
  50. package/dist-lib/native-app-identity-project.cjs +2 -2
  51. package/dist-lib/native-app-identity-project.mjs +2 -2
  52. package/dist-lib/native-app-identity.cjs +1 -1
  53. package/dist-lib/native-app-identity.mjs +1 -1
  54. package/dist-lib/native-firebase-metadata.cjs +1 -1
  55. package/dist-lib/native-firebase-metadata.mjs +1 -1
  56. package/dist-lib/pdfium-raster.cjs +1 -1
  57. package/dist-lib/pdfium-raster.mjs +1 -1
  58. package/dist-lib/plist.cjs +1 -1
  59. package/dist-lib/plist.mjs +1 -1
  60. package/dist-lib/profiles.cjs +1 -1
  61. package/dist-lib/public-brand.cjs +1 -1
  62. package/dist-lib/public-origins-lib-esm.json +24 -24
  63. package/dist-lib/public-origins-lib.json +53 -53
  64. package/dist-lib/react-native-host-modules.cjs +1 -1
  65. package/dist-lib/react-native-host-modules.mjs +1 -1
  66. package/dist-lib/reap-browser.cjs +1 -1
  67. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  68. package/dist-lib/sdk.cjs +487 -512
  69. package/dist-lib/sdk.mjs +487 -512
  70. package/dist-lib/skills.cjs +536 -552
  71. package/dist-lib/swift-compile.cjs +11 -3
  72. package/dist-lib/swift-compile.mjs +11 -3
  73. package/dist-lib/swift-package.cjs +1 -1
  74. package/dist-lib/swift-package.mjs +1 -1
  75. package/dist-lib/swift-submit.cjs +1 -1
  76. package/dist-lib/swift-submit.mjs +1 -1
  77. package/dist-lib/swift-toolchain.cjs +1 -1
  78. package/dist-lib/swift.cjs +1 -1
  79. package/dist-lib/vite-swift.cjs +28 -20
  80. package/dist-lib/vite.cjs +3 -3
  81. package/dist-lib/worklet-executable.cjs +1 -1
  82. package/dist-lib/worklet-executable.mjs +1 -1
  83. package/dist-types/packages/peach-engine/src/render-worker/compositor-protocol.d.ts +3 -0
  84. package/kotlin/sdk.tar.gz +0 -0
  85. package/package.json +1 -1
  86. package/src/native-static-libraries.ts +16 -16
  87. package/src/swift-shared-sdk.ts +6 -1
  88. package/src/swift-wasm-prune.ts +5 -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,525 @@ 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
+ // the reads are independent, so they run concurrently: a loaded sim
322
+ // answers each one late, and a poll that waits for them in turn
323
+ // costs their sum, which fits too few polls in the budget to settle.
324
+ // the window node count is the exception: it launches after the
325
+ // motion read, so a poll motion already fails skips that walk.
326
+ // strict reads also wait out shell motion. pixel reads inspect finite
327
+ // animations in both realms: a worklet can move the app while the
328
+ // tenant's basic animation flag and last presented pixels read still.
329
+ const accessibilityRead = maestro
330
+ ? answer(() => globalThis.__sootsimTest.captureAccessibilityTree()).catch(() => null)
331
+ : null
332
+ const motionRead = strict || screenStill
333
+ ? answer(() => globalThis.__sootsimTest?.listAnimations?.()).catch(() => null)
334
+ : null
335
+ const statsRead = answer(() => globalThis.__sootsimRenderHost?.queryStats?.()).catch(() => null)
336
+ // image preparation ends in the tenant before the compositor decodes
337
+ // and realizes its pixels. both owners must finish before settling.
338
+ // the compositor rejects a stats request it is too busy to answer.
339
+ const compositorRead = answer(() => globalThis.__sootsimCompositor.getStats({ detail: 'readiness' })).catch(() => BUSY)
340
+ const countsRead = answer(() => globalThis.__sootsimTest?.getRequestCounts?.()).catch(() => null)
341
+ // the mounted hierarchy in render-worker mode comes from the test
342
+ // bridge: globalThis.__sootsimRoot is an empty placeholder there, so a
343
+ // walk over it hashes every screen to the same empty string while
344
+ // it moves. listInspectable is the worker-backed read describe
345
+ // uses; a worker too busy to answer it reads as unsettled. tight
346
+ // budgets skip this read and settle on the cheaper signals above.
347
+ // it walks every node, so a poll whose geometry revision matches the
348
+ // last read, in this wait or an earlier one, reuses that read.
349
+ const hierarchyRead =
350
+ fullGeometry && typeof globalThis.__sootsimTest?.listInspectable === 'function'
351
+ ? answer(() => globalThis.__sootsimTest.getGeometryRevision?.())
352
+ .catch(() => null)
353
+ .then((revision) => {
354
+ if (revision === BUSY) return BUSY
355
+ if (typeof revision === 'string' && geometry.revision === revision) return geometry.hierarchy
356
+ return answer(() => globalThis.__sootsimTest.listInspectable({}))
357
+ .catch(() => null)
358
+ .then((hierarchy) => {
359
+ const kept = typeof revision === 'string' && Array.isArray(hierarchy)
360
+ geometry.revision = kept ? revision : null
361
+ geometry.hierarchy = kept ? hierarchy : null
362
+ return hierarchy
363
+ })
364
+ })
345
365
  : 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
- }
366
+ if (motionRead) {
367
+ const motion = await motionRead
368
+ if (motion === BUSY) workerBusy = true
369
+ else if (Array.isArray(motion)) {
370
+ const blocking = motion.filter((anim) =>
371
+ (anim.realm === 'shell' || screenStill) &&
372
+ anim.priority !== 'low' && anim.visible !== false &&
373
+ (!screenStill || anim.loop !== true))
374
+ shellAnimating = blocking.length > 0
375
+ // what blocking leaves out still moves the screen while visible;
376
+ // it ends a screen-still wait only at maestro's hierarchy check
377
+ // or the deadline, as a screen that never holds still does on ios.
378
+ const moving = screenStill
379
+ ? motion.filter((anim) => anim.visible !== false && !blocking.includes(anim))
380
+ : []
381
+ visibleMotion = moving.length > 0
382
+ visibleMotionBy = moving
383
+ .slice(0, 4)
384
+ .map((anim) => anim.source + '/' + anim.kind + '#' + anim.id + (anim.loop ? ' loop' : '') + (anim.priority === 'low' ? ' low' : ''))
385
+ .join(', ')
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(', ')
392
391
  }
393
- const stats = await statsRead
394
- if (stats === BUSY) {
395
- 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
- }
392
+ }
393
+ const stats = await statsRead
394
+ if (stats === BUSY) {
395
+ 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
+ },
411
410
  }
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
411
  }
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'
464
- }
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
+ (!screenStill && (readyPlayback ? stats.hasPendingReadinessAnimationFrames : stats.hasPendingBlockingAnimationFrames) === true)
419
+ if (animating)
420
+ animatingBy = [
421
+ stats.hasActiveAnims === true && 'activeAnims',
422
+ stats.hasActiveBlockingNativeAnimations === true && 'blockingNative',
423
+ !screenStill && stats.hasPendingBlockingAnimationFrames === true && 'pendingFrames',
424
+ !screenStill && 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
+ }
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'
465
464
  }
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
465
+ }
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
490
+ }
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'
490
500
  }
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() + '")'
501
+ if (typeof text === 'string' && LOADING_TEXT_REGEX.test(text.trim())) {
502
+ webViewStarting = true
503
+ if (!webViewBlocker) webViewBlocker = 'webView startup in progress ("' + text.trim() + '")'
504
+ }
505
+ }
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)
516
+ nodes.push(geometry)
517
+ nodeRows.push([String(n.nodeId ?? nodes.length - 1), (n.type || '?') + (n.testId ? '#' + n.testId : ''), geometry])
504
518
  }
519
+ noteLoading(
520
+ n.accessibilityState,
521
+ typeof n.text === 'string' ? n.text : '',
522
+ )
505
523
  }
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)
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)
516
530
  nodes.push(geometry)
517
- nodeRows.push([String(n.nodeId ?? nodes.length - 1), (n.type || '?') + (n.testId ? '#' + n.testId : ''), geometry])
531
+ nodeRows.push([String(n.id ?? nodes.length - 1), (n.type || '?') + (n.props?.testID ? '#' + n.props.testID : ''), geometry])
518
532
  }
519
533
  noteLoading(
520
- n.accessibilityState,
521
- typeof n.text === 'string' ? n.text : '',
534
+ n.props?.accessibilityState,
535
+ n.textContent || (typeof n.props?.children === 'string' ? n.props.children : ''),
522
536
  )
537
+ for (const c of n.children || []) walk(c)
523
538
  }
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
- }
539
+ walk(root)
541
540
  }
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
541
+ }
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
548
+ })
549
+ if (busyEl) {
550
+ 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
548
561
  })
549
- if (busyEl) {
562
+ if (unreadyWebView) {
550
563
  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
- }
564
+ webViewBlocker = 'webView document still loading'
566
565
  }
567
566
  }
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
584
- }
585
- }
586
- return { layout: nodes.join(';'), nodeRows, nativeHierarchy, screenPixels, animating, animatingBy, shellAnimating, shellBlockers, layoutDirty, pendingFetches, workerBusy, webViewStarting, webViewBlocker, renderStatsAvailable, requestTotal, requestInFlight, appCommits, nodeCount }
587
567
  }
568
+ return { layout: nodes.join(';'), nodeRows, nativeHierarchy, visibleMotion, visibleMotionBy, animating, animatingBy, shellAnimating, shellBlockers, layoutDirty, pendingFetches, workerBusy, webViewStarting, webViewBlocker, renderStatsAvailable, requestTotal, requestInFlight, appCommits, nodeCount }
569
+ }
588
570
 
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
- }
571
+ // how long generic background network is allowed to keep us waiting AFTER
572
+ // the screen is otherwise visually settled. apps with continuous traffic
573
+ // (polling, realtime sockets, a tap that fires 20-50 fetches) never reach
574
+ // requestInFlight===0 / a stable requestTotal, so requiring full network
575
+ // quiet burns the ENTIRE budget on every command — the leading idle that
576
+ // failed PR-preview recordings for network-heavy apps (3pc fight-pulse).
577
+ // layout-stability + the image-loader already prove visible content
578
+ // loaded (a data load changes layout; an image load shows in the loader),
579
+ // so the generic request counters are a courtesy, not a gate: honor them
580
+ // only within this grace once the screen is visually still.
581
+ const networkQuietGraceMs = 1200
582
+ let lastNativeHierarchy = null
583
+ let lastLayout = ''
584
+ let lastNodeRows = []
585
+ // what moved between the last two differing polls, bounded; names the
586
+ // nodes behind "layout changed" without keeping any poll history.
587
+ let lastLayoutChange = null
588
+ const describeLayoutChange = (before, after) => {
589
+ const previous = new Map(before.map(([key, label, geometry]) => [key, [label, geometry]]))
590
+ const moved = []
591
+ const added = []
592
+ const short = (label, key) => String(label).slice(0, 48) + ' [' + String(key).slice(0, 24) + ']'
593
+ for (const [key, label, geometry] of after) {
594
+ const was = previous.get(key)
595
+ previous.delete(key)
596
+ if (!was) added.push(short(label, key) + ' ' + geometry)
597
+ else if (was[1] !== geometry) moved.push(short(label, key) + ' ' + was[1] + '->' + geometry)
622
598
  }
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
599
+ const removed = [...previous].map(([key, [label, geometry]]) => short(label, key) + ' ' + geometry)
600
+ return {
601
+ moved: moved.length, added: added.length, removed: removed.length,
602
+ movedSample: moved.slice(0, 3), addedSample: added.slice(0, 3), removedSample: removed.slice(0, 3),
649
603
  }
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 &&
604
+ }
605
+ let screenChangedPolls = 0
606
+ let lastRequestTotal = -1
607
+ let lastAppCommits = null
608
+ let lastNodeCount = null
609
+ // the last completed poll and the values it was compared against.
610
+ let report = null
611
+ // the still polls of the current run, when each began and answered
612
+ let stillPolls = []
613
+ let lastIdlePoll = null
614
+ let visuallyStillSince = 0
615
+ // counts across the whole budget: a flag that is true on every poll is a
616
+ // different bug from one that is true intermittently, and the two need
617
+ // opposite fixes (engine vs budget).
618
+ let polls = 0
619
+ let dirtyPolls = 0
620
+ let animatingPolls = 0
621
+ let layoutChangedPolls = 0
622
+ let webViewStartingPolls = 0
623
+ const hierarchyUnchanged = (current, previous) =>
624
+ current !== null && previous !== null && current.length === previous.length &&
625
+ current.every((node, index) => sameNativeAccessibilityShape(node, previous[index], accessibilityBounds))
626
+ while (true) {
627
+ if (clockNow() >= deadline) {
628
+ if (!transitionWait) break
629
+ await transitionWait
630
+ transitionWait = null
631
+ // nothing polled while parked on the transition, and a loaded
632
+ // worker's late reply would spend the restarted budget unobserved.
633
+ if (transitionEndedAt !== null) deadline = Math.max(deadline, clockNow() + budgetMs)
634
+ if (clockNow() >= deadline) break
635
+ }
636
+ const pollStarted = clockNow()
637
+ const snapshot = await readSnapshot()
638
+ if (snapshot.runtimeUnsupported) return snapshot.runtimeUnsupported
639
+ // a read the deadline cut short observed nothing: the last full poll
640
+ // names what held the settle, not a worker that ran out of budget.
641
+ // the loop head drains a transition still in flight before it ends.
642
+ if (snapshot.workerBusy && clockNow() >= deadline && report) continue
643
+ polls++
644
+ report = { snapshot, nativeHierarchy: lastNativeHierarchy, layout: lastLayout, requestTotal: lastRequestTotal, appCommits: lastAppCommits, nodeCount: lastNodeCount }
645
+ if (snapshot.layoutDirty) dirtyPolls++
646
+ if (snapshot.animating || snapshot.shellAnimating) animatingPolls++
647
+ if (snapshot.webViewStarting) webViewStartingPolls++
648
+ if (polls > 1 && snapshot.layout !== lastLayout) {
649
+ layoutChangedPolls++
650
+ lastLayoutChange = describeLayoutChange(lastNodeRows, snapshot.nodeRows)
651
+ }
652
+ // the first poll has nothing to compare, so it cannot prove a still screen
653
+ const screenChanged = screenStill && (
654
+ polls === 1 ||
655
+ snapshot.visibleMotion ||
656
+ (snapshot.appCommits !== null && lastAppCommits !== null && snapshot.appCommits !== lastAppCommits) ||
657
+ (snapshot.nodeCount !== null && lastNodeCount !== null && snapshot.nodeCount !== lastNodeCount) ||
658
+ snapshot.layout !== lastLayout ||
659
+ (maestro && !hierarchyUnchanged(snapshot.nativeHierarchy, lastNativeHierarchy))
660
+ )
661
+ if (polls > 1 && screenChanged) screenChangedPolls++
662
+ const strictOk =
663
+ !strict ||
664
+ (snapshot.renderStatsAvailable &&
706
665
  !snapshot.animating &&
707
666
  !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: '' }
667
+ !snapshot.layoutDirty)
668
+ // visually settled: no worker motion or layout work, no new layout
669
+ // commits, a stable mounted node count, no image content loading
670
+ // (unless motion alone is asked), no webview startup in progress,
671
+ // layout unchanged since the last poll. both modes wait out finite
672
+ // worker motion now; strict additionally implies the flags through
673
+ // strictOk and adds shell motion plus the blocking-stats floor. a
674
+ // null count or commit reading means the runtime does not report
675
+ // it, which reads as stable the way a missing stats block does.
676
+ // equal presented pixels can precede pending worker motion or layout.
677
+ // after that work drains, iOS's 3 s pixel phase may accept two equal
678
+ // native TreeNodes while paint-only playback continues. overlap
679
+ // hierarchy reads so neither the gesture nor screenshot deadline grows.
680
+ const maestroStill = !snapshot.workerBusy && snapshot.pendingFetches === 0 && snapshot.requestInFlight === 0 && !snapshot.webViewStarting &&
681
+ !snapshot.animating && !snapshot.shellAnimating && !snapshot.layoutDirty && (
682
+ !screenChanged || (clockNow() - start >= 3000 &&
683
+ hierarchyUnchanged(snapshot.nativeHierarchy, lastNativeHierarchy))
684
+ )
685
+ const idleSnapshot =
686
+ strictOk &&
687
+ !snapshot.animating &&
688
+ !snapshot.shellAnimating &&
689
+ !snapshot.layoutDirty &&
690
+ snapshot.pendingFetches === 0 &&
691
+ !snapshot.workerBusy &&
692
+ !snapshot.webViewStarting
693
+ const visuallyStill = maestro ? maestroStill :
694
+ idleSnapshot &&
695
+ (snapshot.appCommits === null || lastAppCommits === null || snapshot.appCommits === lastAppCommits) &&
696
+ (snapshot.nodeCount === null || lastNodeCount === null || snapshot.nodeCount === lastNodeCount) &&
697
+ !screenChanged &&
698
+ snapshot.layout === lastLayout
699
+ // generic network quiet: nothing in flight and no new requests issued.
700
+ const networkQuiet =
701
+ snapshot.requestInFlight === 0 && snapshot.requestTotal === lastRequestTotal
702
+ if (visuallyStill) {
703
+ if (visuallyStillSince === 0) visuallyStillSince = clockNow()
704
+ // two equal idle observations prove the interval between them.
705
+ // discarding the first requires a third worker round trip, which
706
+ // can exhaust the budget after a late image on a loaded host.
707
+ if (!maestro && !screenStill && stillPolls.length === 0 && lastIdlePoll) {
708
+ stillPolls.push(lastIdlePoll)
709
+ }
710
+ stillPolls.push({ started: pollStarted, answered: clockNow() })
711
+ // still long enough, counting only polls that began after a started
712
+ // transition drained.
713
+ const stillProven = () => {
714
+ const proving = stillPolls.filter((poll) => transitionEndedAt === null || poll.started >= transitionEndedAt)
715
+ return proving.length >= minimumStablePolls && clockNow() - proving[0].answered >= requiredStillMs
716
+ }
717
+ // settle once the screen has held still long enough AND either the
718
+ // network is genuinely quiet OR it has refused to quiet within the
719
+ // grace (continuous background traffic must not block forever).
720
+ if (
721
+ stillProven() &&
722
+ (maestro || networkQuiet || clockNow() - visuallyStillSince >= networkQuietGraceMs)
723
+ ) {
724
+ if (transitionWait) {
725
+ await transitionWait
726
+ transitionWait = null
748
727
  }
749
- } else {
750
- stillPolls = []
751
- visuallyStillSince = 0
728
+ if (stillProven()) return { settled: true, elapsed: clockNow() - start, blockedBy: '' }
752
729
  }
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)
765
- }
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) : ''),
730
+ } else {
731
+ stillPolls = []
732
+ visuallyStillSince = 0
797
733
  }
798
- } finally {
799
- unsubscribe?.()
734
+ lastIdlePoll = idleSnapshot ? { started: pollStarted, answered: clockNow() } : null
735
+ lastNativeHierarchy = snapshot.nativeHierarchy
736
+ lastLayout = snapshot.layout
737
+ lastNodeRows = snapshot.nodeRows
738
+ lastRequestTotal = snapshot.requestTotal
739
+ lastAppCommits = snapshot.appCommits
740
+ lastNodeCount = snapshot.nodeCount
741
+ // reply latency belongs inside the poll interval; the stillness window
742
+ // above remains measured from completed observations.
743
+ const remainingPollMs = pollMs - (clockNow() - pollStarted)
744
+ if (remainingPollMs > 0) await clockSleep(remainingPollMs)
745
+ }
746
+ if (!report) {
747
+ return { settled: false, elapsed: clockNow() - start, blockedBy: 'no poll fit the budget' }
748
+ }
749
+ const last = report.snapshot
750
+ const blockers = []
751
+ if (!maestro && strict && !last.renderStatsAvailable) blockers.push('render stats unavailable')
752
+ if (!maestro && last.animating) blockers.push('animations still running' + (last.animatingBy ? ' (' + last.animatingBy + ')' : ''))
753
+ if (last.shellAnimating) blockers.push('animations still running (' + last.shellBlockers + ')')
754
+ if (!maestro && last.layoutDirty) blockers.push('layout still dirty')
755
+ if (!maestro && last.appCommits !== null && report.appCommits !== null && last.appCommits !== report.appCommits) blockers.push('layout commits still landing')
756
+ if (!maestro && last.nodeCount !== null && report.nodeCount !== null && last.nodeCount !== report.nodeCount) blockers.push('node count still changing')
757
+ if (last.pendingFetches > 0) blockers.push(last.pendingFetches + ' image fetches pending')
758
+ if (last.workerBusy) blockers.push('a render worker too busy to report')
759
+ if (last.webViewStarting) blockers.push(last.webViewBlocker || 'webView still starting')
760
+ if (!maestro && last.layout !== report.layout) blockers.push('layout still changing')
761
+ if (maestro && !hierarchyUnchanged(last.nativeHierarchy, report.nativeHierarchy)) blockers.push(last.nativeHierarchy === null ? 'native accessibility hierarchy unavailable' : 'native accessibility hierarchy still changing')
762
+ if (screenStill && last.visibleMotion) blockers.push('visible motion continues (' + last.visibleMotionBy + ')')
763
+ if (last.requestInFlight > 0) blockers.push(last.requestInFlight + ' requests in flight')
764
+ else if (!maestro && last.requestTotal !== report.requestTotal) blockers.push('new requests issued')
765
+ if (polls < 2) blockers.push('sim too busy to poll twice')
766
+ // the last read is still: motion ended too near the deadline for the
767
+ // stillness window to hold before it.
768
+ if (!blockers.length) blockers.push('motion ended before stillness was proven')
769
+ return {
770
+ settled: false,
771
+ elapsed: clockNow() - start,
772
+ blockedBy:
773
+ blockers.join(', ') + ' over ' + polls + ' polls (layout changed ' + layoutChangedPolls +
774
+ 'x, layoutDirty ' + dirtyPolls + 'x, animating ' + animatingPolls + 'x, webViewStarting ' + webViewStartingPolls + 'x, screen changed ' + screenChangedPolls + 'x)' +
775
+ (lastLayoutChange ? '; last layout change ' + JSON.stringify(lastLayoutChange) : ''),
800
776
  }
801
777
  })()`,
802
778
  },