import { randomBytes, randomUUID } from 'crypto'
// detox-compatible test driver for sootsim
// drop-in replacement for `import { by, device, element, expect, waitFor } from 'detox'`
// uses playwright to control a headless browser running sootsim
import * as fs from 'fs'
import { execFile } from 'node:child_process'
import { createRequire } from 'node:module'
import { promisify } from 'node:util'
import * as path from 'path'
import { chromium } from 'playwright-core'
import { waitForSootsimIdle as waitForRuntimeIdle } from '../cli/commands/inspect/settling'
import { createBridge } from '../cli/ws-bridge'
import { resolveSootsimBridgePortForHttpPort } from '../src/bridge-constants'
import { getCliRuntime } from '../src/cli-runtime.ts'
import { awaitStampedExpoSwiftReady } from '../src/expo-swift-ready'
import { SOOTSIM_SHELL_COMMAND_NAME } from '../src/menu'
import { pollUntil } from '../src/poll-until'
import {
  launchReapedChromeScoped,
  reserveChromiumAdmission,
  type ChromiumLaunchAdmission,
} from '../src/reap-browser'
import { usesDirectLookup } from '../src/target-matcher'
import {
  createExpect,
  createWaitFor,
  describeNodeVisibility,
  focusIsWithin,
  isTextInputNodeFocused,
  isNodeVisible,
} from './expectations'
import { REQUIRED_IDENTICAL_PROOF_FRAMES, framesIdentical } from './frame-identity.cjs'
import { frameTimingRoundingBound } from './frame-offset.mjs'
import {
  dispatchTwoFingerGesture,
  DETOX_PLATFORM,
  dragScrollNode,
  readSootsimInteractiveViewport,
  readSootsimViewport,
  resolveScrollStartPosition,
  sootsimToPage,
  waitForSootsimGestureHandler,
} from './gestures'
import {
  applyDetoxLaunchPermissions,
  permissionBootSeed,
  type DetoxLaunchPermissions,
} from './launch-permissions'
import { by, type Matcher } from './matchers'
import { describeSootsimBridgeFailure, navigateSootsimPage } from './navigation-lifecycle'
import {
  requireProofObserver,
  type ClassifyDiscreteFrame,
  type DiscreteFrameCadence,
  type DiscreteFrameObservation,
  type DiscreteFrameTrace,
  type DiscreteProofBinding,
  type MotionChangeDefinition,
  type MotionChangeMeasurement,
} from './proof-observer'
import type {
  SootSimInteractBridge,
  SootSimNodeInfo,
} from '../../peach-globals/src/index'
import type { SootSimElement } from './element-types'
import type {
  LockstepInputReceipt,
  LockstepScheduledInput,
  SootSimLockstepFrameReceipt,
} from '@peach/globals'
import type { Browser, BrowserContext, Page } from 'playwright-core'

const WORKLET_FRAME_TRACE_LIMIT = 16384

type DiscreteStageFrame = {
  label: string
  offsetMs: number
  actualMs: number
  frameIndex: number
  virtualTimestampMs: number
  dataUrl: string
}
type DiscreteObserverState = {
  stages: () => DiscreteStageFrame[]
  step: (durationMs: number) => Promise<void>
  entry: () => Promise<number>
  recordCapture: () => void
  finish: () => DiscreteFrameTrace
  close: () => void
}
type VisibleChangeCaptureState = {
  cancelled: boolean
  ready: boolean
  triggerStarted: boolean
  triggerCompleted: boolean
}
declare global {
  var __peachChromiumAdmission: ChromiumLaunchAdmission | undefined
  var __peachDetoxCleanup: (() => Promise<void>) | undefined
  interface Window {
    __sootsimVisibleChangeCaptures?: Record<string, VisibleChangeCaptureState>
    __peachClassifyDiscreteFrame?: ClassifyDiscreteFrame
    __peachDiscreteObserver?: DiscreteObserverState
  }
}

export { by }
export { registerProofObserver, type ProofObserver } from './proof-observer'
export type { SootSimElement } from './element-types'

declare global {
  interface Window {
    // installed by takeScreenshotStagesFast; each input action calls it with
    // its capture token immediately before invoking the input bridge so
    // only that capture's stages anchor at dispatch, before input completes.
    __sootsimAnchorTimedInput?: (token: string) => void
  }
}

const BASE_URL = process.env.PEACH_URL || 'http://localhost:5173'
const SCREENSHOT_DIR =
  process.env.PEACH_SCREENSHOT_DIR ||
  path.join(process.cwd(), 'test', 'detox-driver', 'screenshots', String(process.pid))

// shared state -- playwright page and browser
let _browser: Browser | null = null
let _browserLaunch: Promise<void> | null = null
let _browserLaunchAbort: AbortController | null = null
let _nativePrepareAbort = new AbortController()
let _reapBrowserNow: (() => void) | null = null
let _context: BrowserContext | null = null
let _appStorageState: Awaited<ReturnType<BrowserContext['storageState']>> | undefined
let _page: Page | null = null
let _synchronizationEnabled = false
let _proofFrameObservationActive = false
let _browserCompromised: string | null = null
let browserIdentity = 0
let contextIdentity = 0
let nextBrowserIdentity = 0
let nextContextIdentity = 0

// maximum duration for browser/context lifecycle operations (closeContext,
// newContext, newPage). playwright does not bound context.close() or context
// creation; this bound converts an opaque 180s Jest hook timeout into a
// named failure that identifies which lifecycle step stalled.
const BROWSER_LIFECYCLE_TIMEOUT_MS = 30_000

async function withLifecycleTimeout<T>(
  actionName: string,
  targetContextId: number,
  fn: () => Promise<T>,
  timeoutMs = BROWSER_LIFECYCLE_TIMEOUT_MS,
): Promise<T> {
  const start = Date.now()
  let timer: ReturnType<typeof setTimeout> | undefined
  try {
    return await Promise.race([
      fn(),
      new Promise<never>((_, reject) => {
        timer = setTimeout(() => {
          const elapsed = Date.now() - start
          reject(
            new Error(
              `sootsim browser lifecycle error: ${actionName} did not settle after ${elapsed}ms (context=${targetContextId})`,
            ),
          )
        }, timeoutMs)
      }),
    ])
  } finally {
    if (timer) clearTimeout(timer)
  }
}

const STATUS_BAR_OVERRIDE_EVENT = 'sootsim:statusBarOverride'

type StatusBarConfig = {
  time?: string
  dataNetwork?: string
  wifiMode?: string
  wifiBars?: string
  cellularMode?: string
  cellularBars?: string
  operatorName?: string
  batteryState?: string
  batteryLevel?: string | number
}

function getPage(): Page {
  if (_browserCompromised) {
    throw new Error(`sootsim browser is compromised: ${_browserCompromised}`)
  }
  if (!_page)
    throw new Error('sootsim driver not initialized -- call device.launchApp() first')
  return _page
}

async function waitForSootsimTree(page: Page, timeout = 30000): Promise<void> {
  try {
    await page.waitForFunction(() => !!window.__sootsimTest?.waitForTree, undefined, {
      timeout,
    })
    await page.evaluate(async (timeoutMs) => {
      let timer: ReturnType<typeof setTimeout> | undefined
      try {
        await Promise.race([
          window.__sootsimTest!.waitForTree(),
          new Promise((_, reject) => {
            timer = setTimeout(
              () =>
                reject(new Error(`sootsim waitForTree timed out after ${timeoutMs}ms`)),
              timeoutMs,
            )
          }),
        ])
      } finally {
        if (timer !== undefined) clearTimeout(timer)
      }
    }, timeout)
  } catch (error) {
    throw await describeSootsimBridgeFailure(page, error)
  }
}

async function waitForSootsimSurfaceMetrics(page: Page, timeout = 30000): Promise<void> {
  const deadline = Date.now() + timeout
  let lastSnapshot: unknown = null
  while (Date.now() < deadline) {
    lastSnapshot = await page.evaluate(async () => {
      const metricsWindow = (value: unknown): Record<string, unknown> | null => {
        if (!value || typeof value !== 'object') return null
        const windowValue = (value as Record<string, unknown>).window
        if (!windowValue || typeof windowValue !== 'object') return null
        return windowValue as Record<string, unknown>
      }
      const snapshot = await window.__sootsimTest?.getSurfaceMetricsSnapshot?.()
      const windowMetrics = metricsWindow(snapshot)
      const width = windowMetrics?.width
      const height = windowMetrics?.height
      if (
        typeof width === 'number' &&
        typeof height === 'number' &&
        width > 0 &&
        height > 0
      ) {
        return { ready: true }
      }
      return { ready: false, snapshot }
    })
    if (
      lastSnapshot &&
      typeof lastSnapshot === 'object' &&
      (lastSnapshot as { ready?: boolean }).ready
    ) {
      return
    }
    await page.waitForTimeout(50)
  }
  throw new Error(
    `timed out waiting for sootsim surface metrics: ${JSON.stringify(lastSnapshot)}`,
  )
}

export async function waitForSootsimShellReady(
  page: Page,
  timeout = 30000,
): Promise<void> {
  // home boots paint shell content through the shell worker; app boots
  // (direct /rn bundle urls, harness fixtures, deep links) paint through
  // the compositor and shellHost.firstContentPainted never settles. classify
  // with the engine's own boot-target predicate — the same one the shell
  // worker and SootSimCanvas agree on — and await the matching boundary:
  // shell first paint for home boots, compositor app-surface first paint for
  // app boots.
  // exported for the focused regression test.
  const expectsInitialAppPaint =
    getCliRuntime().render_worker_app_load.isAppBootTargetUrl(page.url())
  try {
    await page.evaluate(
      async ({ timeoutMs, expectsInitialAppPaint }) => {
        type ShellHostReadyBridge = {
          ready?: Promise<unknown>
          firstContentPainted?: Promise<unknown>
        }

        let deadline = Date.now() + timeoutMs
        const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
        const remaining = () => Math.max(1, deadline - Date.now())
        const withTimeout = async <T>(label: string, promise: Promise<T>) => {
          let timer: ReturnType<typeof setTimeout> | null = null
          try {
            await Promise.race([
              promise,
              new Promise((_, reject) => {
                timer = setTimeout(
                  () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
                  remaining(),
                )
              }),
            ])
          } finally {
            if (timer) clearTimeout(timer)
          }
        }

        const isTenantOnly =
          new URL(window.location.href).searchParams.get('renderMode') === 'tenant-only'
        let shellHost: ShellHostReadyBridge | null = null
        while (Date.now() < deadline) {
          const candidate = (window as any).SootSim?.bridges?.shellHost
          if (candidate || isTenantOnly) {
            shellHost = candidate ?? null
            break
          }
          await sleep(25)
        }

        if (!shellHost) {
          if (isTenantOnly) return
          throw new Error(`sootsim shell host unavailable after ${timeoutMs}ms`)
        }

        if (shellHost.ready && typeof shellHost.ready.then === 'function') {
          await withTimeout('sootsim shell ready', shellHost.ready)
        }
        // the shell's boot-stage receipt can advance on an auxiliary paint.
        // the compositor promise resolves only when app:one has actually
        // painted. the enclosing jest test bounds a genuinely hung boot.
        if (expectsInitialAppPaint) {
          const compositorHost: { firstContentPainted?: Promise<unknown> } | undefined =
            Reflect.get(window, '__sootsimCompositor')
          if (typeof compositorHost?.firstContentPainted?.then !== 'function') {
            throw new Error('sootsim app compositor unavailable at boot')
          }
          await compositorHost.firstContentPainted
        }

        // the tenant restarts into its matching worker artifact when a bundle's
        // actual mode differs from the booted one (production bundle, no url
        // mode params), and any in-flight tenant call then rejects with
        // 'render host disposed'. the compositor paint promise is stable
        // across tenant restarts, but the transitions drain is a tenant call,
        // so run the drain after paint and re-run it when a
        // restart lands mid-sequence. transition timeouts are genuine failures
        // and are never retried.
        const isRenderHostDisposed = (error: unknown): boolean =>
          error instanceof Error && error.message.includes('render host disposed')
        for (;;) {
          try {
            if (expectsInitialAppPaint) {
              // a compositor paint can precede appBooted. peer stats wait on
              // that signal, so finish the app launch before starting the
              // separate worklet-idle observation and its unchanged budget.
              const renderHost = window.SootSim?.state.renderHost
              if (
                !renderHost ||
                typeof renderHost !== 'object' ||
                !('appReady' in renderHost) ||
                !(renderHost.appReady instanceof Promise)
              ) {
                throw new Error('sootsim tenant app readiness unavailable at boot')
              }
              await withTimeout('sootsim tenant app ready', renderHost.appReady)
            }
            if (
              !expectsInitialAppPaint &&
              shellHost.firstContentPainted &&
              typeof shellHost.firstContentPainted.then === 'function'
            ) {
              await withTimeout(
                'sootsim shell first content paint',
                shellHost.firstContentPainted,
              )
            }

            const waitForScreenTransitions = (window as any).__sootsimTest
              ?.waitForScreenTransitions
            if (typeof waitForScreenTransitions === 'function') {
              const transitionResult = await waitForScreenTransitions({
                timeoutMs: Math.min(remaining(), 3000),
                settleMs: 64,
                startWindowMs: 700,
              })
              if (transitionResult?.timedOut === true) {
                throw new Error(
                  `sootsim app launch transitions timed out: ${JSON.stringify(transitionResult)}`,
                )
              }
            }
            break
          } catch (error) {
            if (!isRenderHostDisposed(error) || Date.now() >= deadline) throw error
            await sleep(100)
          }
        }
      },
      { timeoutMs: timeout, expectsInitialAppPaint },
    )
  } catch (error) {
    throw await describeSootsimBridgeFailure(page, error)
  }
}

async function waitForSootsimWorkletsIdle(page: Page, timeout = 3000): Promise<void> {
  const result = await page.evaluate(
    async ({ timeout }) => {
      const testBridge = window.__sootsimTest
      const getPeerStats = testBridge?.getPeerStats
      if (typeof getPeerStats !== 'function') {
        return { settled: true, skipped: true }
      }

      const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
      const start = Date.now()
      const deadline = start + timeout
      const requiredStableMs = 120
      let lastPending: number | null | undefined = null
      let completedReads = 0
      let lastReply: string | null = null
      let readStartedAt: number | null = null
      let tenantAtRead = window.__sootsimRenderHost
      let shellAtRead = window.SootSim?.bridges?.shellHost
      let peerProgress: import('@peach/globals').PeachPeerStatsProgress | null = null
      let deadlineTimerLateMs: number | null = null

      while (Date.now() < deadline) {
        readStartedAt = Date.now()
        tenantAtRead = window.__sootsimRenderHost
        shellAtRead = window.SootSim?.bridges?.shellHost
        let timer: ReturnType<typeof setTimeout> | undefined
        const peerRead = getPeerStats(false)
        peerProgress =
          peerRead && 'peachPeerProgress' in peerRead
            ? (peerRead.peachPeerProgress ?? null)
            : null
        const stats = await Promise.race([
          peerRead,
          new Promise<undefined>((resolve) => {
            timer = setTimeout(
              () => {
                deadlineTimerLateMs = Date.now() - deadline
                resolve(undefined)
              },
              Math.max(0, deadline - Date.now()),
            )
          }),
        ]).finally(() => {
          if (timer !== undefined) clearTimeout(timer)
        })
        if (stats === undefined) break
        readStartedAt = null
        if (stats === null) return { settled: true, elapsed: Date.now() - start }
        completedReads++
        lastReply = JSON.stringify({ elapsedMs: Date.now() - start, stats })
        lastPending = stats.pendingRunWorklets
        // the runtime records its last drain. bridge latency cannot erase an
        // idle interval or turn a missing stats reply into a zero count.
        if (
          lastPending === 0 &&
          stats.runWorkletsIdleMs !== null &&
          stats.runWorkletsIdleMs >= requiredStableMs
        ) {
          return {
            settled: true,
            elapsed: Date.now() - start,
            pending: lastPending,
          }
        }
        await sleep(25)
      }

      const waited = Date.now() - start
      // snapshot only the original read. a later request cannot explain which
      // realm delayed this join, and an unchanged host does not prove readiness.
      const tenantAtDeadline = window.__sootsimRenderHost
      const shellAtDeadline = window.SootSim?.bridges?.shellHost
      const observation = {
        completedReads,
        lastReply,
        outstandingRead:
          readStartedAt === null
            ? null
            : {
                startedAtMs: readStartedAt - start,
                elapsedMs: Date.now() - readStartedAt,
                peerProgress: peerProgress ? { ...peerProgress } : null,
                testBridgeChanged: window.__sootsimTest !== testBridge,
                tenant: {
                  presentAtRequest: !!tenantAtRead,
                  presentAtDeadline: !!tenantAtDeadline,
                  changed: tenantAtRead !== tenantAtDeadline,
                },
                shell: {
                  presentAtRequest: !!shellAtRead,
                  presentAtDeadline: !!shellAtDeadline,
                  changed: shellAtRead !== shellAtDeadline,
                },
              },
        deadlineTimerLateMs,
      }
      return {
        settled: false,
        elapsed: waited,
        pending: lastPending,
        observation,
      }
    },
    { timeout },
  )
  if (!result?.settled) {
    const pending = result?.pending ?? 'no peer stats reply'
    throw await describeSootsimBridgeFailure(
      page,
      new Error(
        `sootsim worklet runtime did not settle after ${result?.elapsed ?? timeout}ms (pending=${pending}; observation=${JSON.stringify(result?.observation)})`,
      ),
      'sootsim worklet runtime did not settle',
    )
  }
}

function reapOwnedBrowser(): void {
  const reap = _reapBrowserNow
  _reapBrowserNow = null
  _browser = null
  try {
    reap?.()
  } catch {}
}

// an open picture-in-picture window keeps the browser context alive and
// context.close() never settles (expo-pip has no exit api, and the OS
// window outlives its video element). exit PiP in every page first; the
// page's leavepictureinpicture handler stops the capture tracks and
// removes the video. bounded and best-effort so a wedged page cannot eat
// the close budget.
const CONTEXT_MEDIA_QUIESCE_TIMEOUT_MS = 2_500

async function quiesceContextMedia(context: BrowserContext): Promise<void> {
  const pages = context.pages()
  if (pages.length === 0) return
  // the race's bound timer must not outlive the race: an uncleared sleep here
  // kept jest's event loop alive past its 1s exit watchdog on every detox run.
  let timer: ReturnType<typeof setTimeout> | undefined
  try {
    await Promise.race([
      Promise.all(
        pages.map((page) =>
          page
            .evaluate(() => {
              const doc = globalThis.document
              if (!doc) return
              if (
                doc.pictureInPictureElement &&
                typeof doc.exitPictureInPicture === 'function'
              ) {
                void doc.exitPictureInPicture().catch(() => {})
              }
              doc.querySelectorAll('video').forEach((v) => {
                try {
                  if (
                    v.srcObject &&
                    typeof (v.srcObject as MediaStream).getTracks === 'function'
                  ) {
                    ;(v.srcObject as MediaStream).getTracks().forEach((t) => t.stop())
                    v.srcObject = null
                  }
                  v.pause()
                  v.remove()
                } catch {}
              })
            })
            .catch(() => {}),
        ),
      ),
      new Promise<void>((resolve) => {
        timer = setTimeout(resolve, CONTEXT_MEDIA_QUIESCE_TIMEOUT_MS)
      }),
    ]).catch(() => {})
  } finally {
    if (timer !== undefined) clearTimeout(timer)
  }
}

async function closeContext(preserveStorage: boolean) {
  if (!preserveStorage) _appStorageState = undefined
  if (_browserCompromised) {
    throw new Error(`sootsim browser is compromised: ${_browserCompromised}`)
  }
  if (!_context) return
  const context = _context
  const closingContextId = contextIdentity
  try {
    // process termination clears the app runtime, while its persistent stores
    // remain installed until launchApp({ delete: true }) requests a fresh app.
    if (preserveStorage) {
      _appStorageState = await withLifecycleTimeout(
        'context.storageState()',
        closingContextId,
        () => context.storageState({ indexedDB: true }),
      )
    }
    await quiesceContextMedia(context)
    await withLifecycleTimeout('context.close()', closingContextId, () => context.close())
    _context = null
    _page = null
    contextIdentity = 0
    _synchronizationEnabled = false
    _proofFrameObservationActive = false
  } catch (error) {
    _browserCompromised = error instanceof Error ? error.message : String(error)
    reapOwnedBrowser()
    throw error
  }
}

async function closeBrowser(preserveStorage: boolean) {
  if (!preserveStorage) _appStorageState = undefined
  if (!_browser) return
  const browser = _browser
  const reapBrowserNow = _reapBrowserNow
  _browser = null
  _reapBrowserNow = null
  browserIdentity = 0

  let closeError: Error | null = null
  try {
    await closeContext(preserveStorage)
  } catch (error) {
    closeError = error instanceof Error ? error : new Error(String(error))
  }

  // reap Chrome directly without waiting on an unbounded browser.close()
  try {
    reapBrowserNow?.()
  } catch {}

  try {
    await browser.close()
  } catch {}

  if (closeError) {
    throw closeError
  }
}

