Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

- Core: skip `startRecording` with a warning on platforms that cannot record, instead of failing the flow or leaving a 0-byte file
- Core: don't let a failed screen recording start silently disable every later recording in the session
- iOS: record the external display on tvOS simulators, where screen recordings were never captured
- iOS: don't hang the run forever when a simulator screen recording refuses to stop
- iOS: report screen recording as unsupported on physical devices instead of crashing with `TODO()`
- Web: record the screen over CDP when attached to a running Chrome/Electron, where recording used to be a silent no-op

## 2.8.0

- Core: support element-relative `point` on `swipe` commands
Expand Down
1 change: 1 addition & 0 deletions gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ ktor-server-core = { module = "io.ktor:ktor-server-core", version.ref = "ktor" }
ktor-server-cors = { module = "io.ktor:ktor-server-cors", version.ref = "ktor" }
ktor-server-netty = { module = "io.ktor:ktor-server-netty", version.ref = "ktor" }
ktor-server-status-pages = { module = "io.ktor:ktor-server-status-pages", version.ref = "ktor" }
ktor-server-websockets = { module = "io.ktor:ktor-server-websockets", version.ref = "ktor" }
micrometer-core = { module = "io.micrometer:micrometer-core", version.ref = "micrometerCore" }
micrometer-observation = { module = "io.micrometer:micrometer-observation", version.ref = "micrometerObservation" }
mockk = { module = "io.mockk:mockk", version.ref = "mockk" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,13 @@ class RecordCommand : Callable<Int> {
val resultView = AnsiResultView()
val screenRecording = kotlin.io.path.createTempFile(suffix = ".mp4").toFile()
val exitCode = screenRecording.sink().use { out ->
runBlocking { maestro.startScreenRecording(out) }.use {
val recording = try {
runBlocking { maestro.startScreenRecording(out) }
} catch (e: UnsupportedOperationException) {
// recording is the entire point of this command, so don't degrade
throw CliError("\"maestro record\" needs a device that can record video: ${e.message}")
}
recording.use {
TestRunner.runSingle(
maestro,
device,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ object MaestroSessionManager {
throw UnsupportedOperationException("Unsupported device type $deviceType for iOS platform")
}
}
val isTvOS = deviceType == Device.DeviceType.SIMULATOR && LocalSimulatorUtils.isTV(deviceId)
val iOSDriverConfig = when (deviceType) {
Device.DeviceType.REAL -> {
val maestroDirectory = Paths.get(System.getProperty("user.home"), ".maestro")
Expand All @@ -403,7 +404,7 @@ object MaestroSessionManager {
)
}
Device.DeviceType.SIMULATOR -> {
val sourceDirectory = if (LocalSimulatorUtils.isTV(deviceId)) {
val sourceDirectory = if (isTvOS) {
"driver-appletvSimulator"
} else {
"driver-iPhoneSimulator"
Expand All @@ -428,7 +429,8 @@ object MaestroSessionManager {
Device.DeviceType.SIMULATOR -> {
val simctlIOSDevice = SimctlIOSDevice(
deviceId = deviceId,
tempFileHandler = tempFileHandler
tempFileHandler = tempFileHandler,
isTvOS = isTvOS,
)
simctlIOSDevice
}
Expand Down
6 changes: 3 additions & 3 deletions maestro-client/src/main/java/maestro/Maestro.kt
Original file line number Diff line number Diff line change
Expand Up @@ -693,10 +693,10 @@ class Maestro(
}
}
}
screenRecordingInProgress = true

LOGGER.info("Starting screen recording")
// only mark it in progress once the driver actually started, or a failure here would
// silently no-op every later recording in the session
val screenRecording = runInterruptible(Dispatchers.IO) { driver.startScreenRecording(out) }
screenRecordingInProgress = true
val startTimestamp = System.currentTimeMillis()
return object : ScreenRecording {
override fun close() {
Expand Down
33 changes: 30 additions & 3 deletions maestro-client/src/main/java/maestro/drivers/CdpWebDriver.kt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ class CdpWebDriver(
private var injectedArguments: Map<String, Any> = emptyMap()

private var webScreenRecorder: WebScreenRecorder? = null
private var cdpScreenRecording: ScreenRecording? = null

private val isAttachMode: Boolean get() = cdpUrl != null

Expand Down Expand Up @@ -262,13 +263,15 @@ class CdpWebDriver(
try {
seleniumDriver?.quit()
webScreenRecorder?.close()
cdpScreenRecording?.close()
} catch (e: Exception) {
// Swallow the exception to avoid crashing the whole process
}

seleniumDriver = null
lastSeenWindowHandles = setOf()
webScreenRecorder = null
cdpScreenRecording = null
}

override fun deviceInfo(): DeviceInfo {
Expand Down Expand Up @@ -733,10 +736,34 @@ class CdpWebDriver(

override fun startScreenRecording(out: Sink): ScreenRecording {
if (isAttachMode) {
// WebScreenRecorder is Selenium-backed; unavailable when attached over CDP.
return object : ScreenRecording {
override fun close() {}
// WebScreenRecorder is Selenium-backed, so attach mode drives the screencast
// over the raw CDP socket instead and feeds the frames to the same encoder.
val encoder = JcodecVideoEncoder()
encoder.start(out)

val screencast = try {
runBlocking { cdpClient.startScreencast(resolveTarget(), onFrame = encoder::encodeFrame) }
} catch (e: Exception) {
encoder.close()
throw e
}

val recording = object : ScreenRecording {
private var closed = false

override fun close() {
// Also reached via the driver's own close(); finishing the encoder twice throws.
if (closed) return
closed = true

// Order matters: the screencast join guarantees no frame is mid-encode.
screencast.close()
encoder.close()
}
}
cdpScreenRecording = recording

return recording
}

val driver = ensureOpen()
Expand Down
3 changes: 2 additions & 1 deletion maestro-client/src/main/java/maestro/drivers/RokuDriver.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package maestro.drivers

import maestro.utils.ScreenRecordingUnsupported
import maestro.Capability
import maestro.DeviceInfo
import maestro.Driver
Expand Down Expand Up @@ -264,7 +265,7 @@ class RokuDriver(
}

override fun startScreenRecording(out: Sink): ScreenRecording {
throw UnsupportedOperationException("Screen recording is not supported on Roku")
throw ScreenRecordingUnsupported("Roku")
}

override fun setLocation(latitude: Double, longitude: Double) {
Expand Down
3 changes: 2 additions & 1 deletion maestro-client/src/main/java/maestro/drivers/VegaDriver.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package maestro.drivers

import maestro.utils.ScreenRecordingUnsupported
import maestro.Capability
import maestro.DeviceInfo
import maestro.Driver
Expand Down Expand Up @@ -163,7 +164,7 @@ class VegaDriver(
}

override fun startScreenRecording(out: Sink): ScreenRecording {
throw UnsupportedOperationException("Screen recording is not supported on Vega")
throw ScreenRecordingUnsupported("Vega")
}

override fun setLocation(latitude: Double, longitude: Double) {
Expand Down
53 changes: 53 additions & 0 deletions maestro-client/src/test/java/maestro/MaestroScreenRecordingTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package maestro

import com.google.common.truth.Truth.assertThat
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import maestro.utils.ScreenRecordingUnsupported
import okio.Sink
import okio.blackholeSink
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

class MaestroScreenRecordingTest {

@Test
fun `a recorder that fails to start does not disable later recordings`() {
var closed = false
val recording = object : ScreenRecording {
override fun close() {
closed = true
}
}
val driver = mockk<Driver>(relaxed = true)
every { driver.startScreenRecording(any<Sink>()) } throws
ScreenRecordingUnsupported("Roku") andThen recording

val maestro = Maestro(driver)

assertThrows<ScreenRecordingUnsupported> {
runBlocking { maestro.startScreenRecording(blackholeSink()) }
}
// The failed attempt must not leave the session marked as "already recording",
// which would silently turn every later recording into a no-op.
runBlocking { maestro.startScreenRecording(blackholeSink()) }.close()
io.mockk.verify(exactly = 2) { driver.startScreenRecording(any<Sink>()) }
assertThat(closed).isTrue()
}

@Test
fun `a second recording while one is in progress is a no-op`() {
val driver = mockk<Driver>(relaxed = true)
every { driver.startScreenRecording(any<Sink>()) } returns object : ScreenRecording {
override fun close() = Unit
}

val maestro = Maestro(driver)
val first = runBlocking { maestro.startScreenRecording(blackholeSink()) }
val second = runBlocking { maestro.startScreenRecording(blackholeSink()) }

assertThat(first).isNotSameInstanceAs(second)
io.mockk.verify(exactly = 1) { driver.startScreenRecording(any<Sink>()) }
}
}
6 changes: 5 additions & 1 deletion maestro-ios-driver/src/main/kotlin/device/SimctlIOSDevice.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import java.nio.file.Files
class SimctlIOSDevice(
override val deviceId: String,
val tempFileHandler: TempFileHandler = TempFileHandler(),
isTvOS: Boolean? = null,
) : IOSDevice {

companion object {
Expand All @@ -31,6 +32,9 @@ class SimctlIOSDevice(

private var screenRecording: LocalSimulatorUtils.ScreenRecording? = null

// screen recording has to target the external display on tvOS; only look it up if the caller didn't know
private val isTvOS: Boolean by lazy { isTvOS ?: LocalSimulatorUtils.isTV(deviceId) }

override fun open() {
TODO("Not yet implemented")
}
Expand Down Expand Up @@ -116,7 +120,7 @@ class SimctlIOSDevice(
}

override fun startScreenRecording(out: Sink): IOSScreenRecording {
val screenRecording = localSimulatorUtils.startScreenRecording(deviceId)
val screenRecording = localSimulatorUtils.startScreenRecording(deviceId, isTvOS)
this.screenRecording = screenRecording

return object : IOSScreenRecording {
Expand Down
47 changes: 42 additions & 5 deletions maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ import java.io.InputStream
import java.lang.ProcessBuilder.Redirect.PIPE
import java.nio.file.Files
import java.nio.file.Path
import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.concurrent.TimeUnit
import kotlin.io.path.Path

class LocalSimulatorUtils(private val tempFileHandler: TempFileHandler) {
Expand All @@ -23,6 +25,9 @@ class LocalSimulatorUtils(private val tempFileHandler: TempFileHandler) {

companion object {
private const val LOG_DIR_DATE_FORMAT = "yyyy-MM-dd_HHmmss"

// Backstop for screenrecord.sh's own escalation; the SIGINT flush path is normally fast.
private val SCREEN_RECORDING_STOP_TIMEOUT: Duration = Duration.ofMinutes(2)
private val logger = LoggerFactory.getLogger(LocalSimulatorUtils::class.java)

fun isTV(deviceId: String): Boolean {
Expand Down Expand Up @@ -651,12 +656,17 @@ class LocalSimulatorUtils(private val tempFileHandler: TempFileHandler) {
)
}

/** Older simctl rejects display names and IDs, so use the "external"/"internal" aliases. */
internal fun displayEnvironment(isTvOS: Boolean): Map<String, String> =
if (isTvOS) mapOf("RECORDING_DISPLAY" to "external") else emptyMap()

data class ScreenRecording(
val process: Process,
val file: File,
)

fun startScreenRecording(deviceId: String): ScreenRecording {
/** [isTvOS] selects the display to record; tvOS simulators only expose the external one. */
fun startScreenRecording(deviceId: String, isTvOS: Boolean = isTV(deviceId)): ScreenRecording {
val tempDir = tempFileHandler.createTempDirectory()
val inputStream = LocalSimulatorUtils::class.java.getResourceAsStream("/screenrecord.sh")
if (inputStream != null) {
Expand All @@ -672,6 +682,7 @@ class LocalSimulatorUtils(private val tempFileHandler: TempFileHandler) {
val environment = processBuilder.environment()
environment["DEVICE_ID"] = deviceId
environment["RECORDING_PATH"] = recording.path
environment.putAll(displayEnvironment(isTvOS))

val recordingProcess = processBuilder
.redirectInput(PIPE)
Expand Down Expand Up @@ -736,11 +747,37 @@ class LocalSimulatorUtils(private val tempFileHandler: TempFileHandler) {
).redirectOutput(outputFile).redirectErrorStream(true).start()
}

fun stopScreenRecording(screenRecording: ScreenRecording): File {
screenRecording.process.outputStream.close()
screenRecording.process.waitFor()
/**
* Stops the recorder and returns the recording. Bounded by [timeout]: a recorder that never
* exits (simctl has been seen ignoring the stop signal on headless tvOS simulators) degrades
* the recording instead of hanging the whole run.
*/
fun stopScreenRecording(
screenRecording: ScreenRecording,
timeout: Duration = SCREEN_RECORDING_STOP_TIMEOUT,
): File {
runCatching { screenRecording.process.outputStream.close() }
.onFailure { logger.warn("Failed to signal the screen recorder to stop: ${it.message}") }

if (!screenRecording.process.waitFor(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
logger.warn("Screen recording did not stop within $timeout, force-terminating the recorder")
forceTerminate(screenRecording.process)
}

// make the media duration match the movie duration so browsers report the real length
Mp4DurationNormalizer.normalize(screenRecording.file)
if (screenRecording.file.length() > 0) {
Mp4DurationNormalizer.normalize(screenRecording.file)
}
return screenRecording.file
}

/** Kills the recorder and its descendants; killing only the script leaves xcrun/simctl orphaned. */
private fun forceTerminate(process: Process) {
val handle = process.toHandle()
// collect before destroying the parent, or the descendants are already reparented
val descendants = handle.descendants().toList()
(descendants + handle).forEach { runCatching { it.destroyForcibly() } }
descendants.forEach { runCatching { it.onExit().orTimeout(5, TimeUnit.SECONDS).join() } }
process.waitFor(5, TimeUnit.SECONDS)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ object Mp4DurationNormalizer {
fun normalize(recording: File) {
try {
RelocateMP4Editor().modifyOrRelocate(recording, HoldLastFrameToMovieDuration)
} catch (e: Exception) {
} catch (e: Throwable) { // a truncated recording makes jcodec throw errors too, never fail teardown
logger.warn("Skipping recording duration normalization for ${recording.name}: ${e.message}")
}
}
Expand Down
24 changes: 22 additions & 2 deletions maestro-ios-driver/src/main/resources/screenrecord.sh
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,14 @@
# Also not that the backend currently does not support hvec. That is why the
# codec is set to h264.

xcrun simctl io "$DEVICE_ID" recordVideo --force --codec h264 "$RECORDING_PATH" >"${RECORDING_PATH}.out" 2>"${RECORDING_PATH}.err" &
# tvOS only has an "external" display; simctl's default ("internal") records a display
# that does not exist there, producing no frames and a recorder that ignores SIGINT.
display_args=()
if [ -n "$RECORDING_DISPLAY" ]; then
display_args=(--display "$RECORDING_DISPLAY")
fi

xcrun simctl io "$DEVICE_ID" recordVideo --force --codec h264 "${display_args[@]}" "$RECORDING_PATH" >"${RECORDING_PATH}.out" 2>"${RECORDING_PATH}.err" &
simctlpid=$!

# Wait briefly for simctl to either fail fast or create the file
Expand All @@ -32,5 +39,18 @@ echo "RECORDING_STARTED"
# Wait for STDIN to close
cat

kill -SIGINT "$simctlpid"
kill -SIGINT "$simctlpid" 2>/dev/null

# simctl sometimes never exits on SIGINT (seen on headless tvOS simulators), which
# would block the caller forever. Give it time to flush the moov atom, then force it.
deadline=$((SECONDS + 60))
while kill -0 "$simctlpid" 2>/dev/null && [ "$SECONDS" -lt "$deadline" ]; do
sleep 1
done

if kill -0 "$simctlpid" 2>/dev/null; then
echo "RECORDING_STOP_TIMEOUT pid=$simctlpid"
kill -KILL "$simctlpid" 2>/dev/null
fi

wait $simctlpid
Loading
Loading