import XCTest
import AgentDeviceSnapshotPresentation

extension RunnerTests {
  private func refusedTapResponse(_ refusal: RunnerInteractionOutcome) -> Response {
    clearRememberedTextEntryTap()
    return refusalResponse(refusal)
  }


  @MainActor
  func executeOnMainPrepared(
    command: Command,
    activeApp: XCUIApplication,
    activeAppBundleId: String? = nil,
    alertDeadline: Date? = nil
  ) throws -> Response {
    do {
      return try executePrepared(
        command: command,
        activeApp: activeApp,
        activeAppBundleId: activeAppBundleId,
        alertDeadline: alertDeadline
      )
    } catch let refusal as RunnerAppScreenCaptureFailure {
      return refusal.response
    } catch let refusal as RunnerCoordinateRefusal {
      return unsupportedResponse(message: refusal.message, hint: refusal.hint)
    } catch let unknown as RunnerGestureOutcomeUnknown {
      return Response(
        ok: false,
        error: ErrorPayload(
          code: RunnerWireErrorCode.synthesizedGestureOutcomeUnknown,
          message: unknown.message,
          hint: unknown.hint
        )
      )
    }
  }

  @MainActor
  private func executePrepared(
    command: Command,
    activeApp: XCUIApplication,
    activeAppBundleId: String?,
    alertDeadline: Date?
  ) throws -> Response {
    var activeApp = activeApp
    mainOwned.soleDisplayPortraitSize = nil
    if command.invalidatesRememberedTextEntryTap {
      clearRememberedTextEntryTap()
    }
    if let refusal = prepareCommandSurface(command: command, app: activeApp) {
      return refusal.response
    }
    switch command.command {
    case .status, .activate, .terminate, .targetReset, .shutdown, .recordStart, .recordStop, .uptime,
      .appState, .pasteboardWrite, .snapshot, .snapshotBridge:
      return Response(
        ok: false,
        error: ErrorPayload(
          code: "UNSUPPORTED_OPERATION",
          message: "\(command.command.rawValue) cannot be executed through the prepared command path"
        )
      )
    case .tap:
      if let selectorKey = command.selectorKey, let selectorValue = command.selectorValue {
        let expectedPoint: CGPoint?
        if command.allowNonHittableCoordinateFallback == true,
          let x = command.x,
          let y = command.y
        {
          expectedPoint = CGPoint(x: x, y: y)
        } else {
          expectedPoint = nil
        }
        let match = try findElement(
          app: activeApp,
          selectorKey: selectorKey,
          selectorValue: selectorValue,
          allowNonHittableFallback: command.allowNonHittableCoordinateFallback == true,
          expectedPoint: expectedPoint
        )
        if match.isAmbiguous {
          clearRememberedTextEntryTap()
          return Response(ok: false, error: ErrorPayload(code: "AMBIGUOUS_MATCH", message: "selector matched multiple elements"))
        }
        if let element = match.element {
          let frame = element.frame









          if try !match.usedNonHittableFallback
            && !TapPointPolicy.isAllowed(
              elementFrame: frame,
              windowFrame: onScreenWindowFrame(app: activeApp)
            ) {
            clearRememberedTextEntryTap()
            return Response(ok: false, error: ErrorPayload(
              code: "ELEMENT_OFFSCREEN",
              message: "element resolved off-screen at (\(Int(frame.midX)), \(Int(frame.midY)))"))
          }
          let isTextEntry = isTextEntryElement(element)
          let touchPoint = expectedPoint ?? CGPoint(x: frame.midX, y: frame.midY)
          let touchFrame = try resolvedTouchVisualizationFrame(
            app: activeApp,
            x: touchPoint.x,
            y: touchPoint.y
          )
          var fallback: GestureFallback?
          if command.synthesized == true {
            switch try performSynthesizedTapGesture(app: activeApp, x: touchPoint.x, y: touchPoint.y) {
            case .performed(let timing):
              if isTextEntry {
                try waitForTextEntryReadinessAfterTap(app: activeApp, element: element)
              }
              rememberTextEntryTap(isTextEntry ? element : nil)
              return gestureResponse(
                message: match.usedNonHittableFallback
                  ? "tapped via non-hittable coordinate fallback"
                  : "tapped",
                timing: timing,
                frame: .touch(touchFrame),
                maestroNonHittableCoordinateFallbackUsed:
                  command.allowNonHittableCoordinateFallback == true
                  ? match.usedNonHittableFallback
                  : nil
              )
            case .xctestFallback(let message, let hint):
              fallback = .coordinateTap(message, hint: hint)
            case .refused(_, let refusal):
              return refusedTapResponse(refusal)
            }
          }
          let (timing, outcome) = try performGesture(activeApp) {
            if expectedPoint != nil || match.usedNonHittableFallback {




              return try tapAt(app: activeApp, x: touchPoint.x, y: touchPoint.y)
            }
            return try activateElement(app: activeApp, element: element, action: "tap by selector")
          }
          if let response = unsupportedResponse(for: outcome) {
            clearRememberedTextEntryTap()
            return response
          }
          if isTextEntry {
            try waitForTextEntryReadinessAfterTap(app: activeApp, element: element)
          }
          rememberTextEntryTap(isTextEntry ? element : nil)
          return gestureResponse(
            message: match.usedNonHittableFallback ? "tapped via non-hittable coordinate fallback" : "tapped",
            timing: timing,
            frame: .touch(touchFrame),
            fallback: fallback,
            maestroNonHittableCoordinateFallbackUsed:
              command.allowNonHittableCoordinateFallback == true
              ? match.usedNonHittableFallback
              : nil
          )
        }
        clearRememberedTextEntryTap()
        return Response(ok: false, error: ErrorPayload(code: "ELEMENT_NOT_FOUND", message: "element not found"))
      }
      if let x = command.x, let y = command.y {
        let xCTestChannelPenalized = isSnapshotXCTestChannelPenalized(
          bundleId: mainOwned.bundleId
        )
        let xCTestTextInputProbeSkipped = !shouldProbeCoordinateTapTextInput(
          xCTestChannelPenalized: xCTestChannelPenalized,
          evidence: command.coordinateTapTextInputEvidence,
          point: CGPoint(x: x, y: y),
          targetBundleId: activeAppBundleId
        )
        let textInput: XCUIElement?
        if !xCTestTextInputProbeSkipped {
          textInput = try coordinateTapTextInputAt(app: activeApp, x: x, y: y)
        } else {
          textInput = nil

          clearRememberedTextEntryTap()
          NSLog(
            "AGENT_DEVICE_RUNNER_COORDINATE_TAP_TEXT_INPUT_PROBE_SKIPPED bundle=%@ reason=%@",
            mainOwned.bundleId ?? "",
            xCTestChannelPenalized ? "penalized-xctest-channel" : "evidence"
          )
        }
        var fallback: GestureFallback?
        if command.synthesized == true {
          switch try performSynthesizedTapGesture(app: activeApp, x: x, y: y) {
          case .performed(let timing):
            rememberTextEntryTap(textInput)
            return gestureResponse(message: "tapped", timing: timing)
          case .xctestFallback(let message, let hint):
            fallback = .coordinateTap(message, hint: hint)
          case .refused(_, let refusal):
            return refusedTapResponse(refusal)
          }
        }
        let touchFrame = try resolvedTouchVisualizationFrame(app: activeApp, x: x, y: y)
        let (timing, outcome) = try performGesture(activeApp) { try tapAt(app: activeApp, x: x, y: y) }
        if let response = unsupportedResponse(for: outcome) {
          clearRememberedTextEntryTap()
          return response
        }
        rememberTextEntryTap(textInput)
        return gestureResponse(
          message: "tapped",
          timing: timing,
          frame: .touch(touchFrame),
          fallback: fallback
        )
      }
      clearRememberedTextEntryTap()
      return Response(ok: false, error: ErrorPayload(message: "tap requires a selector or x/y"))
    case .mouseClick:
      guard let x = command.x, let y = command.y else {
        return Response(ok: false, error: ErrorPayload(message: "mouseClick requires x and y"))
      }
      let touchFrame = try resolvedTouchVisualizationFrame(app: activeApp, x: x, y: y)
      do {


        var clickError: Error?
        let timing = measureGesture {
          do {
            try mouseClickAt(app: activeApp, x: x, y: y, button: command.button ?? "primary")
          } catch {
            clickError = error
          }
        }
        if let clickError {
          throw clickError
        }
        return gestureResponse(message: "clicked", timing: timing, frame: .touch(touchFrame))
      } catch {
        return Response(ok: false, error: ErrorPayload(message: error.localizedDescription))
      }
    case .longPress:
      guard let x = command.x, let y = command.y else {
        return Response(ok: false, error: ErrorPayload(message: "longPress requires x and y"))
      }
      let durationMs = command.durationMs ?? 800
      let fallback: GestureFallback?
#if os(iOS)
      let policyKind = SynthesizedGesturePolicyKind.coordinateLongPress
      let context = try synthesizedCoordinateContext(app: activeApp)
      switch try performSynthesizedGesture(activeApp, kind: policyKind, context: context, synthesize: {
        try synthesizedLongPressAt(app: activeApp, x: x, y: y, durationMs: durationMs, context: context)
      }) {
      case .performed(let timing):
        let touchFrame = context.map { touchVisualizationFrame(point: SurfacePoint(CGPoint(x: x, y: y)), context: $0) }
        return gestureResponse(message: "long pressed", timing: timing, frame: .touch(touchFrame))
      case .xctestFallback(let message, let hint):
        fallback = GestureFallback(strategy: "xctest-coordinate-long-press", message: message, hint: hint)
      case .refused(_, let refusal):
        return refusalResponse(refusal)
      }
#else
      fallback = nil
#endif
      let touchFrame = try resolvedTouchVisualizationFrame(app: activeApp, x: x, y: y)
      let (timing, outcome) = try performGesture(activeApp) {
        try longPressAt(app: activeApp, x: x, y: y, duration: durationMs / 1000.0)
      }
      if let response = unsupportedResponse(for: outcome) {
        return response
      }
      return gestureResponse(
        message: "long pressed",
        timing: timing,
        frame: .touch(touchFrame),
        fallback: fallback
      )
    case .drag:
      guard let x = command.x, let y = command.y, let x2 = command.x2, let y2 = command.y2 else {
        return Response(ok: false, error: ErrorPayload(message: "drag requires x, y, x2, and y2"))
      }
      let defaults = runnerDragCommandDefaults(command)
      return try executeDragGesture(
        activeApp: activeApp,
        x: x,
        y: y,
        x2: x2,
        y2: y2,
        durationMs: defaults.durationMs,
        message: "dragged"
      )
    case .scroll:



      guard let rawDirection = command.direction,
        let direction = RunnerScrollDirection(rawValue: rawDirection)
      else {
        return invalidScrollDirectionResponse(commandName: "scroll")
      }
#if os(watchOS)
      return try watchCrownScroll(app: activeApp, command: command, direction: direction)
#endif
      guard let scrollContext = try synthesizedCoordinateContext(app: activeApp) else {
        return Response(
          ok: false,
          error: ErrorPayload(message: "scroll could not resolve a usable interaction frame")
        )
      }
      let viewport = try resolvedScrollViewport(app: activeApp, context: scrollContext)
      let defaults = runnerDragCommandDefaults(command)
      switch viewport.gestureDispatch(
        direction: direction,
        amount: defaults.scrollAmount,
        pixels: command.pixels
      ) {
      case .occluded(let occlusionKeyboardMinY, let visibleHeight):
        return scrollKeyboardOccludedResponse(
          direction: direction.rawValue,
          keyboardMinY: occlusionKeyboardMinY,
          visibleHeight: visibleHeight
        )
      case .unusableFrame:
        return Response(
          ok: false,
          error: ErrorPayload(message: "scroll could not resolve a usable interaction frame")
        )
      case .unusablePlan:
        return Response(
          ok: false,
          error: ErrorPayload(
            code: "INVALID_ARGS",
            message: "scroll could not compute a gesture plan"
          )
        )
      case .gesture(let gesture):
        guard scrollDurationIsValid(command.durationMs) else {
          return invalidScrollDurationResponse(commandName: "scroll")
        }
        return gesture.attachingEvidence(
          to: try executeScrollDragGesture(
            activeApp: activeApp,
            x: gesture.planFrame.minX + gesture.plan.x1,
            y: gesture.planFrame.minY + gesture.plan.y1,
            x2: gesture.planFrame.minX + gesture.plan.x2,
            y2: gesture.planFrame.minY + gesture.plan.y2,
            durationMs: defaults.durationMs,
            message: "scrolled",
            context: scrollContext,
            releaseBehavior: command.scrollReleaseBehavior
          )
        )
      }
    case .desktopScroll:
      guard let rawDirection = command.direction,
        let direction = RunnerScrollDirection(rawValue: rawDirection)
      else {
        return invalidScrollDirectionResponse(commandName: "desktopScroll")
      }
      let appFrame = try readableAppFrame(app: activeApp)
      let frame = try resolvedTouchReferenceFrame(app: activeApp)
      guard frame.width > 0, frame.height > 0 else {
        return Response(
          ok: false,
          error: ErrorPayload(message: "desktopScroll could not resolve a usable interaction frame")
        )
      }
      guard let plan = runnerScrollGesturePlan(
        direction: direction,
        amount: command.amount,
        pixels: command.pixels,
        referenceWidth: frame.width,
        referenceHeight: frame.height
      ) else {
        return Response(
          ok: false,
          error: ErrorPayload(
            code: "INVALID_ARGS",
            message: "desktopScroll could not compute a wheel plan"
          )
        )
      }
      let x = frame.midX
      let y = frame.midY
      let localX = x - (appFrame.isEmpty ? frame.minX : appFrame.minX)
      let localY = y - (appFrame.isEmpty ? frame.minY : appFrame.minY)
      guard scrollDurationIsValid(command.durationMs) else {
        return invalidScrollDurationResponse(commandName: "desktopScroll")
      }
      let touchFrame = try resolvedTouchVisualizationFrame(
        app: activeApp,
        x: localX,
        y: localY
      )
      do {
        var scrollError: Error?
        let timing = measureGesture {
          do {
            try desktopScrollAt(
              app: activeApp,
              x: x,
              y: y,
              direction: direction,
              pixels: plan.travelPixels,
              durationMs: command.durationMs
            )
          } catch {
            scrollError = error
          }
        }
        if let scrollError {
          throw scrollError
        }
        return gestureResponse(message: "scrolled", timing: timing, frame: .touch(touchFrame))
      } catch {
        return Response(ok: false, error: ErrorPayload(message: error.localizedDescription))
      }
    case .remotePress:
      guard let button = tvRemoteButton(from: command.remoteButton) else {
        return Response(ok: false, error: ErrorPayload(message: "remotePress requires remoteButton"))
      }
      let duration = (command.durationMs ?? 0) / 1000.0
      guard pressTvRemote(button, duration: duration) else {
        return Response(
          ok: false,
          error: ErrorPayload(
            code: RunnerWireErrorCode.hardwareControlUnavailable,
            message: "remotePress is only supported on tvOS",
            hint: "Only a tvOS target has a Siri Remote. On a TV target use tv-remote; on a phone or Mac, press the app's own control by its ref."
          )
        )
      }
      return Response(ok: true, data: DataPayload(message: "remote pressed"))
    case .type:
      var outcome: Result<Response, Error>?
      withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) {
        outcome = Result { try executeTypeCommand(activeApp: activeApp, command: command) }
      }
      return try outcome?.get() ?? Response(ok: false, error: ErrorPayload(message: "type produced no response"))
    case .swipe:
      guard let direction = command.direction else {
        return Response(ok: false, error: ErrorPayload(message: "swipe requires direction"))
      }


      var executedFrame: Result<DragVisualizationFrame?, Error> = .success(nil)
      let timing = measureGesture {
        withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) {
          executedFrame = Result { try swipe(app: activeApp, direction: direction) }
        }
      }
      guard let dragFrame = try executedFrame.get() else {
        return Response(ok: false, error: ErrorPayload(message: "swipe is only supported on tvOS"))
      }
      return gestureResponse(message: "swiped", timing: timing, frame: .drag(dragFrame))
    case .findText:
      guard let text = command.text else {
        return Response(ok: false, error: ErrorPayload(message: "findText requires text"))
      }
      let found = try findElement(app: activeApp, text: text) != nil
      return Response(ok: true, data: DataPayload(found: found))
    case .querySelector:
      guard let selectorKey = command.selectorKey, let selectorValue = command.selectorValue else {
        return Response(ok: false, error: ErrorPayload(message: "querySelector requires selectorKey and selectorValue"))
      }
      if command.hittabilityProbe == true {
        return try probeElementHittability(app: activeApp, selectorKey: selectorKey, selectorValue: selectorValue)
      }
      return try queryElement(app: activeApp, selectorKey: selectorKey, selectorValue: selectorValue)
    case .readText:
      guard let x = command.x, let y = command.y else {
        return Response(ok: false, error: ErrorPayload(message: "readText requires x and y"))
      }
      guard let text = try readTextAt(app: activeApp, x: x, y: y) else {
        return Response(ok: false, error: ErrorPayload(message: "readText did not resolve text"))
      }
      return Response(ok: true, data: DataPayload(text: text))
    case .screenshot:
#if os(macOS)