// transitionStartWindowMs is how long to wait for a screen transition that an
// action just requested to begin. a wait that follows no new input passes 0: a
// transition already running is still waited out, but none can start.
export async function waitForSootsimIdle(
  page: Page,
  maxMs = 3000,
  strict = false,
  transitionStartWindowMs = 600,
): Promise<void> {
  const result = await waitForRuntimeIdle({
    bridge: {
      send(command) {
        if (command.type !== 'evaluate' || typeof command.code !== 'string') {
          throw new Error('Detox readiness requires an evaluate command')
        }
        return page.evaluate(command.code)
      },
    },
    maxMs,
    strict,
    motionOnly: !strict,
    stablePolls: 3,
    transitionStartWindowMs,
    transitionTimeoutMs: 1800,
  })
  if (!result.settled) {
    throw new Error(
      `sootsim synchronization timed out after ${result.elapsed}ms (${result.blockedBy})`,
    )
  }
}

// keep matching and target sampling in one browser call. host scheduling and
// protocol serialization must not consume a round trip between real samples.
async function queryMatcherInPage({
  matcher: indexedMatcher,
  all = false,
  direct,
  settle,
}: {
  matcher: Matcher
  all?: boolean
  direct: boolean
  settle?: { action: string; startedAt: number; maxWaitMs: number; maxSpeed: number }
}): Promise<SootSimNodeInfo[]> {
  const find = () => window.__sootsimTest!.queryMatchingNodes(indexedMatcher)
  if (!settle) {
    if (!all && direct) {
      const bridge = window.__sootsimTest!
      const node =
        indexedMatcher.type === 'id'
          ? await bridge.findByTestId(indexedMatcher.value)
          : indexedMatcher.type === 'label'
            ? await bridge.findByLabel(indexedMatcher.value)
            : indexedMatcher.type === 'role'
              ? await bridge.findByRole(indexedMatcher.value)
              : (await bridge.queryAll({ type: indexedMatcher.value }))[0]
      return node ? [node] : []
    }
    return find()
  }

  const { action, startedAt, maxWaitMs, maxSpeed } = settle
  let lastPos: { x: number; y: number } | null = null
  let lastAnswered: number | null = null
  let lastRate: { vx: number; vy: number; speed: number } | null = null
  let sampleCount = 0
  let lastNodeId: number | null = null
  let stablePolls = 0
  const requiredStable = 2
  let hadNumericLayout = false
  let disappearedMidWait = false
  while (Date.now() - startedAt < maxWaitMs) {
    // detox taps the element's own activation point and lets window
    // hit-testing pick the receiver, so the settle wait tracks that point
    // even when no finger can reach the element itself.
    const observation = await window.__sootsimTest!.observeTapTarget(indexedMatcher, {
      includeUnreachable: true,
    })
    const node = observation
    if (!node) {
      if (hadNumericLayout) disappearedMidWait = true
      else return []
    } else {
      disappearedMidWait = false
      const pos = observation.tapPoint
      const answered = observation.sampledAt
      if (pos) {
        if (lastNodeId !== node.nodeId) {
          lastPos = null
          lastAnswered = null
          stablePolls = 0
        }
        lastNodeId = node.nodeId
        hadNumericLayout = true
        sampleCount++
        if (lastPos && lastAnswered !== null) {
          // the worker stamps actual geometry reads. reply latency does not
          // change the interval between those observations.
          const dtSec = (answered - lastAnswered) / 1000
          if (dtSec > 0.005) {
            const vx = Math.abs(pos.x - lastPos.x) / dtSec
            const vy = Math.abs(pos.y - lastPos.y) / dtSec
            const speed = Math.sqrt(vx * vx + vy * vy)
            lastRate = { vx, vy, speed }
            stablePolls = speed < maxSpeed ? stablePolls + 1 : 0
            if (stablePolls >= requiredStable && Date.now() - startedAt <= maxWaitMs)
              return [node]
          }
        }
        lastPos = pos
        lastAnswered = answered
      }
    }
    const frameStarted = performance.now()
    await new Promise<void>((resolve) => {
      const timeoutId = setTimeout(resolve, 50)
      requestAnimationFrame(() => {
        clearTimeout(timeoutId)
        resolve()
      })
    })
    const remaining = 25 - (performance.now() - frameStarted)
    if (remaining > 0)
      await new Promise<void>((resolve) => setTimeout(resolve, remaining))
  }
  const elapsed = Date.now() - startedAt
  const target = JSON.stringify(indexedMatcher)
  if (disappearedMidWait) {
    throw new Error(
      `element disappeared while waiting to come to rest for ${action}: ${target} after ${elapsed}ms`,
    )
  }
  if (!hadNumericLayout) {
    throw new Error(
      `element layout is not available for ${action}: ${target} after ${elapsed}ms`,
    )
  }
  if (lastRate === null || lastRate.speed < maxSpeed) {
    throw new Error(
      `element stillness was not proven for ${action}: ${target}; ${sampleCount} samples, ${stablePolls}/${requiredStable} stable intervals after ${elapsed}ms`,
    )
  }
  throw new Error(
    `element did not come to rest for ${action}: ${target}; still moving ${lastRate.vx.toFixed(1)} points/sec x / ${lastRate.vy.toFixed(1)} points/sec y after ${elapsed}ms`,
  )
}

// every node a regex, indexed or text matcher selects, in tree order
async function findNodesByMatcher(matcher: Matcher): Promise<SootSimNodeInfo[]> {
  return getPage().evaluate(queryMatcherInPage, {
    matcher,
    all: true,
    direct: usesDirectLookup(matcher),
  })
}

async function findNodeByMatcher(matcher: Matcher): Promise<SootSimNodeInfo | null> {
  return (
    (
      await getPage().evaluate(queryMatcherInPage, {
        matcher,
        direct: usesDirectLookup(matcher),
      })
    )[matcher.index ?? 0] ?? null
  )
}

// get the absolute center coordinates of a node in sootsim coordinate space
function getNodeCenter(nodeInfo: any): { x: number; y: number } {
  return {
    x:
      nodeInfo.absolutePosition.x +
      (nodeInfo.absolutePosition.width ?? nodeInfo.layout.width) / 2,
    y:
      nodeInfo.absolutePosition.y +
      (nodeInfo.absolutePosition.height ?? nodeInfo.layout.height) / 2,
  }
}

async function nodeOffsetToPage(
  page: Page,
  nodeInfo: any,
  dx: number,
  dy: number,
): Promise<{ x: number; y: number }> {
  const center = getNodeCenter(nodeInfo)
  return sootsimToPage(page, center.x + dx, center.y + dy)
}

type TapPoint =
  | { x: number; y: number }
  | {
      nodeId: number
      viewport: { width: number; height: number }
      offset?: { x?: number; y?: number }
    }

async function dispatchTapAtSootsimPoint(page: Page, point: TapPoint, token?: string) {
  await page.evaluate(
    async ({ point, token }) => {
      let x: number
      let y: number
      if ('nodeId' in point) {
        // resolve after the viewport read, in the browser task that dispatches
        // the pointer. a host round trip here can outlive a startup relayout.
        // detox creates the touch at the element's activation point even when
        // the element itself cannot receive a pointer hit; window hit-testing
        // picks the receiver.
        const resolved = await window.__sootsimTest!.resolveTapTarget(point.nodeId, {
          includeUnreachable: true,
        })
        if (!resolved) throw new Error(`element disappeared before tap: ${point.nodeId}`)
        const node = resolved.match
        if (point.offset) {
          x = node.absolutePosition.x + (point.offset.x ?? node.layout.width / 2)
          y = node.absolutePosition.y + (point.offset.y ?? node.layout.height / 2)
        } else {
          x = resolved.cx
          y = resolved.cy
          const frame = node.visibleFrame ?? {
            x: node.absolutePosition.x,
            y: node.absolutePosition.y,
            width: node.layout.width,
            height: node.layout.height,
          }
          const { viewport } = point
          const tolerance = 0.5
          const canTapCenter =
            Math.abs(frame.x - node.absolutePosition.x) <= tolerance &&
            Math.abs(frame.y - node.absolutePosition.y) <= tolerance &&
            frame.width >= node.layout.width - tolerance &&
            frame.height >= node.layout.height - tolerance &&
            x >= 0 &&
            y >= 0 &&
            x < viewport.width &&
            y < viewport.height
          if (!canTapCenter) {
            const left = Math.max(0, frame.x)
            const top = Math.max(0, frame.y)
            const right = Math.min(viewport.width, frame.x + frame.width)
            const bottom = Math.min(viewport.height, frame.y + frame.height)
            if (right > left && bottom > top) {
              x = left + (right - left) / 2
              y = top + (bottom - top) / 2
            }
          }
        }
        // detox creates the touch in the matched view's window and sends it
        // through uiapplication, so system status-bar routing cannot take it.
        // that window's hit test picks the receiver, so a covering view such as
        // a box-only parent or a pointerEvents none sibling takes the press.
        if (token) window.__sootsimAnchorTimedInput?.(token)
        let result = await window.__sootsimTest!.activatePressAt(x, y, point.nodeId)
        const refusal = result?.tap
        const covering =
          refusal &&
          typeof refusal === 'object' &&
          'reason' in refusal &&
          refusal.reason === 'target-covered' &&
          'coordinateTarget' in refusal
            ? refusal.coordinateTarget
            : null
        if (covering && typeof covering === 'object' && 'nodeId' in covering) {
          const { nodeId } = covering
          if (typeof nodeId === 'number') {
            result = await window.__sootsimTest!.activatePressAt(x, y, nodeId)
          }
        }
        // detox delivers the touch and reports success whatever answers it: a
        // disabled control swallows the tap and does nothing. only a miss or a
        // covering view the retry could not reach is a refusal.
        const tap = result?.tap
        const delivered =
          typeof tap === 'object' &&
          tap !== null &&
          'hit' in tap &&
          tap.hit === true &&
          !('requestedTargetMatched' in tap && tap.requestedTargetMatched === false)
        if (result?.ok !== true && !delivered) {
          throw new Error(`element tap was refused: ${JSON.stringify(result)}`)
        }
        return
      } else {
        ;({ x, y } = point)
      }
      const interactTap = window.SootSim?.bridges?.interact?.tap
      if (typeof interactTap === 'function') {
        if (token) window.__sootsimAnchorTimedInput?.(token)
        const result = await interactTap(x, y)
        if (result && (typeof result !== 'object' || result.hit !== false)) {
          return
        }
      }
      const tap = window.__sootsimTest?.tap
      if (typeof tap !== 'function') {
        throw new Error('sootsim tap bridge is not installed')
      }
      if (token) window.__sootsimAnchorTimedInput?.(token)
      await tap(x, y)
    },
    { point, token },
  )
}

async function focusElementForTextEntry(el: SootSimElement): Promise<void> {
  const page = getPage()
  const node = await findNodeByMatcher(el._matcher)
  if (!node) {
    throw new Error(`element not found for text entry: ${JSON.stringify(el._matcher)}`)
  }
  if (await isTextInputNodeFocused(node, page)) return
  await el.tap()
  // the tap reaches the worker on its own channel. keys pressed before it lands
  // would edit around a caret the tap then moves, so wait for its focus.
  await pollUntil(
    () => page.evaluate(async () => window.__sootsimTest!.getFocusedNode()),
    (focused) => focused !== null && focusIsWithin(focused, node),
    {
      timeoutMs: 5000,
      label: `SootSim text input ${node.nodeId} to focus`,
    },
  )
}

function ensureScreenshotDir() {
  if (!fs.existsSync(SCREENSHOT_DIR)) {
    fs.mkdirSync(SCREENSHOT_DIR, { recursive: true })
  }
}

function decodePngDataUrl(dataUrl: string): Buffer {
  const match = /^data:image\/png;base64,(.+)$/.exec(dataUrl)
  if (!match) {
    throw new Error(
      `peach screenshot bridge returned a non-png payload: ${JSON.stringify(dataUrl.slice(0, 120))}`,
    )
  }
  return Buffer.from(match[1], 'base64')
}

type FastScreenshotData = {
  label: string
  offsetMs: number
  actualMs: number
  captureRequestedAtMs?: number
  dataUrl: string
  frameIndex?: number
  virtualTimestampMs?: number
  samplingTargetTimestampMs?: number
}

function writeFastScreenshotFrames<T extends FastScreenshotData>(
  namePrefix: string,
  frames: T[],
): Array<Omit<T, 'dataUrl'> & { path: string }> {
  ensureScreenshotDir()
  return frames.map((frame) => {
    const safeName = `${namePrefix}-${frame.label}`.replace(/[^a-zA-Z0-9._-]+/g, '-')
    const filePath = path.join(SCREENSHOT_DIR, `${safeName}.png`)
    fs.writeFileSync(filePath, decodePngDataUrl(frame.dataUrl))
    const { dataUrl: _dataUrl, ...metadata } = frame
    return {
      ...metadata,
      path: filePath,
    }
  })
}

// single-shot canvas capture — no frame-stability poll. used for multi-stage
// animation captures where we explicitly want to sample mid-transition. the
// usual captureSootsimPng requires three consecutive idle frames to be byte-equal
// which is ideal for settled screenshots but blocks for the full timeout
// while an animation is running.
async function captureSootsimPngFast(opts?: {
  crop?: { h: number; w: number; x: number; y: number }
}) {
  const page = getPage()
  const dataUrl = await page.evaluate(
    async (captureOpts) => {
      const screenshot = (window as { SootSim?: { bridges?: { screenshot?: unknown } } })
        .SootSim?.bridges?.screenshot as ((opts?: unknown) => Promise<string>) | undefined
      if (typeof screenshot !== 'function') {
        throw new Error('peach screenshot bridge is not installed')
      }
      return screenshot(captureOpts)
    },
    { crop: opts?.crop, format: 'png' },
  )
  if (!dataUrl) {
    throw new Error('peach screenshot bridge returned an empty image')
  }
  return decodePngDataUrl(dataUrl)
}

async function setSootsimCursorCaptureActive(page: Page, active: boolean) {
  await page.evaluate(async (captureActive) => {
    const bridge = window.__sootsimTest
    if (typeof bridge?.setCursorCaptureActive !== 'function') {
      throw new Error('sootsim cursor capture control is not installed')
    }
    await bridge.setCursorCaptureActive(captureActive)
  }, active)
}

async function captureSootsimPng(opts?: {
  crop?: { h: number; w: number; x: number; y: number }
}) {
  const page = getPage()
  // a focused TextInput caret changes on a timer. pin it visible for the
  // capture transaction so forced frames represent one settled visual state.
  await setSootsimCursorCaptureActive(page, true)
  try {
    const deadline = Date.now() + 8000
    let previous: Buffer | null = null
    let identicalFrames = 1
    let attempts = 0
    while (Date.now() < deadline) {
      const waitForIdle = () =>
        waitForSootsimIdle(
          page,
          Math.max(1, deadline - Date.now()),
          true,
          attempts === 0 ? 600 : 0,
        )
      if (_proofFrameObservationActive)
        await device.dispatchProofFrameOperation(waitForIdle)
      else await waitForIdle()
      // the pump joins its last probe before the full png read starts.
      const current = await captureSootsimPngFast(opts)
      if (_proofFrameObservationActive) {
        await page.evaluate(() => {
          if (!window.__peachDiscreteObserver)
            throw new Error('peach screenshot lost its proof clock owner')
          window.__peachDiscreteObserver.recordCapture()
        })
      }
      attempts++
      if (framesIdentical(previous, current)) {
        identicalFrames++
        if (identicalFrames >= REQUIRED_IDENTICAL_PROOF_FRAMES) return current
      } else {
        identicalFrames = 1
      }
      previous = current
    }
    throw new Error(
      `peach screenshot did not reach ${REQUIRED_IDENTICAL_PROOF_FRAMES} identical idle frames in ${attempts} captures`,
    )
  } finally {
    await setSootsimCursorCaptureActive(page, false)
  }
}

async function writeSootsimScreenshot(
  name: string,
  opts?: { crop?: { h: number; w: number; x: number; y: number } },
) {
  ensureScreenshotDir()
  const screenshotPath = path.join(SCREENSHOT_DIR, `${name}.png`)
  fs.writeFileSync(screenshotPath, await captureSootsimPng(opts))
  return screenshotPath
}

async function dispatchStatusBarOverride(config: StatusBarConfig) {
  const page = getPage()
  const time =
    typeof config.time === 'string' && config.time.length > 0 ? config.time : null
  await page.evaluate(
    ({ eventType, time }) => {
      window.dispatchEvent(
        new CustomEvent(eventType, {
          detail: { time },
        }),
      )
    },
    { eventType: STATUS_BAR_OVERRIDE_EVENT, time },
  )
  await page.waitForTimeout(50)
}

// rotate the simulated device through the same shell command the rotate
// control dispatches, so a conformance rotation runs the engine's own
// orientation switch and geometry republish rather than a driver-side resize.
// detox's ios server requests UIInterfaceOrientationMask.landscapeRight for
// 'landscape' (DetoxManager.swift setOrientation), so ios turns to landscape
// right; android keeps the engine's default landscape.
async function dispatchDeviceOrientation(orientation: 'portrait' | 'landscape') {
  const page = getPage()
  const captureToken = Reflect.get(page, '__sootsimCaptureToken')
  await page.evaluate(
    ({ eventType, next, landscapeSide, token }) => {
      if (token) window.__sootsimAnchorTimedInput?.(token)
      window.dispatchEvent(
        new CustomEvent(eventType, {
          detail: { type: 'set-device-orientation', orientation: next, landscapeSide },
        }),
      )
    },
    {
      eventType: SOOTSIM_SHELL_COMMAND_NAME,
      next: orientation,
      landscapeSide: DETOX_PLATFORM === 'ios' ? 'right' : 'left',
      token: captureToken,
    },
  )
  // destination dimensions publish before the interface finishes turning.
  await page.waitForFunction(
    (next) => {
      const settings = window.SootSim?.bridges?.settings?.get?.()
      const rotation = Reflect.get(window, '__sootsimDeviceRotation')
      return (
        typeof settings === 'object' &&
        settings !== null &&
        'orientation' in settings &&
        settings.orientation === next &&
        rotation?.active !== true
      )
    },
    orientation,
    { timeout: 15000 },
  )
}

// sweep the simulated duo's hinge to a rest through the command the pose
// buttons dispatch, so a conformance posture change runs the engine's own fold.
// resolves once the fold bus reports the hinge resting there.
async function dispatchDevicePosture(rest: 'closed' | 'book' | 'open') {
  const page = getPage()
  const captureToken = Reflect.get(page, '__sootsimCaptureToken')
  await page.evaluate(
    ({ eventType, rest, token }) => {
      if (token) window.__sootsimAnchorTimedInput?.(token)
      window.dispatchEvent(
        new CustomEvent(eventType, { detail: { type: 'fold-to-rest', rest } }),
      )
    },
    { eventType: SOOTSIM_SHELL_COMMAND_NAME, rest, token: captureToken },
  )
  await page.waitForFunction(
    (rest) => {
      const fold = Reflect.get(window, '__sootsimDuoFold')
      return fold?.rest === rest && fold.active !== true
    },
    rest,
    { timeout: 10000 },
  )
}

const MAX_SETTLED_SPEED_PT_PER_SEC = 2.0

async function findStableNodeByMatcher(
  matcher: Matcher,
  action = 'tap',
  maxWaitMs = 1500,
): Promise<SootSimNodeInfo | null> {
  const nodes = await getPage().evaluate(queryMatcherInPage, {
    matcher,
    direct: usesDirectLookup(matcher),
    settle: {
      action,
      startedAt: Date.now(),
      maxWaitMs,
      maxSpeed: MAX_SETTLED_SPEED_PT_PER_SEC,
    },
  })
  return nodes[0] ?? null
}

function createSootSimElement(matcher: Matcher): SootSimElement {
  const el: SootSimElement = {
    _matcher: matcher,

    async tap(point) {
      const page = getPage()
      // detox ios waits for the app to go idle before an action only while
      // synchronization is on; an unsynchronized tap lands mid-animation
      if (_synchronizationEnabled) await waitForSootsimWorkletsIdle(page, 3000)
      const node = await findStableNodeByMatcher(matcher, 'tap')
      if (!node) throw new Error(`element not found for tap: ${JSON.stringify(matcher)}`)
      if (!isNodeVisible(node)) {
        throw new Error(
          `Cannot perform action due to constraint failure: element not visible (${describeNodeVisibility(node)}): ${JSON.stringify(matcher)}`,
        )
      }
      const viewport = await readSootsimInteractiveViewport(page)
      const captureToken = (page as any).__sootsimCaptureToken
      await dispatchTapAtSootsimPoint(
        page,
        { nodeId: node.nodeId, viewport, offset: point },
        captureToken,
      )
      if (_synchronizationEnabled) {
        await waitForSootsimIdle(page)
      }
    },

    async multiTap(times: number) {
      // detox iOS multiTap performs N taps with the system's natural double-
      // tap pause. UITapGestureRecognizer treats taps within ~250ms as a
      // multi-tap. emit each tap as a discrete down/up at the same node
      // center with a small inter-tap pause that stays inside RNGH's
      // default maxDelay window of 200ms.
      const page = getPage()
      const node = await findStableNodeByMatcher(matcher, 'multiTap')
      if (!node)
        throw new Error(`element not found for multiTap: ${JSON.stringify(matcher)}`)
      if (!isNodeVisible(node)) {
        throw new Error(
          `Cannot perform action due to constraint failure: element not visible (${describeNodeVisibility(node)}): ${JSON.stringify(matcher)}`,
        )
      }
      const center = getNodeCenter(node)
      const pageCoords = await sootsimToPage(page, center.x, center.y)

      for (let i = 0; i < times; i++) {
        await page.mouse.move(pageCoords.x, pageCoords.y)
        await page.mouse.down()
        await page.waitForTimeout(50)
        await page.mouse.up()
        if (i < times - 1) {
          await page.waitForTimeout(80)
        }
      }
      await page.waitForTimeout(80)
    },

    // mirrors detox element.longPress(duration) and longPress(point, duration),
    // where the point is relative to the element's origin
    async longPress(
      pointOrDuration?: { x: number; y: number } | number,
      durationArg = 1000,
    ) {
      const page = getPage()
      const node = await findStableNodeByMatcher(matcher, 'longPress')
      if (!node)
        throw new Error(`element not found for longPress: ${JSON.stringify(matcher)}`)
      if (!isNodeVisible(node)) {
        throw new Error(
          `Cannot perform action due to constraint failure: element not visible (${describeNodeVisibility(node)}): ${JSON.stringify(matcher)}`,
        )
      }
      const duration = typeof pointOrDuration === 'number' ? pointOrDuration : durationArg
      const target =
        typeof pointOrDuration === 'object'
          ? {
              x: node.absolutePosition.x + pointOrDuration.x,
              y: node.absolutePosition.y + pointOrDuration.y,
            }
          : getNodeCenter(node)
      const captureToken = (page as any).__sootsimCaptureToken
      await page.evaluate(
        async ({ duration, x, y, token }) => {
          const longPress = window.SootSim?.bridges?.interact?.longPress
          if (typeof longPress !== 'function') {
            throw new Error('sootsim longPress bridge is not installed')
          }
          if (token) window.__sootsimAnchorTimedInput?.(token)
          await longPress(x, y, duration)
        },
        { duration, x: target.x, y: target.y, token: captureToken },
      )
      await page.waitForTimeout(50)
    },

    async longPressAndDrag(
      duration: number,
      normalizedStartX: number,
      normalizedStartY: number,
      targetElement: SootSimElement,
      normalizedEndX: number,
      normalizedEndY: number,
      speed = 'fast',
      holdDuration = 0,
    ) {
      const page = getPage()
      // resolve source element
      const srcNode = await findStableNodeByMatcher(matcher, 'longPressAndDrag')
      if (!srcNode)
        throw new Error(`source element not found: ${JSON.stringify(matcher)}`)

      // resolve target element
      const tgtNode = await findStableNodeByMatcher(
        targetElement._matcher,
        'longPressAndDrag',
      )
      if (!tgtNode)
        throw new Error(
          `target element not found: ${JSON.stringify(targetElement._matcher)}`,
        )

      // compute start and end in sootsim coords
      const startSootSimX =
        srcNode.absolutePosition.x + srcNode.layout.width * normalizedStartX
      const startSootSimY =
        srcNode.absolutePosition.y + srcNode.layout.height * normalizedStartY
      const endSootSimX =
        tgtNode.absolutePosition.x + tgtNode.layout.width * normalizedEndX
      const endSootSimY =
        tgtNode.absolutePosition.y + tgtNode.layout.height * normalizedEndY

      const startPage = await sootsimToPage(page, startSootSimX, startSootSimY)
      const endPage = await sootsimToPage(page, endSootSimX, endSootSimY)
      // Detox's dtx_longPressAtPoint:...thenDragToElement: presses for
      // `duration`, then moves one point per display frame at its pan
      // velocity (25pt per event, times 0.1 slow or 0.5 fast), adds one more
      // point past the end at the same pace, holds `holdDuration` before that
      // last point and lifts there
      const pace = 25 * (speed === 'slow' ? 0.1 : 0.5)
      const steps = Math.max(
        1,
        Math.round(
          Math.max(
            Math.abs(endSootSimX - startSootSimX),
            Math.abs(endSootSimY - startSootSimY),
          ) / pace,
        ),
      )
      const frameMs = 1000 / 60

      await page.mouse.move(startPage.x, startPage.y)
      await page.mouse.down()
      await page.waitForTimeout(duration)
      const dx = (endPage.x - startPage.x) / steps
      const dy = (endPage.y - startPage.y) / steps
      for (let i = 1; i <= steps + 1; i++) {
        await page.waitForTimeout(i === steps + 1 ? holdDuration : frameMs)
        await page.mouse.move(startPage.x + dx * i, startPage.y + dy * i)
      }

      await page.mouse.up()
      await page.waitForTimeout(50)
    },

    async typeText(text: string) {
      const page = getPage()
      await focusElementForTextEntry(el)
      await page.keyboard.type(text)
    },

    async tapReturnKey() {
      const page = getPage()
      await focusElementForTextEntry(el)
      await page.keyboard.press('Enter')
    },

    async replaceText(text: string) {
      const page = getPage()
      const node = await findNodeByMatcher(matcher)
      const resolvedId = node?.testID ?? node?.id
      if (
        matcher.type === 'id' &&
        typeof resolvedId === 'string' &&
        typeof node?.nodeId === 'number' &&
        node.nodeId >= 0x40000000
      ) {
        const replaced = await page.evaluate(
          async ({ id, value }) => {
            const mainShell = window.SootSim?.bridges?.mainShell
            if (typeof mainShell?.callTestBridge !== 'function') return false
            return mainShell.callTestBridge('replaceTextByTestId', id, value)
          },
          { id: resolvedId, value: text },
        )
        if (replaced === true) return
      }
      await focusElementForTextEntry(el)
      // detox replaces the whole value wherever the focusing tap left the caret
      await page.keyboard.press('End')
      const value = typeof node?.text === 'string' ? node.text : ''
      for (let i = 0; i < value.length; i++) {
        await page.keyboard.press('Backspace')
      }
      await page.keyboard.type(text)
    },

    async clearText() {
      const page = getPage()
      await focusElementForTextEntry(el)
      await page.keyboard.press('End')
      const node = await findNodeByMatcher(matcher)
      const value = typeof node?.text === 'string' ? node.text : ''
      for (let i = 0; i < value.length; i++) {
        await page.keyboard.press('Backspace')
      }
    },

    async scroll(
      pixels: number,
      direction: 'up' | 'down' | 'left' | 'right',
      startPositionX?: number,
      startPositionY?: number,
    ) {
      const node = await findNodeByMatcher(matcher)
      if (!node)
        throw new Error(`element not found for scroll: ${JSON.stringify(matcher)}`)
      const page = getPage()
      await dragScrollNode(page, node, pixels, direction, startPositionX, startPositionY)
    },

    async scrollTo(
      edge: 'top' | 'bottom' | 'left' | 'right',
      startPositionX?: number,
      startPositionY?: number,
    ) {
      const node = await findNodeByMatcher(matcher)
      if (!node)
        throw new Error(`element not found for scrollTo: ${JSON.stringify(matcher)}`)

      const targetId =
        typeof node.testID === 'string' && node.testID
          ? node.testID
          : typeof node.id === 'string' && node.id
            ? node.id
            : null
      if (!targetId) {
        throw new Error(
          `scrollTo requires an id-backed scroll view: ${JSON.stringify(matcher)}`,
        )
      }

      const normalizedStartX = resolveScrollStartPosition(
        startPositionX,
        'scrollTo startPositionX',
      )
      const normalizedStartY = resolveScrollStartPosition(
        startPositionY,
        'scrollTo startPositionY',
      )
      const hitX = node.absolutePosition.x + node.layout.width * normalizedStartX
      const hitY = node.absolutePosition.y + node.layout.height * normalizedStartY
      const page = getPage()
      const result = await page.evaluate(
        async ({ edge, hitX, hitY, targetId }) => {
          const bridge = window.__sootsimTest
          if (!bridge?.getScrollStateAt || !bridge.scrollTo) {
            return { ok: false, reason: 'scroll bridge unavailable' }
          }

          const state = await bridge.getScrollStateAt(hitX, hitY)
          if (!state) return { ok: false, reason: 'scroll state not found' }

          const maxOffset =
            state.maxOffset && typeof state.maxOffset === 'object'
              ? (state.maxOffset as { x?: number; y?: number })
              : null
          const offset =
            state.offset && typeof state.offset === 'object'
              ? (state.offset as { x?: number; y?: number })
              : null
          const maxX =
            typeof state.maxOffsetX === 'number' ? state.maxOffsetX : (maxOffset?.x ?? 0)
          const maxY =
            typeof state.maxOffsetY === 'number' ? state.maxOffsetY : (maxOffset?.y ?? 0)
          const currentX =
            typeof state.offsetX === 'number' ? state.offsetX : (offset?.x ?? 0)
          const currentY =
            typeof state.offsetY === 'number' ? state.offsetY : (offset?.y ?? 0)

          const x = edge === 'left' ? 0 : edge === 'right' ? maxX : currentX
          const y = edge === 'top' ? 0 : edge === 'bottom' ? maxY : currentY
          return bridge.scrollTo(targetId, x, y, false)
        },
        { edge, hitX, hitY, targetId },
      )

      if (!result?.ok) {
        throw new Error(
          `scrollTo(${edge}) failed for ${targetId}: ${result?.reason ?? 'unknown error'}`,
        )
      }

      await page.evaluate(
        () =>
          new Promise<void>((resolve) => {
            requestAnimationFrame(() => resolve())
          }),
      )
      if (_synchronizationEnabled) {
        await waitForSootsimIdle(page)
      }
    },

    async swipe(
      direction: 'up' | 'down' | 'left' | 'right',
      speed: 'fast' | 'slow' = 'fast',
      percentage = 0.75,
      normalizedStartingPointX?: number,
      normalizedStartingPointY?: number,
    ) {
      const page = getPage()
      if (_synchronizationEnabled) await waitForSootsimIdle(page, 3000, false, 0)
      const node = await findStableNodeByMatcher(matcher, 'swipe')
      if (!node)
        throw new Error(`element not found for swipe: ${JSON.stringify(matcher)}`)

      const { absolutePosition, layout } = node
      const viewport = await readSootsimViewport(page)
      const vertical = direction === 'up' || direction === 'down'
      const dist = (vertical ? viewport.height : viewport.width) * percentage
      const sign = direction === 'up' || direction === 'left' ? -1 : 1

      // detox on ios (measured on iOS 27, iPhone 16): an unspecified starting
      // coordinate on the swipe's axis centers the swipe on the screen's middle,
      // clamped into the element (the far edge one point inside); the other axis
      // starts at the element's center.
      const alongStart = vertical ? absolutePosition.y : absolutePosition.x
      const alongSize = vertical ? layout.height : layout.width
      const alongScreen = vertical ? viewport.height : viewport.width
      const alongNormalized = vertical
        ? normalizedStartingPointY
        : normalizedStartingPointX
      const crossNormalized = vertical
        ? normalizedStartingPointX
        : normalizedStartingPointY
      const along =
        alongNormalized === undefined
          ? Math.min(
              Math.max(alongScreen / 2 - (sign * dist) / 2, alongStart),
              alongStart + alongSize - 1,
            )
          : alongStart + alongSize * alongNormalized
      const cross =
        (vertical ? absolutePosition.x : absolutePosition.y) +
        (vertical ? layout.width : layout.height) * (crossNormalized ?? 0.5)
      const startSootSimX = vertical ? cross : along
      const startSootSimY = vertical ? along : cross

      let endSootSimX = startSootSimX
      let endSootSimY = startSootSimY

      const clampToScreen = (value: number, size: number) =>
        Math.min(Math.max(value, 1), size - 1)
      if (vertical)
        endSootSimY = clampToScreen(startSootSimY + sign * dist, viewport.height)
      else endSootSimX = clampToScreen(startSootSimX + sign * dist, viewport.width)

      // detox accumulates its interpolation fraction in a floating-point loop
      // (NSObject+DetoxActions.m, _DTXApplySwipe), which can stop before 1.
      const divisions = speed === 'slow' ? 40 : 20
      let steps = 0
      let lastProgress = 0
      for (let progress = 0; progress <= 1; progress += 1 / divisions) {
        lastProgress = progress
        steps++
      }
      steps--
      endSootSimX = startSootSimX + (endSootSimX - startSootSimX) * lastProgress
      endSootSimY = startSootSimY + (endSootSimY - startSootSimY) * lastProgress
      const stepDelay = 1000 / 60

      const captureToken = (page as any).__sootsimCaptureToken
      await page.evaluate(
        async ({ fromX, fromY, toX, toY, steps, stepMs, token }) => {
          // the interact bridge, not __sootsimTest.drag. the test bridge's drag
          // runs the whole down/move/up loop through the tenant's own
          // dispatchPointer and never fans to the shell, where gesture-handler's
          // recognizers live, so a swipe reported exact-zero activations for
          // every pan, fling, and manual gesture. taps were unaffected because
          // the responder path is tenant-local. the interact bridge resolves the
          // owner and feeds both, which is why the cases that call it directly
          // pass.
          const drag = window.__sootsimInteract?.drag
          if (typeof drag !== 'function') {
            throw new Error('sootsim interact bridge is not installed')
          }
          if (token) window.__sootsimAnchorTimedInput?.(token)
          await drag(fromX, fromY, toX, toY, steps, stepMs)
        },
        {
          fromX: startSootSimX,
          fromY: startSootSimY,
          toX: endSootSimX,
          toY: endSootSimY,
          steps,
          stepMs: stepDelay,
          token: captureToken,
        },
      )
      await page.waitForTimeout(100)
    },

    async setColumnToValue(column: number, value: string) {
      if (!Number.isInteger(column) || column < 0) {
        throw new Error(`picker column must be a non-negative integer, got ${column}`)
      }
      if (typeof value !== 'string') {
        throw new Error(`picker value must be a string, got ${typeof value}`)
      }

      const picker = await findStableNodeByMatcher(matcher, 'setColumnToValue')
      if (!picker) {
        throw new Error(
          `element not found for setColumnToValue: ${JSON.stringify(matcher)}`,
        )
      }

      const page = getPage()
      const candidates = await page.evaluate(
        async ({ picker, column, value }) => {
          const result = await window.__sootsimTest?.queryTextCandidates?.({
            query: value,
            exact: true,
          })
          if (!result || !Array.isArray(result.candidates)) return []
          const left = picker.absolutePosition.x
          const top = picker.absolutePosition.y
          const right = left + picker.layout.width
          const bottom = top + picker.layout.height
          return result.candidates
            .filter((candidate) => candidate.ancestorPickerColumnIndices.includes(column))
            .map((candidate) => candidate.info)
            .filter((candidate) => {
              const x = candidate.absolutePosition?.x
              const y = candidate.absolutePosition?.y
              const width = candidate.layout?.width
              const height = candidate.layout?.height
              if (
                typeof x !== 'number' ||
                typeof y !== 'number' ||
                typeof width !== 'number' ||
                typeof height !== 'number'
              ) {
                return false
              }
              const centerX = x + width / 2
              const centerY = y + height / 2
              return (
                centerX >= left && centerX <= right && centerY >= top && centerY <= bottom
              )
            })
        },
        { picker, column, value },
      )

      if (candidates.length !== 1) {
        throw new Error(
          `setColumnToValue(${column}, ${JSON.stringify(value)}) found ${candidates.length} matching rows inside ${JSON.stringify(matcher)}`,
        )
      }

      const target = candidates[0]
      // detox selects the picker row, whose hit rectangle stays flat. the
      // label is visually projected around the wheel and can overlap a later
      // label near the cylinder edge.
      const tapTarget = await page.evaluate(
        async (nodeId) =>
          window.__sootsimTest?.resolveTapTarget(nodeId, { includeUnreachable: true }),
        target.nodeId,
      )
      if (!tapTarget) {
        throw new Error(
          `setColumnToValue(${column}, ${JSON.stringify(value)}) could not resolve its picker row`,
        )
      }
      const captureToken = (page as any).__sootsimCaptureToken
      await dispatchTapAtSootsimPoint(
        page,
        {
          x: tapTarget.target.absolutePosition.x + tapTarget.target.layout.width / 2,
          y: tapTarget.target.absolutePosition.y + tapTarget.target.layout.height / 2,
        },
        captureToken,
      )
    },

    async pinch(scale: number, speed: 'fast' | 'slow' = 'fast', angle: number = 0) {
      // detox iOS pinch: scale > 1 spreads fingers (zoom in), scale < 1
      // brings them together (zoom out). speed maps to step delay so RNGH's
      // velocity tracking sees a realistic delta. angle (radians) tilts the
      // pinch axis off horizontal — matches Detox's third arg.
      const page = getPage()
      const node = await findStableNodeByMatcher(matcher, 'pinch')
      if (!node)
        throw new Error(`element not found for pinch: ${JSON.stringify(matcher)}`)
      if (!node.nativePinchEnabled) {
        await waitForSootsimGestureHandler(page, node.nodeId, 'PinchGestureHandler')
      }
      const startSpread = Math.min(
        60,
        Math.max(12, Math.min(node.layout.width, node.layout.height) * 0.25),
      )
      const endSpread = startSpread * Math.max(scale, 0.05)
      const cos = Math.cos(angle)
      const sin = Math.sin(angle)
      const offset = (d: number) => ({ dx: d * cos, dy: d * sin })
      const a0 = offset(-startSpread)
      const b0 = offset(startSpread)
      const a1 = offset(-endSpread)
      const b1 = offset(endSpread)
      await dispatchTwoFingerGesture(
        page,
        await nodeOffsetToPage(page, node, a0.dx, a0.dy),
        await nodeOffsetToPage(page, node, b0.dx, b0.dy),
        await nodeOffsetToPage(page, node, a1.dx, a1.dy),
        await nodeOffsetToPage(page, node, b1.dx, b1.dy),
        { steps: speed === 'fast' ? 4 : 12, stepDelayMs: speed === 'fast' ? 18 : 24 },
      )
    },

    async rotate(radians: number, speed: 'fast' | 'slow' = 'fast') {
      // two fingers held on a horizontal axis around the node center, then
      // both rotated to `radians` around the same center. on a y-down
      // screen positive radians drive the left finger up and the right
      // finger down, which is clockwise, so RNGH reports a positive
      // 'rotation' delta (clockwise reads positive on both natives).
      const page = getPage()
      const node = await findStableNodeByMatcher(matcher, 'rotate')
      if (!node)
        throw new Error(`element not found for rotate: ${JSON.stringify(matcher)}`)
      await waitForSootsimGestureHandler(page, node.nodeId, 'RotationGestureHandler')
      const radius = Math.min(
        60,
        Math.max(12, Math.min(node.layout.width, node.layout.height) * 0.25),
      )
      const startA = await nodeOffsetToPage(page, node, -radius, 0)
      const startB = await nodeOffsetToPage(page, node, radius, 0)
      const cos = Math.cos(radians)
      const sin = Math.sin(radians)
      const endA = await nodeOffsetToPage(page, node, -radius * cos, -radius * sin)
      const endB = await nodeOffsetToPage(page, node, radius * cos, radius * sin)
      await dispatchTwoFingerGesture(page, startA, startB, endA, endB, {
        steps: speed === 'fast' ? 10 : 20,
        stepDelayMs: speed === 'fast' ? 14 : 24,
      })
    },

    async takeScreenshot(name: string): Promise<string> {
      const node = await findNodeByMatcher(matcher)
      if (!node)
        throw new Error(
          `element not found for takeScreenshot: ${JSON.stringify(matcher)}`,
        )

      const box = node.frame ?? {
        x: node.absolutePosition.x,
        y: node.absolutePosition.y,
        width: node.layout.width,
        height: node.layout.height,
      }
      return writeSootsimScreenshot(name, {
        crop: {
          x: box.x,
          y: box.y,
          w: box.width,
          h: box.height,
        },
      })
    },

    async getAttributes(): Promise<any> {
      // detox ios reads attributes only once the app is idle while
      // synchronization is on, so a settling sheet reports its resting frame
      if (_synchronizationEnabled) await waitForSootsimIdle(getPage())
      const attributesOf = (node: any) => ({
        text: node.text || '',
        label: node.accessibilityLabel || node.text || '',
        identifier: node.testID || node.id || '',
        visible: node.layout.width > 0 && node.layout.height > 0,
        enabled: !node.accessibilityState?.disabled,
        ...node,
        // native detox reads a gauge's accessibility path, which excludes
        // the empty space below an accessory arc. keep other frame contracts.
        frame:
          node.nativeType === 'ExpoUI_GaugeView' && node.accessibilityFrame
            ? node.accessibilityFrame
            : node.absolutePosition?.width !== undefined &&
                node.absolutePosition.height !== undefined
              ? {
                  x: node.absolutePosition.x,
                  y: node.absolutePosition.y,
                  width: node.absolutePosition.width,
                  height: node.absolutePosition.height,
                }
              : node.frame,
      })
      // detox reads an unindexed pattern that selects several elements as a list
      if (matcher.regexFlags !== undefined && matcher.index === undefined) {
        const nodes = await findNodesByMatcher(matcher)
        if (nodes.length > 1) return { elements: nodes.map(attributesOf) }
      }
      const node = await findNodeByMatcher(matcher)
      if (!node)
        throw new Error(`element not found for getAttributes: ${JSON.stringify(matcher)}`)
      // detox reports the window point a tap on the element lands on. unlike
      // frame, it follows presentation transforms, so it moves while a sheet or
      // push is still sliding and a caller can wait for it to rest.
      const observation = await getPage().evaluate(
        (observed) =>
          window.__sootsimTest!.observeTapTarget(observed, { includeUnreachable: true }),
        matcher,
      )
      return { ...attributesOf(node), activationPoint: observation?.tapPoint ?? null }
    },

    atIndex(index: number) {
      return createSootSimElement({ ...matcher, index })
    },
  }

  return el
}

// element() factory -- takes a matcher and returns an element interaction object
export function element(matcher: Matcher): SootSimElement {
  return createSootSimElement(matcher)
}

// device object -- app lifecycle
export interface DetoxUserNotificationParams {
  trigger: {
    type: string
    [key: string]: unknown
  }
  title?: unknown
  subtitle?: unknown
  body?: unknown
  badge?: unknown
  category?: unknown
  'content-available'?: unknown
  payload?: Record<string, unknown>
  'user-text'?: unknown
  'action-identifier'?: unknown
  [key: string]: unknown
}