      let screenshotBundleId = command.appBundleId?.trimmedNonEmpty
      if let bundleId = screenshotBundleId {
        let targetApp = XCUIApplication(bundleIdentifier: bundleId)
        if macAppCaptureNeedsRaise(
          fullscreen: command.fullscreen,
          targetState: targetApp.state
        ) {
          targetApp.activate()

          sleepFor(0.5)
        }
        activeApp = targetApp
      }
      let screenshot: XCUIScreenshot
      if command.fullscreen == true {
        screenshot = XCUIScreen.main.screenshot()
      } else if screenshotBundleId != nil {
        screenshot = screenshotRoot(app: activeApp).screenshot()
      } else {
        screenshot = XCUIScreen.main.screenshot()
      }
      return screenshotResponse(
        image: screenshot.image,
        inlineScreenshot: command.inlineScreenshot == true
      )
    #elseif os(iOS)









      switch captureObservedScreen(
        app: resolveAppWithoutActivation(command: command),
        litPanel: requestLitPanel
      ) {
      case .failure(let failure):
        return Response(
          ok: false,
          error: ErrorPayload(code: failure.rawValue, message: failure.message, hint: failure.hint)
        )
      case .success(let captured):


        NSLog(
          "AGENT_DEVICE_RUNNER_SCREEN_CAPTURE display=%lu pixels=%ldx%ld pixelsPerPoint=%g",
          captured.displayID,
          captured.pixelWidth,
          captured.pixelHeight,
          captured.pixelsPerPoint
        )
        return screenshotResponse(
          image: captured.image,
          inlineScreenshot: command.inlineScreenshot == true,
          metadata: ScreenshotMetadataPayload(
            displayID: captured.displayID,
            pixelWidth: captured.pixelWidth,
            pixelHeight: captured.pixelHeight,
            pixelsPerPoint: captured.pixelsPerPoint
          )
        )
      }
#else
      return screenshotResponse(
        image: XCUIScreen.main.screenshot().image,
        inlineScreenshot: command.inlineScreenshot == true
      )
#endif
    case .backInApp:
      switch try performInAppBack(app: activeApp) {
      case .performed:
        return Response(ok: true, data: DataPayload(message: "backInApp"))
      case .refused(let error), .unconfirmed(let error):
        return Response(ok: false, error: error)
      }
    case .home:
      pressHomeButton()
      return Response(ok: true, data: DataPayload(message: "home"))
    case .rotate:
      return executeRotateCommand(command)
    case .appSwitcher:
      try performAppSwitcherGesture(app: activeApp)
      return Response(ok: true, data: DataPayload(message: "appSwitcher"))
    case .actionButton:
      guard pressActionButton() else {
        return Response(
          ok: false,
          error: ErrorPayload(
            code: RunnerWireErrorCode.hardwareControlUnavailable,
            message: "actionButton requires a device model with an Action Button",
            hint: Self.actionButtonUnavailableHint
          )
        )
      }
      return Response(ok: true, data: DataPayload(message: "actionButton"))
    case .volumeUp, .volumeDown:
      guard pressVolumeButton(command.command) else {
        return Response(
          ok: false,
          error: ErrorPayload(
            code: RunnerWireErrorCode.hardwareControlUnavailable,
            message: "\(command.command) requires a physical iPhone or iPad; XCUIDevice exposes no volume press on a simulator",
            hint: "hardware-button volume-up/volume-down is supported on physical iOS devices through the runner or Appium; iOS Simulators have no pressable volume key."
          )
        )
      }
      return Response(ok: true, data: DataPayload(message: command.command.rawValue))
    case .keyboardDismiss, .keyboardStatus:
      var status: RunnerKeyboardStatus?
      withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .bothSkipped) {
        status = keyboardStatus(app: activeApp)
      }
      guard let status else {
        return Response(ok: false, error: ErrorPayload(
          code: "OBSERVATION_UNAVAILABLE",
          message: "Could not determine whether the software keyboard is visible",
          hint: "Take a screenshot or try keyboard status again."
        ))
      }
      if command.command == .keyboardDismiss {
        guard !status.visible else {
          return Response(ok: false, error: keyboardDismissRefusal(
            returnKey: status.returnKey.flatMap(RunnerKeyboardReturnKey.init(rawValue:))
          ))
        }
        return Response(ok: true, data: DataPayload(
          message: "keyboardDismiss", visible: false, wasVisible: false, dismissed: false
        ))
      }
      return Response(ok: true, data: DataPayload(
        message: "keyboardStatus",
        visible: status.visible,
        keyboardReturnKey: status.returnKey,
        keyboardReturnKeyLabel: status.returnKeyLabel
      ))
    case .keyboardReturn:
      var result: DataPayload?
      withBoundedInteractionIdleTimeoutIfSupported(activeApp, waits: .preEventSkipped) {
        let wasVisible = keyboardStatus(app: activeApp)?.visible
        guard pressKeyboardReturn(app: activeApp) else { return }
        sleepFor(0.2)
        result = DataPayload(
          message: "keyboardReturn",
          visible: keyboardStatus(app: activeApp)?.visible,
          wasVisible: wasVisible
        )
      }
      guard let result else {
        return Response(ok: false, error: keyboardReturnRefusal)
      }
      return Response(ok: true, data: result)
    case .alert:
      let action = (command.action ?? "get").lowercased()
      let deadline = alertDeadline ?? Date().addingTimeInterval(
        Self.alertCommandTimeout(timeoutMs: command.timeoutMs)
      )
      switch resolveAlert(app: activeApp, deadline: deadline) {
      case .resolved(let alert):
        return try handleAlert(alert, action: action, deadline: deadline)
      case .absent:


        return Response(
          ok: false,
          error: ErrorPayload(code: "ALERT_NOT_FOUND", message: "alert not found")
        )
      case .unresolved, .notActionable:
        return alertUnresolvedResponse()
      }
    case .gesture:
      guard let plan = command.gesturePlan else {
        return Response(
          ok: false,
          error: ErrorPayload(code: "INVALID_ARGS", message: "gesture requires gesturePlan")
        )
      }
      if let validationError = plannedGestureValidationError(plan) {
        return Response(
          ok: false,
          error: ErrorPayload(code: "INVALID_ARGS", message: validationError)
        )
      }
      let execution = plannedGestureExecution(for: plan)
      let response: Response
      switch execution {
      case .fastSwipe:

        let first = plan.pointers[0].samples.first!.point
        let last = plan.pointers[0].samples.last!.point
        response = canonicalPlannedGestureResponse(
          try executeDragGesture(
            activeApp: activeApp,
            x: first.x,
            y: first.y,
            x2: last.x,
            y2: last.y,
            durationMs: plan.durationMs,
            message: plan.intent,
            synthesized: (profile: .fastSwipe, policyKind: .synthesizedDrag)
          )
        )
      case .sampled:
        let (timing, outcome) = try performGesture(activeApp, idleTimeout: false) {
          try sampledPlannedGesture(app: activeApp, plan: plan)
        }
        response = plannedGestureResponse(plan: plan, timing: timing, outcome: outcome)
#if os(iOS) && targetEnvironment(simulator)
      case .screenEdgeTouch:
        let (timing, outcome) = try performGesture(activeApp, idleTimeout: false) {
          try screenEdgePlannedGesture(app: activeApp, plan: plan)
        }
        response = plannedGestureResponse(plan: plan, timing: timing, outcome: outcome)
#endif
      }
      return Self.reportingSchedule(execution.schedule, in: response)
    case .gestureViewport:
      let frame = try gestureViewportFrame(app: activeApp, includesKeyboard: command.includesKeyboard == true)
      guard !frame.isNull, !frame.isInfinite, !frame.isEmpty else {
        return Response(ok: false, error: ErrorPayload(code: "COMMAND_FAILED", message: "Active app interaction viewport is unavailable"))
      }
      return Response(ok: true, data: DataPayload(message: "gestureViewport", x: frame.minX, y: frame.minY, x2: frame.width, y2: frame.height))
    case .sequence:
      return try executeSequence(command: command, activeApp: activeApp)
    }
  }
}