// detox's documented sendUserNotification data, converted the way detox ios
// builds it (DetoxUserNotificationDispatcher.payload): the user info is the
// custom `payload`, with the top-level title, subtitle, and body written into
// its aps alert and badge, category, and content-available written into its
// aps. a top-level key that is absent removes the payload's own value, as
// assigning nil to a swift dictionary does; every other aps key survives.
function detoxNotificationToApnsPayload(params: DetoxUserNotificationParams): {
  payload: Record<string, unknown>
  actionId?: string
  userText?: string
} {
  const trigger = objectOrEmpty(objectOrEmpty(params).trigger)
  const supported = ['push', 'calendar', 'location', 'timeInterval']
  if (typeof trigger.type !== 'string' || !supported.includes(trigger.type)) {
    throw new Error(
      `Missing trigger or invalid trigger type. A 'trigger' key must exist, with one of the following types: '${supported.join("', '")}'`,
    )
  }
  if (trigger.type !== 'push') {
    throw new Error(
      `sootsim device.sendUserNotification: trigger type '${trigger.type}' is not simulated, only 'push'`,
    )
  }
  const assign = (record: Record<string, unknown>, key: string, value: unknown) => {
    if (value === undefined) delete record[key]
    else record[key] = value
  }
  const payload = { ...objectOrEmpty(params.payload) }
  const aps = { ...objectOrEmpty(payload.aps) }
  const alert = { ...objectOrEmpty(aps.alert) }
  assign(alert, 'title', params.title)
  assign(alert, 'subtitle', params.subtitle)
  assign(alert, 'body', params.body)
  aps.alert = alert
  assign(aps, 'badge', params.badge)
  assign(aps, 'category', params.category)
  assign(aps, 'content-available', params['content-available'])
  payload.aps = aps
  return {
    payload,
    actionId:
      typeof params['action-identifier'] === 'string'
        ? params['action-identifier']
        : undefined,
    userText: typeof params['user-text'] === 'string' ? params['user-text'] : undefined,
  }
}

function objectOrEmpty(value: unknown): Record<string, unknown> {
  return value !== null && typeof value === 'object' && !Array.isArray(value)
    ? { ...value }
    : {}
}

interface PreparedRemotePush {
  payload: Record<string, unknown>
  actionId?: string
  userText?: string
}

async function postPreparedRemotePush(
  prepared: PreparedRemotePush,
  launch: boolean,
): Promise<void> {
  const { payload, actionId, userText } = prepared
  const page = getPage()
  await page.evaluate(
    ({ request }) => {
      const bridges = (
        window as unknown as {
          SootSim?: {
            bridges?: {
              shellHost?: { postNativeUIRequest?: (request: unknown) => unknown }
            }
          }
        }
      ).SootSim?.bridges
      // the shell host queues requests until the shell worker connects, so a
      // post here never silently drops. (mainShell.postNativeUIRequest would
      // swallow a not-yet-connected shell and report success.)
      const target = bridges?.shellHost
      const post = target?.postNativeUIRequest
      if (typeof post !== 'function') {
        throw new Error(
          'sootsim device.sendUserNotification: simulator shell unavailable — call device.launchApp() first',
        )
      }
      post.call(target, request)
    },
    {
      request: {
        kind: 'notification.remote-push',
        payload,
        launch,
        ...(actionId !== undefined ? { actionId } : {}),
        ...(userText !== undefined ? { userText } : {}),
      },
    },
  )
}

async function postRemotePushToSimulator(
  params: DetoxUserNotificationParams,
  launch: boolean,
): Promise<void> {
  await postPreparedRemotePush(detoxNotificationToApnsPayload(params), launch)
}

// the onset search steps finer than a display frame so it stops close to the
// change the native leg saw on its first moving frame
const ONSET_STEP_MS = 1000 / 240

// when another platform has no recorded stage times, search for the progress
// of its first stored native stage within this window around the nominal time
const PHASE_SEARCH_MS = 1000 / 30
// a card crosses about seven device pixels per millisecond, so a finer step fits its text
const PHASE_STEP_MS = 0.25
// native bar items start at the first vsync after their card's commit, so a
// recording's bar trails its fitted card by zero to one 60hz frame
const BAR_LAG_SEARCH_MS = 1000 / 60

// the stored native leg lives at
// <proof dir>/<target>/<case>/<checkpoint> and the prefix is `<case>-<checkpoint>`
function storedNativeCheckpoint(namePrefix: string) {
  const nativeTarget = `${DETOX_PLATFORM}${(process.env.APPEARANCE_REPORTED || process.env.APPEARANCE) === 'dark' ? '-dark' : ''}`
  const targetDir = path.resolve(
    process.cwd(),
    process.env.CONFORMANCE_PROOF_DIR || 'artifacts/conformance-proof/latest',
    nativeTarget,
  )
  if (!fs.existsSync(targetDir)) return null
  for (const caseName of fs.readdirSync(targetDir)) {
    if (!namePrefix.startsWith(`${caseName}-`)) continue
    const checkpointDir = path.join(
      targetDir,
      caseName,
      namePrefix.slice(caseName.length + 1),
    )
    return checkpointDir
  }
  return null
}

const isProgressStage = (stage: {
  offsetMs: number
  nativeActualMs?: number
  anchor?: object
}) => stage.offsetMs > 0 && stage.nativeActualMs === undefined && !stage.anchor

export const device = {
  _currentUrl: '',
  _platform: DETOX_PLATFORM as 'ios' | 'android',

  async launchApp(opts?: {
    delete?: boolean
    newInstance?: boolean
    // detox permission presets for the guest app, deposited into the
    // permission store's own database before navigation through a page
    // init script, so the store hydrates with them before any guest
    // evaluation — like detox setting the simulator before launching. a
    // resumed launch applies to the running guest without remounting. ios
    // only: native android silently ignores launchApp permissions, so
    // peach android ignores them too — a genuinely fresh android store
    // instead starts with every runtime permission granted, like native's
    // install -g, while carried state survives relaunches.
    permissions?: DetoxLaunchPermissions
    url?: string
    fetchProxySpki?: string
    sourceApp?: string
    launchArgs?: Record<string, any>
    // launch from a notification, like detox launchApp({ userNotification }):
    // dispatched during launch, so the app receives its tap response.
    userNotification?: DetoxUserNotificationParams
    // when set, the new BrowserContext records video at this dir. used by
    // captureProofMenuStages for the multi-stage animation diff path. must
    // be set at launchApp time because playwright recordVideo can't be
    // toggled on an existing context.
    recordVideoDir?: string
  }) {
    if (_browserCompromised) {
      throw new Error(`sootsim browser is compromised: ${_browserCompromised}`)
    }
    if (opts?.fetchProxySpki) {
      if (!/^[A-Za-z0-9+/]{43}=$/.test(opts.fetchProxySpki))
        throw new Error('sootsim fetch proxy requires a SHA-256 public-key pin')
      if (_browser || _browserLaunch)
        throw new Error('sootsim fetch proxy pin must be set on a fresh browser')
    }
    const newInstance = opts?.newInstance ?? !_page
    if (_page && !newInstance && !opts?.delete && !opts?.recordVideoDir) {
      const page = _page
      const appId = await page.evaluate(async () => {
        const state = await window.SootSim?.bridges?.mainShell?.getState?.()
        const guestApp = state?.guestApp
        if (typeof guestApp !== 'string') {
          throw new Error('SootSim main shell reports no guest app')
        }
        if (state?.state === 'app' && state.activeApp === guestApp) return null
        window.SootSim?.bridges?.mainShell?.launchApp?.(guestApp)
        return guestApp
      })
      if (appId !== null) {
        await pollUntil(
          () =>
            page.evaluate(async (id) => {
              const state = await window.SootSim?.bridges?.mainShell?.getState?.()
              return (
                state?.state === 'app' &&
                state.activeApp === id &&
                state.switcherPhase === 'idle'
              )
            }, appId),
          Boolean,
          {
            timeoutMs: 10000,
            label: `SootSim app ${appId} to resume`,
          },
        )
      }
      await waitForSootsimTree(page, 10000)
      if (opts?.permissions && DETOX_PLATFORM === 'ios') {
        await applyDetoxLaunchPermissions(page, opts.permissions)
      }
      if (opts?.url) {
        await device.openURL({ url: opts.url, sourceApp: opts.sourceApp })
      }
      if (opts?.userNotification) {
        await postRemotePushToSimulator(opts.userNotification, true)
      }
      return
    }

    const url = opts?.url || BASE_URL
    // the pre-boot permission seed is pure data computed before any
    // browser work: the owner id plus the init script that deposits it
    // into the localstorage inbox ahead of navigation.
    const bootSeed = permissionBootSeed(url, DETOX_PLATFORM, opts?.permissions)

    if (!_browser && !_browserLaunch) {
      _browserLaunchAbort = new AbortController()
      const signal = _browserLaunchAbort.signal
      const admission = globalThis.__peachChromiumAdmission ?? {
        signal,
        acquire: () => reserveChromiumAdmission(signal),
      }
      _browserLaunch = (async () => {
        const executablePath = chromium.executablePath()
        if (!fs.existsSync(executablePath)) {
          const requireDriver = createRequire(path.join(__dirname, 'index.cjs'))
          const cliPath = path.join(
            path.dirname(requireDriver.resolve('playwright-core/package.json')),
            'cli.js',
          )
          try {
            await promisify(execFile)(
              process.execPath,
              [cliPath, 'install', 'chromium'],
              {
                timeout: 600_000,
                maxBuffer: 4 * 1024 * 1024,
              },
            )
          } catch (error) {
            throw new Error('Peach Detox could not install its Chromium browser', {
              cause: error,
            })
          }
        }
        // conformance renders canvaskit and must use the real platform gpu. the
        // bundled chromium_headless_shell has no GPU and silently falls back to
        // swiftshader, invalidating visual/perf results while pegging the box.
        // the canonical gpu args force metal/vulkan and stripping playwright's
        // --enable-unsafe-swiftshader default makes gpu init fail loudly. the
        // scoped reaper owns the whole chrome process tree if detox is interrupted.
        const launched = await launchReapedChromeScoped(
          (options) => chromium.launch(options),
          {
            headless: true,
            ignoreDefaultArgs: ['--disable-popup-blocking'],
            ...(opts?.fetchProxySpki
              ? { args: [`--ignore-certificate-errors-spki-list=${opts.fetchProxySpki}`] }
              : {}),
          },
          undefined,
          { admission },
        )
        _browser = launched.browser
        _reapBrowserNow = launched.reapNow
        browserIdentity = ++nextBrowserIdentity
      })()
    }
    if (_browserLaunch) {
      try {
        await _browserLaunch
      } finally {
        _browserLaunch = null
      }
    }

    if (!_page || newInstance || opts?.delete || opts?.recordVideoDir) {
      await closeContext(!opts?.delete)
      const contextOpts: Parameters<NonNullable<typeof _browser>['newContext']>[0] = {
        hasTouch: true,
        viewport: { width: 500, height: 900 },
        storageState: _appStorageState,
      }
      if (opts?.recordVideoDir) {
        fs.mkdirSync(opts.recordVideoDir, { recursive: true })
        contextOpts.recordVideo = {
          dir: opts.recordVideoDir,
          size: { width: 500, height: 900 },
        }
      }
      const newContextIdentity = ++nextContextIdentity
      try {
        _context = await withLifecycleTimeout(
          '_browser.newContext()',
          newContextIdentity,
          () => _browser!.newContext(contextOpts),
        )
      } catch (error) {
        _browserCompromised = error instanceof Error ? error.message : String(error)
        reapOwnedBrowser()
        throw error
      }
      // deposit the permission seed before the first navigation: the init
      // script runs ahead of every engine script, so the store hydrates
      // with the seed before any guest evaluation can read it.
      if (bootSeed.script) {
        await _context.addInitScript(bootSeed.script)
      }
      await getCliRuntime().webview_automation_host.automateWebViewFrames(
        _context,
        getCliRuntime().webview_automation_host.webViewAutomationNames(
          `peachwv${randomBytes(12).toString('hex')}`,
          getCliRuntime().components_native_ui_webview_frame_bridge
            .WEBVIEW_HOST_BOOTSTRAP_SOURCE,
        ),
        getCliRuntime().webview_automation_host.webViewAutomationHelpers,
        (page) => page.workers(),
      )
      await _context.exposeBinding('__sootsimHostCapture', async (source, value) => {
        const request =
          getCliRuntime().capture_browser_composite.readBrowserCompositeCaptureRequest(
            value,
          )
        const session = await source.page.context().newCDPSession(source.page)
        try {
          const { clip, originX, originY } =
            getCliRuntime().capture_browser_composite.resolveBrowserCompositeCdpClip(
              request,
              await session.send('Page.getLayoutMetrics'),
            )
          const result = await session.send('Page.captureScreenshot', {
            format: 'png',
            fromSurface: true,
            clip,
          })
          return { dataUrl: 'data:image/png;base64,' + result.data, originX, originY }
        } finally {
          await session.detach()
        }
      })
      try {
        _page = await withLifecycleTimeout('_context.newPage()', newContextIdentity, () =>
          _context!.newPage(),
        )
      } catch (error) {
        _browserCompromised = error instanceof Error ? error.message : String(error)
        reapOwnedBrowser()
        throw error
      }
      await getCliRuntime().web_authentication_automation_host.automateWebAuthenticationSessions(
        _context!,
        '__peachWebAuthenticationHost',
        _page,
        false,
      )
      contextIdentity = newContextIdentity
    }

    // the bridge hands a prepared native build to the first request that
    // names its token, so each launch prepares its own: a shared token goes to
    // whichever page fetches first, and the case launch then rebuilds inside
    // the tree wait.
    const launchUrl = new URL(url)
    const openToken = randomUUID()
    launchUrl.searchParams.set('inspectOpen', openToken)
    await awaitStampedExpoSwiftReady(
      launchUrl.href,
      openToken,
      DETOX_PLATFORM,
      _nativePrepareAbort.signal,
    )

    // the requested url, not the per-launch token the page navigates to
    device._currentUrl = url
    await navigateSootsimPage(_page!, launchUrl.href, {
      browserId: browserIdentity,
      contextId: contextIdentity,
      operation: 'launchApp',
    })

    if (opts?.userNotification) {
      // detox dispatches the launch notification before the app's js runs.
      // the shell and tenant channels queue it until they connect, so it is
      // posted once, as soon as the shell accepts requests.
      const prepared = detoxNotificationToApnsPayload(opts.userNotification)
      await pollUntil(
        () =>
          postPreparedRemotePush(prepared, true).then(
            () => true,
            () => false,
          ),
        Boolean,
        {
          timeoutMs: 60000,
          label: 'SootSim shell to accept launch notification',
        },
      )
    }

    // every fresh launch seeded pre-boot through the init script above —
    // owned seeds persist before the worker exists, ownerless ones ride
    // the shell worker boot message and apply on the launched app's
    // first read. no post-mount fallback: it could never precede the
    // first guest read.
    await waitForSootsimTree(_page!, 30000)
    await waitForSootsimSurfaceMetrics(_page!, 30000)
    await waitForSootsimShellReady(_page!, 30000)
    await waitForSootsimWorkletsIdle(_page!, 3000)
    // record the wall-clock time the page is ready — captureProofMenuStages
    // uses this to compute trigger-in-video offsets
    device._lastReadyAtMs = Date.now()
  },

  _lastReadyAtMs: 0,

  async reloadReactNative() {
    const page = getPage()
    // native detox reloads the js bundle inside the running app process: the
    // old react tree and runtime retire and a new one mounts. the shell page
    // stays loaded and the tenant worker is replaced in place. the bridge
    // resolves once the new tenant's display is ready.
    await page.evaluate(() => window.SootSim!.bridges.hotRemount!.reloadExternalApp())
    await waitForSootsimTree(page, 30000)
    await waitForSootsimSurfaceMetrics(page, 30000)
    await waitForSootsimShellReady(page, 30000)
    await waitForSootsimWorkletsIdle(page, 3000)
  },

  async terminateApp() {
    await closeBrowser(true)
  },

  async installApp() {
    // no-op for sootsim -- app runs in browser
  },

  async uninstallApp() {
    await closeBrowser(false)
  },

  async openURL(url: { url: string; sourceApp?: string }) {
    const page = getPage()
    if (_synchronizationEnabled) await waitForSootsimIdle(page, 3000, false, 0)
    // native Linking exposes only { url }; sourceApp belongs to the OS payload.
    // use the same tenant bridge as the shell's openUrl command.
    await page.evaluate(async (target) => {
      const result = await window.__sootsimTest?.openDeepLink(target)
      if (!result?.ok) {
        throw new Error(result?.error || 'SootSim deep-link delivery failed')
      }
    }, url.url)
    if (_synchronizationEnabled) await waitForSootsimIdle(page)
  },

  // detox device.sendUserNotification on ios: the notification goes straight
  // to the app's notification center delegate. an active app gets willPresent;
  // otherwise the app gets the tap response.
  async sendUserNotification(params: DetoxUserNotificationParams) {
    await postRemotePushToSimulator(params, false)
  },

  async takeScreenshot(name: string): Promise<string> {
    return writeSootsimScreenshot(name)
  },

  // recreate a design own-paint layer over the scene it was captured from.
  async takeScreenshotOwnPaint(name: string, testID: string): Promise<string> {
    const target = await findNodeByMatcher(by.id(testID))
    if (!target) throw new Error(`own-paint capture target not found: ${testID}`)
    const page = getPage()
    const dataUrl = await page.evaluate(async (id) => {
      const screenshot = window.SootSim!.bridges.screenshot!
      const background = await screenshot({
        layers: 'tenant',
        format: 'png',
        captureFilter: { hideTestIds: [id] },
      })
      const ownPaint = await screenshot({
        layers: 'tenant',
        format: 'png',
        captureFilter: { soloTestId: id, soloOwnPaint: true },
      })
      const backdrop = await createImageBitmap(await (await fetch(background)).blob())
      const layer = await createImageBitmap(await (await fetch(ownPaint)).blob())
      const canvas = document.createElement('canvas')
      canvas.width = backdrop.width
      canvas.height = backdrop.height
      const context = canvas.getContext('2d')!
      context.drawImage(backdrop, 0, 0)
      context.drawImage(layer, 0, 0)
      backdrop.close()
      layer.close()
      return canvas.toDataURL('image/png')
    }, testID)
    ensureScreenshotDir()
    const screenshotPath = path.join(SCREENSHOT_DIR, name + '.png')
    fs.writeFileSync(screenshotPath, decodePngDataUrl(dataUrl))
    return screenshotPath
  },

  // single-shot variant for multi-stage animation captures. skips the
  // frame-stability poll so callers can sample mid-transition.
  async takeScreenshotFast(name: string): Promise<string> {
    ensureScreenshotDir()
    const screenshotPath = path.join(SCREENSHOT_DIR, `${name}.png`)
    fs.writeFileSync(screenshotPath, await captureSootsimPngFast())
    return screenshotPath
  },

  // record the SootSim canvas via the engine's headless recorder
  // (window.__sootsimRecorder — @rnx/plugin-recording). this is the
  // SAME code path `peach record video` drives, NOT the rail-button
  // path (SootSim.bridges.startRecording wires the dialog state machine
  // and never stashes the resulting blob into __sootsimRecorder.lastBlob,
  // which is what getBlobBase64 streams from).
  //
  // unlike playwright's page-level recordVideo, the headless recorder
  // captures ONLY the device canvas (composited shell + tenant surfaces)
  // — no browser chrome, no menu bar, no device frame. uses the EXISTING
  // page/context so per-test state is preserved across capture.
  async startBridgeRecording(opts?: {
    durationMs?: number
    layers?: 'full' | 'tenant' | 'shell'
    fps?: number
  }): Promise<void> {
    const page = getPage()
    const startOpts = {
      format: 'webm' as const,
      fps: opts?.fps ?? 60,
      layers: opts?.layers ?? 'tenant',
      durationMs: opts?.durationMs ?? 5000,
    }
    const result = await page.evaluate(async (startOpts) => {
      const rec = (
        window as {
          __sootsimRecorder?: {
            start?: (
              o: unknown,
            ) => Promise<{ ok: boolean; error?: string; format?: string }>
          }
        }
      ).__sootsimRecorder
      const start = rec?.start
      if (typeof start !== 'function') {
        return { ok: false, error: '__sootsimRecorder.start not installed' }
      }
      return start(startOpts)
    }, startOpts)
    if (!result.ok) {
      throw new Error(`startBridgeRecording failed: ${result.error ?? 'unknown'}`)
    }
  },

  // stop the headless recorder, stream the resulting blob in chunks (same
  // protocol as `peach record`), and write the webm to outPath.
  async stopAndSaveBridgeRecording(outPath: string): Promise<string> {
    const page = getPage()
    const stopResult = await page.evaluate(async () => {
      const rec = (
        window as {
          __sootsimRecorder?: {
            stop?: () => Promise<{
              ok: boolean
              error?: string
              size?: number
              mime?: string
              durationMs?: number
            }>
          }
        }
      ).__sootsimRecorder
      const stop = rec?.stop
      if (typeof stop !== 'function') {
        return { ok: false, error: '__sootsimRecorder.stop not installed' }
      }
      return stop()
    })
    if (!stopResult.ok) {
      throw new Error(`stopBridgeRecording failed: ${stopResult.error ?? 'unknown'}`)
    }
    if (!stopResult.size) {
      throw new Error('stopBridgeRecording: recorder returned empty blob')
    }
    const chunks: Buffer[] = []
    let offset = 0
    const CHUNK = 2 * 1024 * 1024
    while (true) {
      const result: {
        data: string
        size: number
        offset: number
        done: boolean
        mime: string
      } | null = await page.evaluate(
        ({ offset, chunk }) => {
          const rec = (window as { __sootsimRecorder?: { getBlobBase64?: unknown } })
            .__sootsimRecorder
          const get = rec?.getBlobBase64 as
            | ((args: { offset: number; chunk: number }) => Promise<{
                data: string
                size: number
                offset: number
                done: boolean
                mime: string
              } | null>)
            | undefined
          if (typeof get !== 'function') return null
          return get({ offset, chunk })
        },
        { offset, chunk: CHUNK },
      )
      if (!result) throw new Error('peach recorder produced no blob')
      chunks.push(Buffer.from(result.data, 'base64'))
      offset = result.offset
      if (result.done) break
    }
    fs.mkdirSync(path.dirname(outPath), { recursive: true })
    fs.writeFileSync(outPath, Buffer.concat(chunks))
    ;(this as { _lastRecordingPath?: string })._lastRecordingPath = outPath
    return outPath
  },

  _lastRecordingPath: '' as string,

  // park every render clock before the interaction, detect the first changed
  // stepped frame inside the named component, then advance exact 60fps frames
  // to each requested offset. native extraction also chooses the first frame
  // at or after an offset, so both sides use the same rounding convention.
  async beginProofFrameObservation(
    cadence: DiscreteFrameCadence,
    probeRect: { x: number; y: number; width: number; height: number },
    rootRect: { x: number; y: number; width: number; height: number },
    binding: DiscreteProofBinding,
    stages: readonly { label: string; offsetMs: number }[] = [],
  ) {
    if (!binding || !binding.captureNonce || !binding.attemptNonce)
      throw new Error('peach discrete observer needs an issued capture binding')
    if (
      binding.clock !== 'peach-virtual' ||
      JSON.stringify(binding.rootRect) !== JSON.stringify(rootRect) ||
      JSON.stringify(binding.probeRect) !== JSON.stringify(probeRect)
    )
      throw new Error('peach discrete observer geometry differs from its issued capture')
    const page = getPage()
    await page.evaluate(requireProofObserver().classifyDiscreteFrame, {
      installGlobal: true,
    })
    await page.evaluate(
      async ({ cadence, probeRect, rootRect, binding, stages }) => {
        type Bridges = {
          liveComposite: {
            captureFresh: () => Promise<{ canvas: HTMLCanvasElement | null }>
          }
          lockstepCapture: {
            begin: (fps: number) => Promise<{
              framesForOffset: (offsetMs: number) => number
              stepFrame: () => Promise<{ frameIndex: number; virtualTimestampMs: number }>
              end: () => void
            }>
          }
        }
        const isBridges = (value: unknown): value is Bridges => {
          if (
            !value ||
            typeof value !== 'object' ||
            !('liveComposite' in value) ||
            !('lockstepCapture' in value)
          )
            return false
          const live = value.liveComposite,
            clock = value.lockstepCapture
          return Boolean(
            live &&
            typeof live === 'object' &&
            'captureFresh' in live &&
            typeof live.captureFresh === 'function' &&
            clock &&
            typeof clock === 'object' &&
            'begin' in clock &&
            typeof clock.begin === 'function',
          )
        }
        const engine: unknown = Reflect.get(window, 'SootSim')
        if (
          !engine ||
          typeof engine !== 'object' ||
          !('bridges' in engine) ||
          !isBridges(engine.bridges)
        )
          throw new Error(
            'peach discrete observation needs live composite and lockstep bridges',
          )
        if (window.__peachDiscreteObserver)
          throw new Error('peach discrete observer already owns the clock')
        const { liveComposite, lockstepCapture } = engine.bridges
        const classify = window.__peachClassifyDiscreteFrame
        if (!classify) throw new Error('peach discrete classifier is missing')
        const controller = await lockstepCapture.begin(60)
        const probe = document.createElement('canvas')
        const context = probe.getContext('2d', { willReadFrequently: true })
        if (!context) {
          controller.end()
          throw new Error('peach discrete probe needs a canvas')
        }
        const rows: DiscreteFrameObservation[] = []
        const startedAtMs = performance.now()
        let totalProbeBytes = 0,
          maximumProbeBytes = 0,
          requestedPngs = 0
        let baseMs: number | null = null
        let currentMs = 0
        let anchorMs: number | null = null
        let anchorFrameIndex = 0
        const stageFrames: DiscreteStageFrame[] = []
        const observeTick = async () => {
          const receipt = await controller.stepFrame()
          if (baseMs === null) baseMs = receipt.virtualTimestampMs
          currentMs = receipt.virtualTimestampMs - baseMs
          const { canvas } = await liveComposite.captureFresh()
          if (!canvas) throw new Error('peach discrete probe has no presented canvas')
          const sx = canvas.width / rootRect.width,
            sy = canvas.height / rootRect.height
          const x = Math.round((probeRect.x - rootRect.x) * sx),
            y = Math.round((probeRect.y - rootRect.y) * sy)
          const width = Math.round(probeRect.width * sx),
            height = Math.round(probeRect.height * sy)
          if (
            x < 0 ||
            y < 0 ||
            width <= 0 ||
            height <= 0 ||
            x + width > canvas.width ||
            y + height > canvas.height
          )
            throw new Error('peach discrete probe escapes its measured frame')
          if (probe.width !== width || probe.height !== height) {
            probe.width = width
            probe.height = height
          }
          context.drawImage(canvas, x, y, width, height, 0, 0, width, height)
          const pixels = context.getImageData(0, 0, width, height).data
          totalProbeBytes += pixels.byteLength
          maximumProbeBytes = Math.max(maximumProbeBytes, pixels.byteLength)
          const classification = classify({ pixels, frames: cadence.asset.frames })
          if (!classification)
            throw new Error('peach discrete probe has no phase classification')
          rows.push({ frameIndex: rows.length, atMs: currentMs, ...classification })
          if (
            cadence.mode === 'playing' &&
            rows.length > 1 &&
            anchorMs === null &&
            classification.phase === cadence.entryFrame &&
            rows[0].phase !== cadence.entryFrame
          ) {
            anchorMs = currentMs
            anchorFrameIndex = rows.length - 1
          }
          if (anchorMs !== null) {
            const next = stages[stageFrames.length]
            if (
              next &&
              rows.length - 1 >=
                anchorFrameIndex + controller.framesForOffset(next.offsetMs)
            ) {
              requestedPngs++
              stageFrames.push({
                ...next,
                actualMs: currentMs - anchorMs,
                frameIndex: rows.length - 1,
                virtualTimestampMs: currentMs,
                dataUrl: canvas.toDataURL('image/png'),
              })
            }
          }
        }
        try {
          await observeTick()
          window.__peachDiscreteObserver = {
            stages: () => stageFrames,
            step: async (durationMs) => {
              if (!Number.isFinite(durationMs) || durationMs < 0)
                throw new Error('peach discrete wait needs a nonnegative duration')
              const endFrame = rows.length - 1 + controller.framesForOffset(durationMs)
              const horizonFrame =
                cadence.mode === 'playing' && anchorMs !== null
                  ? anchorFrameIndex + controller.framesForOffset(1900)
                  : null
              while (rows.length - 1 < endFrame) {
                if (horizonFrame !== null && rows.length - 1 >= horizonFrame) {
                  await new Promise((resolve) => setTimeout(resolve, 1000 / 60))
                  break
                }
                await observeTick()
              }
            },
            entry: async () => {
              if (cadence.mode !== 'playing')
                throw new Error('frozen observer has no playback entry')
              while (anchorMs === null && currentMs <= 3000) await observeTick()
              if (anchorMs !== null) return anchorMs
              throw new Error(
                'peach discrete playback has no declared entry before 3000ms',
              )
            },
            recordCapture: () => {
              requestedPngs++
            },
            finish: () => ({
              binding,
              cadence,
              observations: rows,
              cost: {
                wallMs: performance.now() - startedAtMs,
                observedFrames: rows.length,
                totalProbeBytes,
                maximumProbeBytes,
                requestedPngs,
              },
              clock: 'peach-virtual',
              coverageStartMs: 0,
              coverageEndMs: currentMs,
              triggerMs: 0,
              windowMs:
                cadence.mode === 'playing'
                  ? 1900
                  : cadence.waitIntervalsMs.reduce((a, b) => a + b, 0),
            }),
            close: () => {
              controller.end()
              delete window.__peachDiscreteObserver
            },
          }
        } catch (error) {
          controller.end()
          throw error
        }
      },
      { cadence, probeRect, rootRect, binding, stages },
    )
    _proofFrameObservationActive = true
  },

  async waitProofFrameObservation(durationMs: number) {
    return getPage().evaluate(async (durationMs) => {
      if (!window.__peachDiscreteObserver)
        throw new Error('peach discrete observer is missing')
      const startMs = window.__peachDiscreteObserver.finish().coverageEndMs
      await window.__peachDiscreteObserver.step(durationMs)
      return { startMs, endMs: window.__peachDiscreteObserver.finish().coverageEndMs }
    }, durationMs)
  },

  async dispatchProofFrameOperation<T>(operation: () => T | Promise<T>) {
    let completed = false
    const outcome = Promise.resolve()
      .then(operation)
      .then(
        (value) => {
          completed = true
          return { succeeded: true, value }
        },
        (error: unknown) => {
          completed = true
          return { succeeded: false, error }
        },
      )
    let completedVirtualMs = 0
    while (!completed) {
      const interval = await this.waitProofFrameObservation(1000 / 60)
      completedVirtualMs = interval.endMs
    }
    const result = await outcome
    if ('error' in result) throw result.error
    return { completedVirtualMs, value: result.value }
  },

  async endProofFrameObservation() {
    try {
      return await getPage().evaluate(() => {
        const observer = window.__peachDiscreteObserver
        if (!observer) throw new Error('peach discrete observer is missing')
        try {
          return observer.finish()
        } finally {
          observer.close()
        }
      })
    } finally {
      _proofFrameObservationActive = false
    }
  },

  async takeDiscreteFrameStagesFast(
    namePrefix: string,
    stages: Array<{ label: string; offsetMs: number }>,
    options: {
      binding: DiscreteProofBinding
      cadence: DiscreteFrameCadence
      probeRect: { x: number; y: number; width: number; height: number }
      rootRect: { x: number; y: number; width: number; height: number }
      trigger: () => unknown
      settleMs: number
    },
  ) {
    if (
      options.cadence.mode !== 'playing' ||
      Math.max(...stages.map((stage) => stage.offsetMs)) + options.settleMs !== 1900
    )
      throw new Error('discrete stages need the original playing horizon')
    await this.beginProofFrameObservation(
      options.cadence,
      options.probeRect,
      options.rootRect,
      options.binding,
      stages,
    )
    const page = getPage()
    const triggerStartMs = Date.now()
    let primary: unknown = null
    let ended = false
    try {
      await this.dispatchProofFrameOperation(options.trigger)
      const triggerCompletedMs = Date.now()
      const anchorMs = await page.evaluate(async () => {
        if (!window.__peachDiscreteObserver)
          throw new Error('peach discrete observer is missing')
        return window.__peachDiscreteObserver.entry()
      })
      const remainingMs = await page.evaluate((anchorMs) => {
        const observer = window.__peachDiscreteObserver
        if (!observer) throw new Error('peach discrete observer is missing')
        return Math.max(0, anchorMs + 1900 - observer.finish().coverageEndMs)
      }, anchorMs)
      await this.waitProofFrameObservation(remainingMs)
      const frames = await page.evaluate(() => {
        if (!window.__peachDiscreteObserver)
          throw new Error('peach discrete observer is missing')
        return window.__peachDiscreteObserver.stages()
      })
      if (frames.length !== stages.length)
        throw new Error('discrete capture missed requested stages')
      const discreteTrace = await this.endProofFrameObservation()
      ended = true
      const anchorFrame = discreteTrace.observations.find((row) => row.atMs === anchorMs)
      if (!anchorFrame) throw new Error('discrete capture has no observed anchor frame')
      discreteTrace.triggerStartedAtMs = triggerStartMs
      discreteTrace.triggerCompletedAtMs = triggerCompletedMs
      discreteTrace.completedAtMs = Date.now()
      return {
        frames: writeFastScreenshotFrames(namePrefix, frames),
        triggerStartMs,
        triggerCompletedMs,
        discreteTrace,
        driveStart: {
          frameIndex: anchorFrame.frameIndex,
          virtualTimestampMs: anchorMs,
        },
        anchors: [],
        visibleChangeDetection: {
          actualMs: anchorMs,
          frame: options.probeRect,
          rootFrame: options.rootRect,
        },
      }
    } catch (error) {
      primary = error
      throw error
    } finally {
      if (!ended) {
        try {
          await this.endProofFrameObservation()
        } catch (cleanup) {
          if (primary)
            throw new AggregateError(
              [primary, cleanup],
              'discrete capture and clock cleanup failed',
            )
          throw cleanup
        }
      }
    }
  },

  async takeScreenshotStagesFromVisibleChangeFast(
    namePrefix: string,
    stages: Array<{
      label: string
      offsetMs: number
      // the time after the onset at which the paired native leg sampled this
      // stage; the stage is sampled at that time instead of the nominal offset
      nativeActualMs?: number
      // the stored native frames whose changed-pixel progress this stage is
      // sampled at, set on the first timed stage only
      nativeProgress?: { baselinePng: string; png: string }
      // the stored native frame of the first moving timed stage: the Peach
      // sample nearest it sets the phase every later stage keeps
      nativePhaseFramePng?: string
      // the stored native frame of a stage after the phase stage: the first one
      // the bar-item clock lag changes fixes the lag that reproduces this recording
      nativeBarFramePng?: string
      anchor?: { id: string; notBeforeMs: number; onsetThresholdPercent?: number }
    }>,
    options: {
      detectionTimeoutMs?: number
      workletFrameTimestampsSeconds?: number[]
      workletFrameTracePath?: string
      frame?: { height: number; width: number; x: number; y: number } | null
      // a pointer the capture itself presses at the trigger point and releases
      // once durationMs of lockstep time has elapsed, so held states (a lifted
      // control thumb, a pressed row) are painted mid-hold. moves drag the
      // held pointer to each point once afterMs of lockstep time has elapsed
      // since the press. an explicit release position preserves witnessed up coordinates.
      hold?: {
        durationMs: number
        eventDurationMs?: number
        firstFrameOffsetMs?: number
        release?: { x: number; y: number }
        moves?: Array<{ afterMs: number; eventAfterMs?: number; x: number; y: number }>
        x: number
        y: number
      } | null
      // stages measure from the delivered press ('down') or release ('up')
      // of the capture-owned hold or trigger-owned gesture, rather than
      // from the first visible change.
      anchorAtTouch?: 'down' | 'up'
      producerWitness?: {
        testId?: string
        producerKind?: string
        nativeOffsetMs: number
        nativeFirstFrameOffsetMs: number
      }
      // witnessed input replays native delivered times and samples the
      // declared offsets directly, as the native lane does.
      witnessedInput?: boolean
      rootFrame?: { height: number; width: number; x: number; y: number } | null
      settleMs?: number
      trigger?: () => unknown
    },
  ): Promise<{
    inputReceipts: LockstepInputReceipt[]
    anchors: Array<{
      changedPixelPercent: number
      frameIndex: number
      id: string
      notBeforeMs: number
      virtualTimestampMs: number
    }>
    driveStart: {
      frameIndex: number
      virtualTimestampMs: number
      guestNowMs?: number | null
      guestClockFrozen?: boolean | null
    }
    producerFrameWitness: {
      id: number
      registeredMs: number
      firstFrameMs: number | null
    } | null
    frames: Array<{
      label: string
      offsetMs: number
      actualMs: number
      anchorId: string
      path: string
      frameIndex: number
      virtualTimestampMs: number
      samplingTargetTimestampMs?: number
    }>
    triggerCompletedMs: number
    triggerStartMs: number
    visibleChangeDetection: {
      actualMs: number
      changedPixelPercent: number
      changedPixels: number
      channelThreshold: number
      frame: { height: number; width: number; x: number; y: number } | null
      minimumChangePercent: number
      rootFrame: { height: number; width: number; x: number; y: number } | null
      totalPixels: number
      frameIndex: number
      virtualTimestampMs: number
    } | null
  }> {
    const page = getPage()
    const token = `motion-${process.pid}-${Date.now()}-${Math.random()}`
    const settleMs = options.settleMs ?? 0
    if (!Number.isFinite(settleMs) || settleMs < 0) {
      throw new Error('peach motion capture needs a non-negative settleMs')
    }
    const proofObserver = requireProofObserver()
    await page.evaluate(proofObserver.measureMotionChange, {
      definition: proofObserver.motionChangeDefinition,
      installGlobal: true,
    })
    if (options.workletFrameTracePath) {
      await page.evaluate(async (limit) => {
        const enable = window.SootSim?.bridges?.test?.setShellReanimatedTraceEnabled
        if (typeof enable !== 'function')
          throw new Error('worklet trace bridge is absent')
        await enable(true, true, limit)
      }, WORKLET_FRAME_TRACE_LIMIT)
    }
    const nativeCheckpoint = storedNativeCheckpoint(namePrefix)
    const nativeStagesPath =
      nativeCheckpoint && path.join(nativeCheckpoint, 'stages.json')
    const nativeRecord: {
      stages: Array<{
        label: string
        captureMode?: string
        mediaActualMs?: number
        touchOffsetMs?: number
      }>
      videoTriggerDetection?: { changedPixelPercent: number }
    } | null =
      nativeStagesPath && fs.existsSync(nativeStagesPath)
        ? JSON.parse(fs.readFileSync(nativeStagesPath, 'utf8'))
        : null
    const nativeStages = nativeRecord?.stages ?? []
    // native first sees the motion on a 60Hz display frame that can land deep
    // into the curve; the onset here is the first step showing as much change,
    // so both legs measure their stages from the same progress. a native
    // onset that changed the whole region asks for the most a minimum allows.
    const onsetChangePercent = Math.min(
      Math.max(
        proofObserver.motionChangeDefinition.minimumChangePercent,
        nativeRecord?.videoTriggerDetection?.changedPixelPercent ?? 0,
      ),
      99.9,
    )
    const pairedStages: typeof stages = stages.map((stage) => {
      if (DETOX_PLATFORM !== 'ios') return stage
      // ios media times share the native stage's detected anchor. actualMs on
      // a settled native screenshot uses a different clock and cannot seed it.
      const { nativeActualMs: _nativeActualMs, ...rest } = stage
      const nativeStage = nativeStages.find((native) => native.label === stage.label)
      const mediaActualMs = nativeStage?.mediaActualMs
      if (
        nativeStagesPath &&
        fs.existsSync(nativeStagesPath) &&
        mediaActualMs === undefined &&
        nativeStage?.captureMode !== 'lossless-settled-frame'
      ) {
        throw new Error(`native motion stage ${stage.label} has no recorded media time`)
      }
      // the native sample keeps its time since its last delivered touch;
      // take out that touch's delivery delay so this lane adds its own
      return mediaActualMs === undefined
        ? rest
        : {
            ...rest,
            nativeActualMs:
              mediaActualMs -
              ((nativeStage?.touchOffsetMs ?? stage.offsetMs) - stage.offsetMs),
          }
    })
    const progressStageIndex =
      DETOX_PLATFORM === 'ios' ||
      pairedStages.some((stage) => stage.nativeActualMs !== undefined)
        ? -1
        : pairedStages.findIndex(isProgressStage)
    const nativeBaselineLabel = nativeStages[0]?.label
    // only a drive anchored on its first visible change carries native's
    // display phase; a touch or witnessed anchor already shares its clock
    const phaseStageIndex =
      DETOX_PLATFORM === 'ios' &&
      !options.anchorAtTouch &&
      !options.producerWitness &&
      !options.hold &&
      !options.witnessedInput
        ? pairedStages.findIndex(
            (stage) =>
              stage.offsetMs > 0 && stage.nativeActualMs !== undefined && !stage.anchor,
          )
        : -1
    const capturePromise: Promise<{
      workletFirstDelivery: { first: number | null; initial: number } | null
      inputReceipts: LockstepInputReceipt[]
      producerFrameWitness: {
        id: number
        registeredMs: number
        firstFrameMs: number | null
      } | null
      anchors: Array<{
        changedPixelPercent: number
        frameIndex: number
        id: string
        notBeforeMs: number
        virtualTimestampMs: number
      }>
      driveStart: {
        frameIndex: number
        virtualTimestampMs: number
        guestNowMs?: number | null
        guestClockFrozen?: boolean | null
      }
      frames: Array<
        FastScreenshotData & {
          anchorId: string
          frameIndex: number
          virtualTimestampMs: number
          samplingTargetTimestampMs?: number
        }
      >
      visibleChangeDetection: {
        actualMs: number
        changedPixelPercent: number
        changedPixels: number
        channelThreshold: number
        frameIndex: number
        minimumChangePercent: number
        totalPixels: number
        virtualTimestampMs: number
      } | null
    }> = page.evaluate(
      async (input) => {
        type CaptureWindow = Window & {
          __sootsimMeasureMotionChange?: (input: {
            baseline: Uint8ClampedArray
            candidate: Uint8ClampedArray
            definition: MotionChangeDefinition
            height: number
            label: string
            width: number
          }) => MotionChangeMeasurement
          SootSim?: {
            bridges?: {
              interact?: Required<
                Pick<SootSimInteractBridge, 'touchDown' | 'touchMove' | 'touchUp'>
              >
              test?: {
                findByTestId: (
                  id: string,
                ) => Promise<{ accessibilityValue?: { text?: string } } | null>
                startProducerFrameCapture: (kind: string) => Promise<void>
                readProducerFrameCapture: () => Promise<
                  { id: number; registeredMs: number; firstFrameMs: number | null }[]
                >
                stopProducerFrameCapture: () => Promise<void>
              }
              liveComposite?: {
                captureFresh: () => Promise<{
                  canvas: HTMLCanvasElement | null
                  frameToken: number
                }>
              }
            }
          }
        }
        type Snapshot = {
          actualMs: number
          anchorId: string
          bitmap: ImageBitmap
          label: string
          offsetMs: number
          frameIndex: number
          virtualTimestampMs: number
          samplingTargetTimestampMs?: number
        }

        const captureWindow = window as unknown as CaptureWindow
        const live = captureWindow.SootSim?.bridges?.liveComposite
        const lockstep = captureWindow.SootSim?.bridges?.lockstepCapture
        if (!live || typeof live.captureFresh !== 'function') {
          throw new Error('peach live composite bridge is not installed')
        }
        if (!lockstep || typeof lockstep.begin !== 'function') {
          throw new Error('SootSim lockstep capture bridge is not installed')
        }
        const registry =
          captureWindow.__sootsimVisibleChangeCaptures ??
          (captureWindow.__sootsimVisibleChangeCaptures = {})
        const state: VisibleChangeCaptureState = {
          cancelled: false,
          ready: false,
          triggerStarted: false,
          triggerCompleted: false,
        }
        registry[input.token] = state
        const measureChange = captureWindow.__sootsimMeasureMotionChange
        if (!measureChange) {
          throw new Error('peach motion change definition is not installed')
        }

        const captureBitmap = async () => {
          const { canvas } = await live.captureFresh()
          if (!canvas) throw new Error('peach live composite produced no canvas')
          return createImageBitmap(canvas)
        }
        const boundsFor = (bitmap: ImageBitmap) => {
          const scale =
            input.rootFrame && input.rootFrame.width > 0
              ? bitmap.width / input.rootFrame.width
              : 1
          return {
            height: input.frame
              ? Math.max(
                  1,
                  Math.min(
                    bitmap.height,
                    Math.ceil((input.frame.y + input.frame.height) * scale),
                  ) - Math.max(0, Math.floor(input.frame.y * scale)),
                )
              : bitmap.height,
            left: input.frame ? Math.max(0, Math.floor(input.frame.x * scale)) : 0,
            top: input.frame ? Math.max(0, Math.floor(input.frame.y * scale)) : 0,
            width: input.frame
              ? Math.max(
                  1,
                  Math.min(
                    bitmap.width,
                    Math.ceil((input.frame.x + input.frame.width) * scale),
                  ) - Math.max(0, Math.floor(input.frame.x * scale)),
                )
              : bitmap.width,
          }
        }
        const regionPixels = (bitmap: ImageBitmap) => {
          const bounds = boundsFor(bitmap)
          const canvas = document.createElement('canvas')
          canvas.width = bounds.width
          canvas.height = bounds.height
          const context = canvas.getContext('2d', { willReadFrequently: true })
          if (!context) throw new Error('peach motion detector needs a 2d canvas')
          context.drawImage(
            bitmap,
            bounds.left,
            bounds.top,
            bounds.width,
            bounds.height,
            0,
            0,
            bounds.width,
            bounds.height,
          )
          return context.getImageData(0, 0, bounds.width, bounds.height).data
        }
        const encode = (snapshot: Snapshot) => {
          const canvas = document.createElement('canvas')
          canvas.width = snapshot.bitmap.width
          canvas.height = snapshot.bitmap.height
          const context = canvas.getContext('2d')
          if (!context) throw new Error('peach motion capture needs a 2d canvas')
          context.drawImage(snapshot.bitmap, 0, 0)
          snapshot.bitmap.close()
          return {
            actualMs: snapshot.actualMs,
            anchorId: snapshot.anchorId,
            dataUrl: canvas.toDataURL('image/png'),
            label: snapshot.label,
            offsetMs: snapshot.offsetMs,
            frameIndex: snapshot.frameIndex,
            virtualTimestampMs: snapshot.virtualTimestampMs,
            samplingTargetTimestampMs: snapshot.samplingTargetTimestampMs,
          }
        }

        const interact = captureWindow.SootSim?.bridges?.interact
        if (input.hold && (!interact || typeof interact.touchDown !== 'function')) {
          throw new Error('peach interact bridge is not installed')
        }
        const pairedPeerStats = async (reset = false) => {
          const stats = await captureWindow.SootSim?.bridges?.test?.getPeerStats?.(reset)
          if (!stats || !Number.isSafeInteger(stats.replayedFrameCallbacks))
            throw new Error(
              'paired worklets clock needs native frame delivery diagnostics',
            )
          return stats
        }
        if (input.workletFrameTimestampsSeconds) await pairedPeerStats(true)
        const controller = await lockstep.begin(60, {
          workletFrameTimestampsSeconds: input.workletFrameTimestampsSeconds,
        })
        const producerTest = captureWindow.SootSim?.bridges?.test
        if (input.producerWitness?.producerKind) {
          if (!producerTest) throw new Error('producer capture requires the test bridge')
          await producerTest.startProducerFrameCapture(input.producerWitness.producerKind)
        }
        let producerFrameWitness: {
          id: number
          registeredMs: number
          firstFrameMs: number | null
        } | null = null
        let heldInput: Promise<void> | null = null
        const releaseReceipt = () =>
          controller.inputReceipts.find((receipt) => receipt.phase === 'up')
        // an anchor is its visible-change frame; its bitmap is kept so a 0ms
        // stage can still capture the anchor frame itself.
        const keptFrames = new Map<
          number,
          { bitmap: ImageBitmap; receipt: SootSimLockstepFrameReceipt }
        >()
        const keepFrame = (receipt: SootSimLockstepFrameReceipt, bitmap: ImageBitmap) => {
          keptFrames.get(receipt.frameIndex)?.bitmap.close()
          keptFrames.set(receipt.frameIndex, { bitmap, receipt })
        }
        try {
          const baselineBitmap = await captureBitmap()
          const baselinePixels = regionPixels(baselineBitmap)
          const baselineSize = `${baselineBitmap.width}x${baselineBitmap.height}`
          // a trigger that moves the app to another display (a duo unfold)
          // draws its stages on a display that was dark before it, as native
          const baseline = (bitmap: ImageBitmap) => {
            if (`${bitmap.width}x${bitmap.height}` === baselineSize) return baselinePixels
            const bounds = boundsFor(bitmap)
            const dark = new Uint8ClampedArray(bounds.width * bounds.height * 4)
            for (let offset = 3; offset < dark.length; offset += 4) dark[offset] = 255
            return dark
          }
          // the press lands before the first stepped frame, so the screen it
          // lands on is the baseline itself
          if (input.anchorAtTouch === 'down')
            keepFrame(controller.initialFrame, baselineBitmap)
          else baselineBitmap.close()
          if (
            input.workletFrameTimestampsSeconds &&
            (await pairedPeerStats()).replayedFrameCallbacks > 0
          )
            throw new Error('paired worklets callback preceded the Peach trigger')
          state.ready = true
          if (input.hold && interact) {
            const hold = input.hold
            const moves = hold.moves ?? []
            const release = hold.release ?? moves.at(-1) ?? hold
            const events: LockstepScheduledInput[] = [
              {
                phase: 'down',
                x: hold.x,
                y: hold.y,
                pointerId: 999,
                afterMs: 0,
                async deliver(timestamp) {
                  const hit = await interact.touchDown(hold.x, hold.y, 999, timestamp)
                  if (!hit)
                    throw new Error(`peach motion hold missed at ${hold.x},${hold.y}`)
                },
              },
              ...moves.map(
                (move): LockstepScheduledInput => ({
                  phase: 'move',
                  x: move.x,
                  y: move.y,
                  pointerId: 999,
                  afterMs: move.afterMs,
                  eventAfterMs: move.eventAfterMs,
                  async deliver(timestamp: number) {
                    await interact.touchMove(move.x, move.y, 999, timestamp)
                  },
                }),
              ),
              {
                phase: 'up',
                x: release.x,
                y: release.y,
                pointerId: 999,
                afterMs: hold.durationMs,
                eventAfterMs: hold.eventDurationMs,
                async deliver(timestamp) {
                  await interact.touchUp(release.x, release.y, 999, timestamp)
                },
              },
            ]
            heldInput = controller.scheduleInput(events)
            // rendering propagates delivery errors; also observe cancellation rejection.
            heldInput.catch(() => {})
            await controller.flushFrame()
          } else {
            // the paired receipt starts after native touch-up. target lookup
            // and synthetic press delivery must finish before consuming it.
            while (
              !(input.workletFrameTimestampsSeconds && !input.anchorAtTouch
                ? state.triggerCompleted
                : state.triggerStarted)
            ) {
              if (state.cancelled) throw new Error('peach motion capture was cancelled')
              await new Promise((resolve) => setTimeout(resolve, 0))
            }
            if (input.anchorAtTouch) {
              // the trigger owns its gesture schedule. flush without advancing
              // time until its press lands, keeping target lookup off the clock.
              while (
                !controller.inputReceipts.some((receipt) => receipt.phase === 'down')
              ) {
                if (state.cancelled) throw new Error('peach motion capture was cancelled')
                await controller.flushFrame()
                if (controller.inputReceipts.some((receipt) => receipt.phase === 'down'))
                  break
                if (state.triggerCompleted)
                  throw new Error('peach touch anchoring found no delivered press')
                await new Promise((resolve) => setTimeout(resolve, 0))
              }
            }
          }

          let visibleStart: SootSimLockstepFrameReceipt | null = null
          let detectedMeasurement: MotionChangeMeasurement | null = null
          let previousBitmap: ImageBitmap | null = null
          const detectionFrameLimit = controller.framesForOffset(input.detectionTimeoutMs)
          const onsetFrameLimit = Math.ceil(input.detectionTimeoutMs / input.onsetStepMs)
          const onsetDefinition = {
            ...input.motionChangeDefinition,
            minimumChangePercent: input.onsetChangePercent,
          }
          // a touch anchor takes stage zero from the delivered touch on both
          // legs, so no visible change gates its drive; a feedback below the
          // change minimum still captures, as it does natively.
          // android can publish mount layout at p=0 before a clock step.
          if (!input.anchorAtTouch && input.platform === 'android') {
            // time zero needs the same producer publication fence as stepped
            // frames; intermediate tree paints are not a transition onset.
            const receipt = await controller.flushFrame()
            const candidateBitmap = await captureBitmap()
            const bounds = boundsFor(candidateBitmap)
            const measurement = measureChange({
              baseline: baseline(candidateBitmap),
              candidate: regionPixels(candidateBitmap),
              definition: onsetDefinition,
              height: bounds.height,
              label: 'peach initial-frame visible-change detector',
              width: bounds.width,
            })
            if (measurement.passedMinimum) {
              visibleStart = receipt
              detectedMeasurement = measurement
              keepFrame(visibleStart, candidateBitmap)
            } else {
              candidateBitmap.close()
            }
          }
          for (
            let frame = 0;
            !input.anchorAtTouch && !visibleStart && frame < onsetFrameLimit;
            frame++
          ) {
            if (state.cancelled) throw new Error('peach motion capture was cancelled')
            const receipt = await controller.stepFrame(input.onsetStepMs)
            const candidateBitmap = await captureBitmap()
            const bounds = boundsFor(candidateBitmap)
            const measurement = measureChange({
              baseline: baseline(candidateBitmap),
              candidate: regionPixels(candidateBitmap),
              definition: onsetDefinition,
              height: bounds.height,
              label: 'SootSim visible-change detector',
              width: bounds.width,
            })
            if (measurement.passedMinimum) {
              previousBitmap?.close()
              previousBitmap = null
              visibleStart = receipt
              detectedMeasurement = measurement
              keepFrame(receipt, candidateBitmap)
              break
            }
            previousBitmap?.close()
            previousBitmap = candidateBitmap
          }
          previousBitmap?.close()
          // stages on every platform measure from the first frame that
          // differs from baseline: native extraction anchors at its
          // detection frame's pts, so the drive starts here too. the
          // preceding tick is still baseline on both legs. a touch anchor
          // instead starts the drive at the press or at the frame that
          // delivers the touch-up.
          let driveStart: SootSimLockstepFrameReceipt
          let currentReceipt: SootSimLockstepFrameReceipt
          if (!input.anchorAtTouch) {
            if (!visibleStart || !detectedMeasurement) {
              throw new Error(
                `peach motion had no visible change before ${input.detectionTimeoutMs}ms`,
              )
            }
            driveStart = visibleStart
            currentReceipt = visibleStart
          } else if (input.anchorAtTouch === 'down') {
            const press = controller.inputReceipts.find(
              (receipt) => receipt.phase === 'down',
            )
            if (press?.frameIndex !== controller.initialFrame.frameIndex) {
              throw new Error(
                'peach press anchoring found no press delivered on the baseline frame',
              )
            }
            driveStart = controller.initialFrame
            currentReceipt = controller.initialFrame
          } else {
            currentReceipt = controller.initialFrame
            while (!releaseReceipt()) {
              if (state.cancelled) throw new Error('peach motion capture was cancelled')
              if (!input.hold && state.triggerCompleted)
                throw new Error('peach release anchoring found no delivered release')
              const receipt = await controller.stepFrame()
              currentReceipt = receipt
              if (releaseReceipt()) keepFrame(receipt, await captureBitmap())
            }
            const released = releaseReceipt()
            if (!released) {
              throw new Error('peach release anchoring found no release frame')
            }
            driveStart = {
              ...released,
              tenantFrame: currentReceipt.tenantFrame,
              stageMs: null,
            }
          }
          let producerOffsetMs = 0
          let nextFrameDurationMs = input.hold?.firstFrameOffsetMs
          if (input.producerWitness) {
            if (input.anchorAtTouch !== 'up' || !driveStart.tenantFrame?.guestClockFrozen)
              throw new Error(
                'producer witness requires a frozen delivered release clock',
              )
            const test = captureWindow.SootSim?.bridges?.test
            if (!test) throw new Error('producer witness requires the test bridge')
            let witnessed = false
            for (let frame = 0; frame < detectionFrameLimit; frame++) {
              if (input.producerWitness.producerKind) {
                const entries = await test.readProducerFrameCapture()
                if (entries.length > 1)
                  throw new Error('producer frame capture is ambiguous')
                const entry = entries[0]
                if (entry?.firstFrameMs !== null && entry !== undefined) {
                  if (
                    entry.registeredMs > entry.firstFrameMs ||
                    entry.firstFrameMs < driveStart.virtualTimestampMs
                  )
                    throw new Error('producer frame preceded the delivered release')
                  producerFrameWitness = entry
                  producerOffsetMs =
                    entry.firstFrameMs -
                    driveStart.virtualTimestampMs -
                    input.producerWitness.nativeFirstFrameOffsetMs
                  if (1000 / 60 + producerOffsetMs <= 0)
                    throw new Error(
                      `producer alignment precedes the next guest refresh: guest first callback ${entry.firstFrameMs - driveStart.virtualTimestampMs}ms after release, native first callback ${input.producerWitness.nativeFirstFrameOffsetMs}ms after release`,
                    )
                  nextFrameDurationMs = 1000 / 60 + producerOffsetMs
                  witnessed = true
                  break
                }
                currentReceipt = await controller.stepFrame(
                  frame === 0
                    ? input.producerWitness.nativeFirstFrameOffsetMs
                    : undefined,
                )
                continue
              }
              if (!input.producerWitness.testId)
                throw new Error('producer witness has no target')
              const value = (await test.findByTestId(input.producerWitness.testId))
                ?.accessibilityValue?.text
              const times = value?.split(',').map(Number)
              if (times?.length === 6 && times.every(Number.isFinite)) {
                const guestInputMs = driveStart.tenantFrame.guestNowMs
                if (
                  Math.abs(times[0]! * 1000 - guestInputMs) > 0.01 ||
                  times[1]! < times[0]! ||
                  times[2]! < times[1]! ||
                  times[5]! < times[0]! ||
                  times[5]! > times[2]!
                )
                  throw new Error(
                    'producer witness does not follow the delivered release',
                  )
                producerOffsetMs =
                  times[5]! * 1000 - guestInputMs - input.producerWitness.nativeOffsetMs
                if (1000 / 60 + producerOffsetMs <= 0)
                  throw new Error(
                    `producer alignment precedes the next guest refresh: guest animation start ${times[5]! * 1000 - guestInputMs}ms after release, native animation start ${input.producerWitness.nativeOffsetMs}ms after release`,
                  )
                nextFrameDurationMs = 1000 / 60 + producerOffsetMs
                witnessed = true
                break
              }
              // place the first refresh at the witnessed native producer
              // callback, then keep the usual refresh cadence.
              currentReceipt = await controller.stepFrame(
                frame === 0 ? input.producerWitness.nativeFirstFrameOffsetMs : undefined,
              )
            }
            if (!witnessed)
              throw new Error('producer display-link witness was not observed')
          }
          const resolvedAnchors = new Map<string, SootSimLockstepFrameReceipt>()
          const anchorRecords: Array<{
            changedPixelPercent: number
            frameIndex: number
            id: string
            notBeforeMs: number
            virtualTimestampMs: number
          }> = []
          // a second drive (the pop after a swipe's pan) re-detects from the
          // search start: the new drive is the passing frame itself, the
          // frame native reports as the onset atSec, mirroring the drive rule.
          const resolveAnchor = async (stage: {
            label: string
            anchor?: { id: string; notBeforeMs: number; onsetThresholdPercent?: number }
          }): Promise<{ anchorId: string; receipt: SootSimLockstepFrameReceipt }> => {
            const anchor = stage.anchor
            if (!anchor) return { anchorId: 'transition', receipt: driveStart }
            const known = resolvedAnchors.get(anchor.id)
            if (known) return { anchorId: anchor.id, receipt: known }
            if (
              typeof anchor.notBeforeMs !== 'number' ||
              !Number.isFinite(anchor.notBeforeMs) ||
              anchor.notBeforeMs < 0
            ) {
              throw new Error(
                `peach motion stage ${stage.label} anchor ${anchor.id} needs a non-negative notBeforeMs`,
              )
            }
            // proof.js owns the default and fills it; this backstop only
            // serves direct shim callers.
            const onsetThresholdPercent = anchor.onsetThresholdPercent ?? 5
            const searchStartFrame =
              driveStart.frameIndex + controller.framesForOffset(anchor.notBeforeMs)
            const searchStartVts = driveStart.virtualTimestampMs + anchor.notBeforeMs
            if (currentReceipt.frameIndex > searchStartFrame) {
              throw new Error(
                `peach motion anchor ${anchor.id} searches from ${anchor.notBeforeMs}ms but the clock already sits past it: the ladder is unexecutable`,
              )
            }
            // step, never jump, to the search start so hold moves land.
            let searchReceipt = currentReceipt
            while (searchReceipt.frameIndex < searchStartFrame) {
              if (state.cancelled) throw new Error('peach motion capture was cancelled')
              searchReceipt = await controller.stepFrame()
            }
            currentReceipt = searchReceipt
            let anchorBitmap = await captureBitmap()
            let previousPixels = regionPixels(anchorBitmap)
            let anchorReceipt = searchReceipt
            let onsetMeasurement: MotionChangeMeasurement | null = null
            // a missed second drive is a wrong gate or search start, never
            // jitter: the capture is lockstep-deterministic. report both
            // peaks so the failure calibrates the gate (the early window is
            // pan-only on every swipe lane: both releases land past it).
            let panPeakPercent = 0
            let latePeakPercent = 0
            for (let frame = 0; frame < detectionFrameLimit; frame++) {
              if (state.cancelled) throw new Error('peach motion capture was cancelled')
              const receipt = await controller.stepFrame()
              const candidateBitmap = await captureBitmap()
              const bounds = boundsFor(candidateBitmap)
              const candidate = regionPixels(candidateBitmap)
              const measurement = measureChange({
                baseline: previousPixels,
                candidate,
                definition: {
                  ...input.motionChangeDefinition,
                  minimumChangePercent: onsetThresholdPercent,
                },
                height: bounds.height,
                label: `SootSim second-drive detector ${anchor.id}`,
                width: bounds.width,
              })
              previousPixels = candidate
              currentReceipt = receipt
              if (receipt.virtualTimestampMs - searchStartVts < 250) {
                panPeakPercent = Math.max(panPeakPercent, measurement.changePercent)
              } else {
                latePeakPercent = Math.max(latePeakPercent, measurement.changePercent)
              }
              const passed = measurement.passedMinimum
              anchorBitmap.close()
              anchorBitmap = candidateBitmap
              anchorReceipt = receipt
              if (passed) {
                onsetMeasurement = measurement
                break
              }
            }
            if (!onsetMeasurement) {
              anchorBitmap.close()
              throw new Error(
                `peach motion anchor ${anchor.id} found no onset past ${onsetThresholdPercent}% within ${input.detectionTimeoutMs}ms of ${anchor.notBeforeMs}ms (pan peak ${panPeakPercent.toFixed(2)}%, later peak ${latePeakPercent.toFixed(2)}%): the gate or the search start is wrong for this surface`,
              )
            }
            keepFrame(anchorReceipt, anchorBitmap)
            resolvedAnchors.set(anchor.id, anchorReceipt)
            anchorRecords.push({
              changedPixelPercent: onsetMeasurement.changePercent,
              frameIndex: anchorReceipt.frameIndex,
              id: anchor.id,
              notBeforeMs: anchor.notBeforeMs,
              virtualTimestampMs: anchorReceipt.virtualTimestampMs,
            })
            return { anchorId: anchor.id, receipt: anchorReceipt }
          }

          // the hold's schedule in delivery order, in ms after the press.
          const holdScheduleMs = input.hold
            ? [
                0,
                ...(input.hold.moves ?? []).map((move) => move.afterMs),
                input.hold.durationMs,
              ].sort((a, b) => a - b)
            : []
          // transition stages take the native touch rule from the touches this
          // lane delivered, stepping until the last one due has landed. a
          // release anchor already sits on the delivered up, so its offsets
          // are up-relative and the press-relative schedule does not apply.
          // a native frame shown before its last touch landed pairs with the
          // touches it had seen (nativeActualMs keeps the schedule clock).
          const stageOffsetMs = async (
            offsetMs: number,
            anchorId: string,
            nativeActualMs = offsetMs,
          ) => {
            if (
              anchorId !== 'transition' ||
              input.witnessedInput ||
              input.anchorAtTouch === 'up'
            )
              return offsetMs
            const due = holdScheduleMs.filter(
              (scheduledMs) => scheduledMs <= Math.min(offsetMs, nativeActualMs),
            )
            while (controller.inputReceipts.length < due.length) {
              if (state.cancelled) throw new Error('peach motion capture was cancelled')
              currentReceipt = await controller.stepFrame()
            }
            const [press] = controller.inputReceipts
            return controller.stageTouchOffsetMs(
              due.map((scheduledMs, index) => ({
                scheduledMs,
                landedMs:
                  controller.inputReceipts[index].virtualTimestampMs -
                  press.virtualTimestampMs,
              })),
              offsetMs,
            )
          }

          const snapshots: Snapshot[] = []
          // use whole refreshes; ordinary timed captures may add a partial step
          const stepToTime = async (
            targetMs: number,
            sampledRefresh = false,
            label = '',
          ) => {
            let receipt = currentReceipt
            if (targetMs < receipt.virtualTimestampMs - 0.01) {
              throw new Error(
                `sample time ${targetMs}ms of ${label} precedes the frames already stepped to ${receipt.virtualTimestampMs}ms (anchor ${driveStart.virtualTimestampMs}ms, producer offset ${producerOffsetMs}ms)`,
              )
            }
            while (
              receipt.virtualTimestampMs + (nextFrameDurationMs ?? 1000 / 60) <=
              targetMs + 0.01
            ) {
              receipt = await controller.stepFrame(nextFrameDurationMs)
              nextFrameDurationMs = undefined
            }
            if (!sampledRefresh && targetMs - receipt.virtualTimestampMs > 0.01) {
              receipt = await controller.stepFrame(targetMs - receipt.virtualTimestampMs)
            }
            currentReceipt = receipt
            return receipt
          }
          const sampleAt = async (
            stage: { label: string; offsetMs: number },
            anchorReceipt: SootSimLockstepFrameReceipt,
            anchorId: string,
            targetMs: number,
          ) => {
            // retain the guest's last produced refresh at the native sample time
            // instead of creating an extra guest refresh at that time.
            // a held touch keeps the refresh cadence its press started, as the
            // native display does; a partial step would add a refresh native
            // never drew and move the later touches off their schedule.
            const sampledRefresh = Boolean(
              input.producerWitness || input.witnessedInput || input.hold,
            )
            const receipt = await stepToTime(targetMs, sampledRefresh, stage.label)
            snapshots.push({
              actualMs: receipt.virtualTimestampMs - anchorReceipt.virtualTimestampMs,
              anchorId,
              bitmap: await captureBitmap(),
              frameIndex: receipt.frameIndex,
              label: stage.label,
              offsetMs: stage.offsetMs,
              virtualTimestampMs: receipt.virtualTimestampMs,
              ...(sampledRefresh ? { samplingTargetTimestampMs: targetMs } : {}),
            })
          }
          const decode = async (png: string) =>
            createImageBitmap(await (await fetch(`data:image/png;base64,${png}`)).blob())
          const screenPixels = (bitmap: ImageBitmap) => {
            const canvas = document.createElement('canvas')
            canvas.width = bitmap.width
            canvas.height = bitmap.height
            const context = canvas.getContext('2d', { willReadFrequently: true })
            if (!context) throw new Error('peach phase fit needs a 2d canvas')
            context.drawImage(bitmap, 0, 0)
            return context.getImageData(0, 0, bitmap.width, bitmap.height).data
          }
          // a summed channel distance, since a card sliding over a dimmed
          // screen of nearly its own colour stays under the change threshold
          const screenDistance = (a: Uint8ClampedArray, b: Uint8ClampedArray) => {
            let diff = 0
            for (let i = 0; i < a.length; i += 4)
              diff +=
                Math.abs(a[i] - b[i]) +
                Math.abs(a[i + 1] - b[i + 1]) +
                Math.abs(a[i + 2] - b[i + 2])
            return diff
          }
          const nativeProgressPercent = async (progress: {
            baselinePng: string
            png: string
          }) => {
            const nativeBaseline = await decode(progress.baselinePng)
            const nativeStage = await decode(progress.png)
            const bounds = boundsFor(nativeStage)
            return measureChange({
              baseline: regionPixels(nativeBaseline),
              candidate: regionPixels(nativeStage),
              definition: input.motionChangeDefinition,
              height: bounds.height,
              label: 'native stage progress',
              width: bounds.width,
            }).changePercent
          }
          // the offset from the nominal time at which the first timed stage
          // reached the progress its native frame showed
          let phaseMs = 0
          let barLagFitted = false
          let barLagMinMs = 0
          for (const stage of input.stages) {
            if (state.cancelled) throw new Error('peach motion capture was cancelled')
            const { anchorId, receipt: anchorReceipt } = await resolveAnchor(stage)
            const touchOffsetMs = await stageOffsetMs(
              stage.offsetMs,
              anchorId,
              stage.nativeActualMs,
            )
            if (typeof stage.nativeActualMs === 'number') {
              // the native frame nearest touch-down can precede the touch. the
              // retained pre-press baseline is the matching Peach frame.
              if (
                input.anchorAtTouch === 'down' &&
                stage.offsetMs === 0 &&
                stage.nativeActualMs < 0 &&
                stage.nativeActualMs >= -1000 / 60
              ) {
                const baselineFrame = keptFrames.get(anchorReceipt.frameIndex)
                if (
                  !baselineFrame ||
                  currentReceipt.frameIndex !== anchorReceipt.frameIndex
                )
                  throw new Error('peach pre-press baseline is unavailable')
                snapshots.push({
                  actualMs: 0,
                  anchorId,
                  bitmap: await createImageBitmap(baselineFrame.bitmap),
                  frameIndex: baselineFrame.receipt.frameIndex,
                  label: stage.label,
                  offsetMs: stage.offsetMs,
                  virtualTimestampMs: baselineFrame.receipt.virtualTimestampMs,
                  samplingTargetTimestampMs:
                    anchorReceipt.virtualTimestampMs + stage.nativeActualMs,
                })
                continue
              }
              // sample the moment the native leg sampled, as long after this
              // lane's last delivered touch as native was after its own
              const nativeMs =
                anchorReceipt.virtualTimestampMs +
                stage.nativeActualMs +
                touchOffsetMs -
                stage.offsetMs +
                producerOffsetMs
              if (!stage.nativePhaseFramePng) {
                if (stage.nativeBarFramePng && !barLagFitted) {
                  const barMs = nativeMs + (anchorId === 'transition' ? phaseMs : 0)
                  await stepToTime(barMs, false, stage.label)
                  const nativeBar = await decode(stage.nativeBarFramePng)
                  const nativePixels = screenPixels(nativeBar)
                  nativeBar.close()
                  const lags: { diff: number; lagMs: number }[] = []
                  for (
                    let lagMs = barLagMinMs;
                    lagMs <= input.barLagSearchMs;
                    lagMs += 2
                  ) {
                    controller.setScreenBarClockLag(lagMs)
                    await controller.flushFrame()
                    const bitmap = await captureBitmap()
                    lags.push({
                      diff: screenDistance(screenPixels(bitmap), nativePixels),
                      lagMs,
                    })
                    bitmap.close()
                  }
                  // lags that render the same here have not reached the bar yet, so
                  // the lag stays open to every one of them until a later stage
                  // tells them apart, and this snapshot is the same for all
                  const bestDiff = Math.min(...lags.map((entry) => entry.diff))
                  const ties = lags.filter((entry) => entry.diff === bestDiff)
                  barLagMinMs = ties[0].lagMs
                  barLagFitted =
                    ties.length === 1 ||
                    ties[ties.length - 1].lagMs < lags[lags.length - 1].lagMs
                  controller.setScreenBarClockLag(barLagMinMs)
                  await controller.flushFrame()
                }
                await sampleAt(
                  stage,
                  anchorReceipt,
                  anchorId,
                  nativeMs + (anchorId === 'transition' ? phaseMs : 0),
                )
                continue
              }
              // native's motion began at a random point of its display frame, so
              // its onset frame sits up to a frame into the curve. the whole
              // screen nearest the native frame within the phase search window
              // gives the phase; the card's travel dominates it, so the bar's own
              // timing is still judged by every later stage.
              const nativeFrame = await decode(stage.nativePhaseFramePng)
              const nativePixels = screenPixels(nativeFrame)
              let receipt = await stepToTime(
                Math.max(
                  currentReceipt.virtualTimestampMs,
                  nativeMs - input.phaseSearchMs,
                ),
                false,
                stage.label,
              )
              let best: {
                bitmap: ImageBitmap
                diff: number
                receipt: typeof receipt
              } | null = null
              // the next stage samples its native gap after the best frame, so
              // the search stops there and every later stage stays ahead of it
              const stageNativeMs = stage.nativeActualMs
              const next = input.stages.find(
                (later) =>
                  typeof later.nativeActualMs === 'number' &&
                  later.nativeActualMs > stageNativeMs,
              )
              const gapMs =
                next?.nativeActualMs === undefined
                  ? Number.POSITIVE_INFINITY
                  : next.nativeActualMs - stageNativeMs
              for (;;) {
                const bitmap = await captureBitmap()
                if (
                  bitmap.width !== nativeFrame.width ||
                  bitmap.height !== nativeFrame.height
                )
                  throw new Error(
                    `peach phase fit compares ${bitmap.width}x${bitmap.height} with native ${nativeFrame.width}x${nativeFrame.height}`,
                  )
                const diff = screenDistance(screenPixels(bitmap), nativePixels)
                // frames that tie carry no phase, as before the motion reaches
                // the screen, so the latest of them is the nearest in phase
                if (!best || diff <= best.diff) {
                  best?.bitmap.close()
                  best = { bitmap, diff, receipt }
                } else {
                  bitmap.close()
                }
                const nextMs = receipt.virtualTimestampMs + input.phaseStepMs
                if (
                  nextMs > nativeMs + input.phaseSearchMs ||
                  nextMs > best.receipt.virtualTimestampMs + gapMs - 2
                )
                  break
                receipt = await controller.stepFrame(input.phaseStepMs)
                currentReceipt = receipt
              }
              nativeFrame.close()
              if (!best)
                throw new Error(`peach phase fit for ${stage.label} sampled nothing`)
              phaseMs = best.receipt.virtualTimestampMs - nativeMs
              snapshots.push({
                actualMs:
                  best.receipt.virtualTimestampMs - anchorReceipt.virtualTimestampMs,
                anchorId,
                bitmap: best.bitmap,
                frameIndex: best.receipt.frameIndex,
                label: stage.label,
                offsetMs: stage.offsetMs,
                virtualTimestampMs: best.receipt.virtualTimestampMs,
                samplingTargetTimestampMs: nativeMs,
              })
              continue
            }
            if (stage.nativeProgress) {
              const targetPercent = await nativeProgressPercent(stage.nativeProgress)
              const nominalMs = anchorReceipt.virtualTimestampMs + touchOffsetMs
              let receipt = currentReceipt
              while (
                receipt.virtualTimestampMs + 1000 / 60 <=
                nominalMs - input.phaseSearchMs
              ) {
                receipt = await controller.stepFrame()
              }
              let progressBitmap: ImageBitmap | null = null
              while (!progressBitmap) {
                if (receipt.virtualTimestampMs > nominalMs + input.phaseSearchMs) {
                  throw new Error(
                    `peach stage ${stage.label} never reached the native progress ${targetPercent}% within ${input.phaseSearchMs}ms of ${touchOffsetMs}ms`,
                  )
                }
                receipt = await controller.stepFrame(1)
                const candidateBitmap = await captureBitmap()
                const bounds = boundsFor(candidateBitmap)
                const progress = measureChange({
                  baseline: baseline(candidateBitmap),
                  candidate: regionPixels(candidateBitmap),
                  definition: input.motionChangeDefinition,
                  height: bounds.height,
                  label: 'peach stage progress',
                  width: bounds.width,
                }).changePercent
                if (progress >= targetPercent) progressBitmap = candidateBitmap
                else candidateBitmap.close()
              }
              currentReceipt = receipt
              phaseMs = receipt.virtualTimestampMs - nominalMs
              snapshots.push({
                actualMs: receipt.virtualTimestampMs - anchorReceipt.virtualTimestampMs,
                anchorId,
                bitmap: progressBitmap,
                frameIndex: receipt.frameIndex,
                label: stage.label,
                offsetMs: stage.offsetMs,
                virtualTimestampMs: receipt.virtualTimestampMs,
              })
              continue
            }
            if (phaseMs !== 0) {
              await sampleAt(
                stage,
                anchorReceipt,
                anchorId,
                anchorReceipt.virtualTimestampMs +
                  touchOffsetMs +
                  (anchorId === 'transition' ? phaseMs : 0),
              )
              continue
            }
            const stageFrameIndex =
              anchorReceipt.frameIndex + controller.framesForOffset(touchOffsetMs)
            const kept = keptFrames.get(stageFrameIndex)
            if (kept && stageFrameIndex <= currentReceipt.frameIndex) {
              snapshots.push({
                actualMs:
                  kept.receipt.virtualTimestampMs - anchorReceipt.virtualTimestampMs,
                anchorId,
                bitmap: await createImageBitmap(kept.bitmap),
                frameIndex: kept.receipt.frameIndex,
                label: stage.label,
                offsetMs: stage.offsetMs,
                virtualTimestampMs: kept.receipt.virtualTimestampMs,
              })
              continue
            }
            // partial steps to native stage times each count a frame, so a settled stage
            // without a native time can target a frame the clock already passed; its
            // virtual time has not.
            if (stageFrameIndex < currentReceipt.frameIndex) {
              await sampleAt(
                stage,
                anchorReceipt,
                anchorId,
                anchorReceipt.virtualTimestampMs + touchOffsetMs,
              )
              continue
            }
            const receipt = await controller.stepToOffset(anchorReceipt, touchOffsetMs)
            currentReceipt = receipt
            snapshots.push({
              actualMs: receipt.virtualTimestampMs - anchorReceipt.virtualTimestampMs,
              anchorId,
              bitmap: await captureBitmap(),
              frameIndex: receipt.frameIndex,
              label: stage.label,
              offsetMs: stage.offsetMs,
              virtualTimestampMs: receipt.virtualTimestampMs,
            })
          }
          // the native receipt was recorded through the last stage, not the
          // release and settle frames that follow it.
          if (input.workletFrameTimestampsSeconds) controller.endWorkletFrameReceipt()
          // a hold that outlasts the last stage still moves and releases on its
          // own frames; the settle jump below would carry the pointer past them
          // and leave it down. the settle then runs from that release.
          let releasedOffsetMs = 0
          while ((input.hold || input.anchorAtTouch) && !releaseReceipt()) {
            if (state.cancelled) throw new Error('peach motion capture was cancelled')
            if (!input.hold && state.triggerCompleted)
              throw new Error('peach touch anchoring found no delivered release')
            currentReceipt = await controller.stepFrame()
            releasedOffsetMs =
              currentReceipt.virtualTimestampMs - driveStart.virtualTimestampMs
          }
          await heldInput
          if (input.settleMs > 0) {
            const maximumPrimaryMs = snapshots.reduce(
              (maximum, snapshot) =>
                Math.max(
                  maximum,
                  snapshot.virtualTimestampMs - driveStart.virtualTimestampMs,
                ),
              releasedOffsetMs,
            )
            await stepToTime(
              driveStart.virtualTimestampMs + maximumPrimaryMs + input.settleMs,
            )
          }
          while (!state.triggerCompleted) {
            if (state.cancelled) throw new Error('peach motion capture was cancelled')
            await controller.stepFrame()
            await new Promise((resolve) => setTimeout(resolve, 0))
          }
          const stats = input.workletFrameTimestampsSeconds
            ? await pairedPeerStats()
            : null
          return {
            workletFirstDelivery: stats
              ? {
                  first: stats.nativeFrameFirstTimestampMs,
                  initial: controller.initialFrame.virtualTimestampMs,
                }
              : null,
            inputReceipts: controller.inputReceipts,
            producerFrameWitness,
            anchors: anchorRecords,
            driveStart: {
              frameIndex: driveStart.frameIndex,
              virtualTimestampMs: driveStart.virtualTimestampMs,
              guestNowMs: driveStart.tenantFrame?.guestNowMs ?? null,
              guestClockFrozen: driveStart.tenantFrame?.guestClockFrozen ?? null,
            },
            frames: snapshots.map(encode),
            visibleChangeDetection:
              visibleStart && detectedMeasurement
                ? {
                    actualMs: (visibleStart.frameIndex * 1000) / 60,
                    changedPixelPercent: detectedMeasurement.changePercent,
                    changedPixels: detectedMeasurement.changePixels,
                    channelThreshold: input.motionChangeDefinition.channelThreshold,
                    minimumChangePercent: input.onsetChangePercent,
                    totalPixels: detectedMeasurement.totalPixels,
                    frameIndex: visibleStart.frameIndex,
                    virtualTimestampMs: visibleStart.virtualTimestampMs,
                  }
                : null,
          }
        } finally {
          if (input.producerWitness?.producerKind && producerTest)
            await producerTest.stopProducerFrameCapture()
          for (const kept of keptFrames.values()) kept.bitmap.close()
          controller.end()
          delete registry[input.token]
        }
      },
      {
        workletFrameTimestampsSeconds: options.workletFrameTimestampsSeconds,
        detectionTimeoutMs: options.detectionTimeoutMs ?? 3000,
        onsetStepMs: ONSET_STEP_MS,
        onsetChangePercent,
        phaseSearchMs: PHASE_SEARCH_MS,
        phaseStepMs: PHASE_STEP_MS,
        barLagSearchMs: BAR_LAG_SEARCH_MS,
        frame: options.frame ?? null,
        anchorAtTouch: options.anchorAtTouch ?? null,
        producerWitness: options.producerWitness ?? null,
        witnessedInput: options.witnessedInput === true,
        hold: options.hold ?? null,
        motionChangeDefinition: proofObserver.motionChangeDefinition,
        platform: device.getPlatform(),
        rootFrame: options.rootFrame ?? null,
        settleMs,
        stages: pairedStages.map((stage, index) =>
          index === phaseStageIndex &&
          nativeCheckpoint &&
          fs.existsSync(path.join(nativeCheckpoint, `${stage.label}.png`))
            ? {
                ...stage,
                nativePhaseFramePng: fs
                  .readFileSync(path.join(nativeCheckpoint, `${stage.label}.png`))
                  .toString('base64'),
              }
            : index > phaseStageIndex &&
                phaseStageIndex >= 0 &&
                stage.nativeActualMs !== undefined &&
                nativeCheckpoint &&
                fs.existsSync(path.join(nativeCheckpoint, `${stage.label}.png`))
              ? {
                  ...stage,
                  nativeBarFramePng: fs
                    .readFileSync(path.join(nativeCheckpoint, `${stage.label}.png`))
                    .toString('base64'),
                }
              : index === progressStageIndex &&
                  nativeCheckpoint &&
                  nativeBaselineLabel &&
                  fs.existsSync(path.join(nativeCheckpoint, `${stage.label}.png`))
                ? {
                    ...stage,
                    nativeProgress: {
                      baselinePng: fs
                        .readFileSync(
                          path.join(nativeCheckpoint, `${nativeBaselineLabel}.png`),
                        )
                        .toString('base64'),
                      png: fs
                        .readFileSync(path.join(nativeCheckpoint, `${stage.label}.png`))
                        .toString('base64'),
                    },
                  }
                : stage,
        ),
        token,
      },
    )

    let captureFailure: { error: unknown } | undefined
    let triggerStartMs = 0
    let triggerCompletedMs = 0
    try {
      await Promise.race([
        page.waitForFunction(
          (captureToken) => {
            const registry = window.__sootsimVisibleChangeCaptures
            return registry?.[captureToken]?.ready === true
          },
          token,
          { timeout: 5000 },
        ),
        capturePromise.then(() => {
          throw new Error('peach motion capture completed before its trigger')
        }),
      ])

      triggerStartMs = Date.now()
      const triggerPromise = (async () => {
        if (!options.hold) {
          if (typeof options.trigger !== 'function') {
            throw new Error('peach motion capture needs a trigger or a hold')
          }
          const triggered = Promise.resolve().then(options.trigger)
          await page.evaluate((captureToken) => {
            const capture = window.__sootsimVisibleChangeCaptures?.[captureToken]
            if (!capture) throw new Error('peach motion capture disarmed before trigger')
            capture.triggerStarted = true
          }, token)
          await triggered
        }
        triggerCompletedMs = Date.now()
        await page.evaluate((captureToken) => {
          const capture = window.__sootsimVisibleChangeCaptures?.[captureToken]
          if (!capture) throw new Error('peach motion capture disarmed before trigger')
          capture.triggerCompleted = true
        }, token)
      })()
      const [capture] = await Promise.all([capturePromise, triggerPromise])
      if (capture.workletFirstDelivery) {
        const { first, initial } = capture.workletFirstDelivery
        const interval = 1000 / 60
        if (
          first === null ||
          !Number.isFinite(first) ||
          Math.abs(first - initial - interval) >
            frameTimingRoundingBound(first, initial, interval)
        )
          throw new Error(
            `paired worklets first delivery did not match the next UI frame: ${first}`,
          )
      }
      return {
        inputReceipts: capture.inputReceipts,
        producerFrameWitness: capture.producerFrameWitness,
        anchors: capture.anchors,
        driveStart: capture.driveStart,
        frames: writeFastScreenshotFrames(namePrefix, capture.frames),
        triggerCompletedMs,
        triggerStartMs,
        visibleChangeDetection: capture.visibleChangeDetection
          ? {
              ...capture.visibleChangeDetection,
              frame: options.frame ?? null,
              rootFrame: options.rootFrame ?? null,
            }
          : null,
      }
    } catch (error) {
      captureFailure = { error }
      await page
        .evaluate((captureToken) => {
          const registry = window.__sootsimVisibleChangeCaptures
          const capture = registry?.[captureToken]
          if (capture) capture.cancelled = true
        }, token)
        .catch(() => {})
      await capturePromise.catch(() => {})
      throw error
    } finally {
      if (options.workletFrameTracePath) {
        try {
          const events = await page.evaluate(async () => {
            const test = window.SootSim?.bridges?.test
            const read = test?.getShellReanimatedTrace
            const enable = test?.setShellReanimatedTraceEnabled
            if (typeof read !== 'function' || typeof enable !== 'function')
              throw new Error('worklet trace bridge is absent')
            try {
              return await read()
            } finally {
              await enable(false, false)
            }
          })
          fs.writeFileSync(
            options.workletFrameTracePath,
            JSON.stringify(
              {
                source: 'peach-native-frame-queue',
                limit: WORKLET_FRAME_TRACE_LIMIT,
                events,
              },
              null,
              2,
            ),
          )
        } catch (traceError) {
          if (!captureFailure) throw traceError
          const primary = captureFailure.error
          if (
            primary &&
            (typeof primary === 'object' || typeof primary === 'function') &&
            Object.isExtensible(primary)
          ) {
            try {
              Object.defineProperty(primary, 'workletFrameTraceError', {
                value: traceError,
                configurable: true,
              })
            } catch (attachmentError) {
              console.error(
                '[peach motion capture] could not attach trace failure:',
                attachmentError,
              )
            }
          }
          console.error(
            '[peach motion capture] secondary worklet trace failure:',
            traceError,
          )
        }
      }
    }
  },

  // FAST multi-stage capture for sub-second animation diffs. each stage
  // schedules a setTimeout at its requested offsetMs and at that moment
  // SYNCHRONOUSLY snapshots the engine's `liveComposite` host-side canvas
  // (drawImage from the worker-transferred home + overlay canvases). PNG
  // encoding is queued after all snapshots land — encoding stalls don't
  // contaminate the animation window.
  //
  // unlike `takeScreenshotStages`, this does NOT go through screenshot()
  // (which calls forceRenderAll + composite + toDataURL serially at
  // 300-1300ms per call and blows the spring-open timing). the worker's
  // vsync-pumped rAF keeps the home canvas fresh; we just sample it.
  //
  // returns paths in stage order; actualMs reports when the snapshot
  // actually fired (typically within a few ms of offsetMs).
  async takeScreenshotStagesFast(
    namePrefix: string,
    stages: Array<{ label: string; offsetMs: number; nativeActualMs?: number }>,
    options: {
      anchorAfterTrigger?: boolean
      skipWarmup?: boolean
      trigger: () => unknown
    },
  ): Promise<{
    captureAnchorMs: number
    frames: Array<{
      label: string
      offsetMs: number
      actualMs: number
      captureCompletedMs: number
      captureRequestedAtMs: number
      path: string
    }>
    triggerCompletedMs: number
    triggerStartMs: number
  }> {
    const page = getPage()
    const token = `timed-${process.pid}-${Date.now()}-${Math.random()}`
    // anchorAfterTrigger false anchors the stages at the moment the trigger
    // hands its input to the engine's interact bridge, after the trigger has
    // resolved its target. arming before the trigger counted node resolution
    // and layout polling as elapsed press time.
    const anchorOnInput = options.anchorAfterTrigger === false
    const capturePromise: Promise<{
      captureAnchorMs: number
      frames: Array<{
        label: string
        offsetMs: number
        actualMs: number
        captureCompletedMs: number
        captureRequestedAtMs: number
        dataUrl: string
      }>
    }> = page.evaluate(
      async (input) => {
        type CaptureState = {
          anchorOnInput: boolean
          anchorPerformanceMs: number | null
          anchorWallMs: number | null
          cancelled: boolean
          ready: boolean
        }
        type CaptureWindow = Window & {
          __sootsimTimedCaptures?: Record<string, CaptureState>
          SootSim?: {
            bridges?: {
              screenshot?: (opts?: unknown) => Promise<string>
              liveComposite?: {
                captureFresh: () => Promise<{
                  canvas: HTMLCanvasElement | null
                  frameToken: number
                }>
              }
            }
          }
        }
        const captureWindow = window as unknown as CaptureWindow
        const screenshot = captureWindow.SootSim?.bridges?.screenshot
        const live = captureWindow.SootSim?.bridges?.liveComposite
        if (typeof screenshot !== 'function') {
          throw new Error('peach screenshot bridge is not installed')
        }
        const registry =
          captureWindow.__sootsimTimedCaptures ??
          (captureWindow.__sootsimTimedCaptures = {})
        const state: CaptureState = {
          anchorOnInput: input.anchorOnInput,
          anchorPerformanceMs: null,
          anchorWallMs: null,
          cancelled: false,
          ready: false,
        }
        registry[input.token] = state
        window.__sootsimAnchorTimedInput = (token: string) => {
          const capture = registry[token]
          if (!capture) return
          if (!capture.anchorOnInput || !capture.ready) return
          if (capture.anchorPerformanceMs !== null) return
          const anchorPerformanceMs = performance.now()
          const anchorWallMs = Date.now()
          capture.anchorPerformanceMs = anchorPerformanceMs
          capture.anchorWallMs = anchorWallMs
        }
        // initial warm-up: ensure the worker has produced at least one
        // frame after the menu's portal mount before we start sampling.
        // (a pump at higher cadence was tried and starved tap propagation —
        // the tenant React commit for setOpen never landed between
        // forceRender calls.)
        if (!input.skipWarmup) {
          await screenshot({ format: 'png' })
        }
        state.ready = true
        while (state.anchorPerformanceMs === null || state.anchorWallMs === null) {
          if (state.cancelled) throw new Error('peach timed capture was cancelled')
          await new Promise((resolve) => setTimeout(resolve, 0))
        }
        const captureAnchorMs = state.anchorWallMs
        const captureAnchorPerformanceMs = state.anchorPerformanceMs
        type Snapshot = {
          label: string
          offsetMs: number
          actualMs: number
          captureCompletedMs: number
          captureRequestedAtMs: number
          dataUrl: string | null
        }
        // each stage fires at its requested offset and SYNCHRONOUSLY
        // snapshots the engine's host-side composite canvas (drawImage
        // from the worker-transferred home canvas + overlay). encoding
        // happens after — encoding stalls don't disturb the next stage's
        // capture moment.
        const snaps: Snapshot[] = await Promise.all(
          input.stages.map(
            (stage) =>
              new Promise<Snapshot>((resolve) => {
                const fire = async () => {
                  const actualMs = performance.now() - captureAnchorPerformanceMs
                  const captureRequestedAtMs = Date.now()
                  // the sample's content is fixed somewhere between the
                  // request and the completed composite paint; the engine
                  // exposes no producer timestamp for the frame it reads.
                  let captureCompletedMs = actualMs
                  try {
                    let dataUrl: string | null = null
                    if (live && typeof live.captureFresh === 'function') {
                      // synchronous paint of current canvas state — no
                      // worker round-trip. the background pump keeps the
                      // canvas fresh.
                      const { canvas } = await live.captureFresh()
                      captureCompletedMs = performance.now() - captureAnchorPerformanceMs
                      if (canvas) {
                        const bmp = await createImageBitmap(canvas)
                        const enc = document.createElement('canvas')
                        enc.width = bmp.width
                        enc.height = bmp.height
                        const ctx = enc.getContext('2d')
                        if (ctx) {
                          ctx.drawImage(bmp, 0, 0)
                          dataUrl = enc.toDataURL('image/png')
                        }
                        bmp.close()
                      }
                    }
                    if (!dataUrl) {
                      dataUrl = await screenshot({ format: 'png' })
                      captureCompletedMs = performance.now() - captureAnchorPerformanceMs
                    }
                    resolve({
                      label: stage.label,
                      offsetMs: stage.offsetMs,
                      actualMs,
                      captureCompletedMs,
                      captureRequestedAtMs,
                      dataUrl,
                    })
                  } catch {
                    resolve({
                      label: stage.label,
                      offsetMs: stage.offsetMs,
                      actualMs,
                      captureCompletedMs,
                      captureRequestedAtMs,
                      dataUrl: null,
                    })
                  }
                }
                setTimeout(
                  () => {
                    void fire()
                  },
                  Math.max(
                    0,
                    captureAnchorPerformanceMs +
                      (stage.nativeActualMs ?? stage.offsetMs) -
                      performance.now(),
                  ),
                )
              }),
          ),
        )
        const out: Array<{
          label: string
          offsetMs: number
          actualMs: number
          captureCompletedMs: number
          captureRequestedAtMs: number
          dataUrl: string
        }> = []
        for (const snap of snaps) {
          if (!snap.dataUrl) continue
          out.push({
            label: snap.label,
            offsetMs: snap.offsetMs,
            actualMs: snap.actualMs,
            captureCompletedMs: snap.captureCompletedMs,
            captureRequestedAtMs: snap.captureRequestedAtMs,
            dataUrl: snap.dataUrl,
          })
        }
        delete registry[input.token]
        return { captureAnchorMs, frames: out }
      },
      { anchorOnInput, stages, skipWarmup: options.skipWarmup === true, token },
    )

    await page.waitForFunction(
      (captureToken) => {
        const registry = (
          window as Window & {
            __sootsimTimedCaptures?: Record<string, { ready: boolean }>
          }
        ).__sootsimTimedCaptures
        return registry?.[captureToken]?.ready === true
      },
      token,
      { timeout: 5000 },
    )

    const armCapture = (anchorMs: number) =>
      page.evaluate(
        ({ anchorMs, captureToken }) => {
          const registry = (
            window as Window & {
              __sootsimTimedCaptures?: Record<
                string,
                {
                  anchorPerformanceMs: number | null
                  anchorWallMs: number | null
                  ready: boolean
                }
              >
            }
          ).__sootsimTimedCaptures
          const capture = registry?.[captureToken]
          if (!capture?.ready) throw new Error('peach timed capture was not armed')
          capture.anchorWallMs = anchorMs
          capture.anchorPerformanceMs = performance.now() - (Date.now() - anchorMs)
          return capture.anchorWallMs
        },
        { anchorMs, captureToken: token },
      )

    let triggerStartMs = 0
    let triggerCompletedMs = 0
    try {
      let captureAnchorMs: number
      if (anchorOnInput) {
        triggerStartMs = Date.now()
        ;(page as any).__sootsimCaptureToken = token
        try {
          await Promise.resolve(options.trigger())
        } finally {
          delete (page as any).__sootsimCaptureToken
        }
        triggerCompletedMs = Date.now()
        // the capture deletes its entry once every stage is sampled, which
        // can precede a long trigger's return; only a live entry can be unanchored
        const unanchored = await page.evaluate(
          (captureToken) =>
            (
              window as Window & {
                __sootsimTimedCaptures?: Record<string, { anchorWallMs: number | null }>
              }
            ).__sootsimTimedCaptures?.[captureToken]?.anchorWallMs === null,
          token,
        )
        if (unanchored) {
          throw new Error(
            'peach timed capture: the trigger completed without dispatching input to anchor its stages',
          )
        }
        const capture = await capturePromise
        return {
          captureAnchorMs: capture.captureAnchorMs,
          frames: writeFastScreenshotFrames(namePrefix, capture.frames),
          triggerCompletedMs,
          triggerStartMs,
        }
      }

      triggerStartMs = Date.now()
      await Promise.resolve(options.trigger())
      triggerCompletedMs = Date.now()
      captureAnchorMs = await armCapture(triggerCompletedMs)
      const capture = await capturePromise
      return {
        captureAnchorMs,
        frames: writeFastScreenshotFrames(namePrefix, capture.frames),
        triggerCompletedMs,
        triggerStartMs,
      }
    } catch (error) {
      await page
        .evaluate((captureToken) => {
          const registry = (
            window as Window & {
              __sootsimTimedCaptures?: Record<string, { cancelled: boolean }>
            }
          ).__sootsimTimedCaptures
          const capture = registry?.[captureToken]
          if (capture) capture.cancelled = true
        }, token)
        .catch(() => {})
      await capturePromise.catch(() => {})
      throw error
    }
  },

  // batched multi-stage capture for animation diffs. all N captures happen
  // inside one page.evaluate round trip so browser-side timing controls the
  // offsets — sidesteps the ~300ms per-call bridge overhead that blows
  // sub-second animation windows. each stage gets a screenshot at the
  // requested offsetMs (from when the evaluate starts, i.e. right after
  // trigger() returns). returns absolute paths in stage order.
  async takeScreenshotStages(
    namePrefix: string,
    stages: Array<{ label: string; offsetMs: number }>,
  ): Promise<Array<{ label: string; offsetMs: number; actualMs: number; path: string }>> {
    const page = getPage()
    const frames: Array<{
      label: string
      offsetMs: number
      actualMs: number
      dataUrl: string
    }> = await page.evaluate(
      async (input) => {
        const screenshot = (
          window as { SootSim?: { bridges?: { screenshot?: unknown } } }
        ).SootSim?.bridges?.screenshot as
          | ((opts?: unknown) => Promise<string>)
          | undefined
        if (typeof screenshot !== 'function') {
          throw new Error('peach screenshot bridge is not installed')
        }
        const start = Date.now()
        const out: Array<{
          label: string
          offsetMs: number
          actualMs: number
          dataUrl: string
        }> = []
        for (const stage of input.stages) {
          const elapsed = Date.now() - start
          const wait = Math.max(0, stage.offsetMs - elapsed)
          if (wait > 0) await new Promise((r) => setTimeout(r, wait))
          const actualMs = Date.now() - start
          const dataUrl = await screenshot({ format: 'png' })
          out.push({ label: stage.label, offsetMs: stage.offsetMs, actualMs, dataUrl })
        }
        return out
      },
      { stages },
    )
    return writeFastScreenshotFrames(namePrefix, frames)
  },

  async shake() {
    // no-op for sootsim
  },

  // native detox sets the simulator's location without changing app permissions.
  // target this page's device through the same location owner as peach location.
  async setLocation(lat: number, lon: number) {
    const page = getPage()
    const simId = await page.evaluate(() => window.SootSim?.state.simId)
    if (!simId) throw new Error('peach location requires a registered harness sim')
    const port = resolveSootsimBridgePortForHttpPort({
      explicitPort: process.env.PEACH_BRIDGE_PORT,
      httpPort: new URL(page.url()).port,
      baseHttpPort: 5173,
    })
    const bridge = createBridge(port, { simId, simIdSource: 'flag' })
    try {
      const result: unknown = await bridge.send({
        type: 'location',
        location: { action: 'set', latitude: lat, longitude: lon },
      })
      if (!result || typeof result !== 'object' || Reflect.get(result, 'ok') !== true)
        throw new Error(`peach location set failed: ${JSON.stringify(result)}`)
    } finally {
      bridge.close()
    }
  },

  async setStatusBar(config: StatusBarConfig) {
    await dispatchStatusBarOverride(config)
  },

  async setOrientation(orientation: string) {
    const next =
      orientation === 'portrait'
        ? 'portrait'
        : orientation === 'landscape'
          ? 'landscape'
          : null
    if (!next) {
      throw new Error(
        `sootsim device.setOrientation supports portrait and landscape; got ${orientation}`,
      )
    }
    await dispatchDeviceOrientation(next)
  },

  async setPosture(posture: string) {
    if (posture !== 'closed' && posture !== 'book' && posture !== 'open') {
      throw new Error(
        `sootsim device.setPosture supports closed, book and open; got ${posture}`,
      )
    }
    await dispatchDevicePosture(posture)
  },

  async setURLBlacklist(urls: string[]) {
    // no-op
  },

  async enableSynchronization() {
    _synchronizationEnabled = true
  },

  async disableSynchronization() {
    _synchronizationEnabled = false
  },

  getPlatform(): 'ios' | 'android' {
    return device._platform
  },

  async pressBack() {
    if (device._platform !== 'android') return
    const page = getPage()
    const dispatched = await page.evaluate(async () => {
      const goBack = window.SootSim?.bridges?.mainShell?.goBack
      if (typeof goBack !== 'function') return false
      return (await goBack()) !== false
    })
    if (!dispatched) throw new Error('sootsim Android back bridge is not installed')
    if (_synchronizationEnabled) {
      await waitForSootsimIdle(page)
    }
  },

  // a real browser key press. host.ts turns window keydown into the
  // `sootsim:hostKey` shell event that overlays listen to, so this drives the
  // same path a desktop user does for keys no device button covers (Escape).
  async pressKey(key: string) {
    const page = getPage()
    await page.keyboard.press(key)
    if (_synchronizationEnabled) {
      await waitForSootsimIdle(page)
    }
  },

  // raw coordinate tap, bypassing the element-based visibility/hit-test path.
  // mirrors detox 20.x device.tap({ x, y }) on real iOS — used when the
  // target is occluded by a native UIWindow (e.g. UIMenu's dim layer) so
  // `element(...).tap({x,y})` would fail Detox's visibility threshold.
  async tap(point?: { x: number; y: number } | boolean) {
    if (point == null || typeof point === 'boolean') return
    const page = getPage()
    const { x, y } = point
    const captureToken = (page as any).__sootsimCaptureToken
    await page.evaluate(
      async ({ x: tx, y: ty, token }) => {
        const interactTap = window.SootSim?.bridges?.interact?.tap
        if (typeof interactTap === 'function') {
          if (token) window.__sootsimAnchorTimedInput?.(token)
          const result = await interactTap(tx, ty)
          if (result && (typeof result !== 'object' || result.hit !== false)) {
            return
          }
        }
        const tap = window.__sootsimTest?.tap
        if (typeof tap !== 'function') {
          throw new Error('sootsim tap bridge is not installed')
        }
        if (token) window.__sootsimAnchorTimedInput?.(token)
        await tap(tx, ty)
      },
      { x, y, token: captureToken },
    )
    await page.waitForTimeout(50)
    if (_synchronizationEnabled) {
      await waitForSootsimIdle(page)
    }
  },

  // window-point counterpart to element(...).longPress, for a target detox can
  // only address by coordinate (a native tab cell, a shell chrome control).
  async longPress(point: { x: number; y: number }, durationMs = 1000) {
    const page = getPage()
    const { x, y } = point
    const captureToken = (page as any).__sootsimCaptureToken
    await page.evaluate(
      async ({ x: px, y: py, ms, token }) => {
        const longPress = window.SootSim?.bridges?.interact?.longPress
        if (typeof longPress !== 'function') {
          throw new Error('sootsim longPress bridge is not installed')
        }
        if (token) window.__sootsimAnchorTimedInput?.(token)
        const hit = await longPress(px, py, ms)
        if (!hit) {
          throw new Error(`sootsim longPress missed at ${px},${py}`)
        }
      },
      { x, y, ms: durationMs, token: captureToken },
    )
    await page.waitForTimeout(50)
    if (_synchronizationEnabled) {
      await waitForSootsimIdle(page)
    }
  },

  async sendToHome() {
    const page = getPage()
    await page.evaluate(async () => {
      const state = await window.SootSim?.bridges?.mainShell?.getState?.()
      if (typeof state?.activeApp !== 'string') {
        throw new Error(`cannot send an inactive SootSim app home`)
      }
      window.SootSim?.bridges?.mainShell?.goHome?.()
    })
    await pollUntil(
      () =>
        page.evaluate(async () => {
          const state = await window.SootSim?.bridges?.mainShell?.getState?.()
          return state?.state === 'home' && state.switcherPhase === 'idle'
        }),
      Boolean,
      {
        timeoutMs: 10000,
        label: 'SootSim home transition',
      },
    )
  },

  // get direct access to the playwright page for advanced use
  getPage(): Page {
    return getPage()
  },
}

// exports matching detox API
const sootsimExpect = createExpect(findNodeByMatcher, getPage)
const sootsimWaitFor = createWaitFor(findNodeByMatcher, getPage)

export { sootsimExpect as expect, sootsimWaitFor as waitFor }

// cleanup -- call this in afterAll
export async function cleanup() {
  _browserLaunchAbort?.abort(new Error('Peach driver cleaned up'))
  _nativePrepareAbort.abort(new Error('Peach driver cleaned up'))
  _nativePrepareAbort = new AbortController()
  await _browserLaunch?.catch(() => {})
  await closeBrowser(false)
}
