From 26baa4c3dae2e5c47c7ff8b8787c690170bba0e1 Mon Sep 17 00:00:00 2001 From: Douwe Bos Date: Thu, 3 Sep 2026 13:29:31 +0200 Subject: [PATCH 1/4] fix(ios): bound simulator screen recording teardown simctl can ignore the SIGINT that stops recordVideo (seen on headless tvOS simulators), and the unbounded waitFor in stopScreenRecording then hangs the whole suite. Wait with a timeout and force-kill the recorder plus its descendants on expiry, escalate to SIGKILL inside screenrecord.sh so the moov atom still gets a chance to flush, and never let normalization throw out of teardown. --- CHANGELOG.md | 2 + .../main/kotlin/util/LocalSimulatorUtils.kt | 39 +++++++++++-- .../main/kotlin/util/Mp4DurationNormalizer.kt | 2 +- .../src/main/resources/screenrecord.sh | 15 ++++- .../LocalSimulatorUtilsScreenRecordingTest.kt | 56 +++++++++++++++++++ 5 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 maestro-ios-driver/src/test/kotlin/util/LocalSimulatorUtilsScreenRecordingTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 60a18fcd46..fe54a45a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- iOS: don't hang the run forever when a simulator screen recording refuses to stop + ## 2.8.0 - Core: support element-relative `point` on `swipe` commands diff --git a/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt b/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt index c9aca7adbb..965fd417c8 100644 --- a/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt +++ b/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt @@ -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) { @@ -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 { @@ -736,11 +741,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) + } } diff --git a/maestro-ios-driver/src/main/kotlin/util/Mp4DurationNormalizer.kt b/maestro-ios-driver/src/main/kotlin/util/Mp4DurationNormalizer.kt index c8ae9414ac..8aa7955434 100644 --- a/maestro-ios-driver/src/main/kotlin/util/Mp4DurationNormalizer.kt +++ b/maestro-ios-driver/src/main/kotlin/util/Mp4DurationNormalizer.kt @@ -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}") } } diff --git a/maestro-ios-driver/src/main/resources/screenrecord.sh b/maestro-ios-driver/src/main/resources/screenrecord.sh index 33118c0925..e4ecf84a8f 100755 --- a/maestro-ios-driver/src/main/resources/screenrecord.sh +++ b/maestro-ios-driver/src/main/resources/screenrecord.sh @@ -32,5 +32,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 diff --git a/maestro-ios-driver/src/test/kotlin/util/LocalSimulatorUtilsScreenRecordingTest.kt b/maestro-ios-driver/src/test/kotlin/util/LocalSimulatorUtilsScreenRecordingTest.kt new file mode 100644 index 0000000000..e91c92222d --- /dev/null +++ b/maestro-ios-driver/src/test/kotlin/util/LocalSimulatorUtilsScreenRecordingTest.kt @@ -0,0 +1,56 @@ +package util + +import com.google.common.truth.Truth.assertThat +import maestro.utils.TempFileHandler +import org.junit.jupiter.api.Test +import java.io.File +import java.nio.file.Files +import java.time.Duration +import java.util.concurrent.TimeUnit + +class LocalSimulatorUtilsScreenRecordingTest { + + private val simulatorUtils = LocalSimulatorUtils(TempFileHandler()) + + /** A recorder that ignores the stop signal and holds a child process, like a stuck simctl. */ + private fun stuckRecorder(): Process = ProcessBuilder( + "bash", "-c", "trap '' INT TERM; sleep 300 & sleep 300", + ).redirectInput(ProcessBuilder.Redirect.PIPE).start() + + @Test + fun `force-terminates a recorder that ignores the stop signal instead of blocking`() { + val process = stuckRecorder() + val recording = LocalSimulatorUtils.ScreenRecording(process, Files.createTempFile("rec", ".mov").toFile()) + // wait for the child to exist, so the descendant kill is actually exercised + val children = waitForDescendants(process) + assertThat(children).isNotEmpty() + + val file = simulatorUtils.stopScreenRecording(recording, timeout = Duration.ofSeconds(1)) + + assertThat(file).isEqualTo(recording.file) + assertThat(process.isAlive).isFalse() + assertThat(children.filter { it.isAlive }).isEmpty() + recording.file.delete() + } + + @Test + fun `returns the recording normally when the recorder stops on its own`() { + val process = ProcessBuilder("bash", "-c", "cat").redirectInput(ProcessBuilder.Redirect.PIPE).start() + val recording = LocalSimulatorUtils.ScreenRecording(process, File("does-not-exist.mov")) + + simulatorUtils.stopScreenRecording(recording, timeout = Duration.ofSeconds(30)) + + assertThat(process.isAlive).isFalse() + assertThat(process.exitValue()).isEqualTo(0) + } + + private fun waitForDescendants(process: Process): List { + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10) + while (System.nanoTime() < deadline) { + val descendants = process.toHandle().descendants().toList() + if (descendants.isNotEmpty()) return descendants + Thread.sleep(50) + } + return emptyList() + } +} From d79a498e072dedf2cf792e5f96bc485c1250059d Mon Sep 17 00:00:00 2001 From: Douwe Bos Date: Thu, 3 Sep 2026 13:58:15 +0200 Subject: [PATCH 2/4] fix(ios): record the external display on tvOS simulators simctl io recordVideo defaults to --display internal, which tvOS does not have, so it never processed a frame, wrote no file, and ignored the SIGINT that stops it - which is what wedged the recorder teardown. Pass --display external for tvOS simulators, plumbing the platform down from the session manager, which already knows it. --- CHANGELOG.md | 1 + .../cli/session/MaestroSessionManager.kt | 6 +- .../src/main/kotlin/device/SimctlIOSDevice.kt | 6 +- .../main/kotlin/util/LocalSimulatorUtils.kt | 8 ++- .../src/main/resources/screenrecord.sh | 9 ++- .../kotlin/util/ScreenRecordCommandTest.kt | 57 +++++++++++++++++++ 6 files changed, 82 insertions(+), 5 deletions(-) create mode 100644 maestro-ios-driver/src/test/kotlin/util/ScreenRecordCommandTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index fe54a45a97..d1763f4afd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- 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 ## 2.8.0 diff --git a/maestro-cli/src/main/java/maestro/cli/session/MaestroSessionManager.kt b/maestro-cli/src/main/java/maestro/cli/session/MaestroSessionManager.kt index b36bf47b3d..739c623eac 100644 --- a/maestro-cli/src/main/java/maestro/cli/session/MaestroSessionManager.kt +++ b/maestro-cli/src/main/java/maestro/cli/session/MaestroSessionManager.kt @@ -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") @@ -403,7 +404,7 @@ object MaestroSessionManager { ) } Device.DeviceType.SIMULATOR -> { - val sourceDirectory = if (LocalSimulatorUtils.isTV(deviceId)) { + val sourceDirectory = if (isTvOS) { "driver-appletvSimulator" } else { "driver-iPhoneSimulator" @@ -428,7 +429,8 @@ object MaestroSessionManager { Device.DeviceType.SIMULATOR -> { val simctlIOSDevice = SimctlIOSDevice( deviceId = deviceId, - tempFileHandler = tempFileHandler + tempFileHandler = tempFileHandler, + isTvOS = isTvOS, ) simctlIOSDevice } diff --git a/maestro-ios-driver/src/main/kotlin/device/SimctlIOSDevice.kt b/maestro-ios-driver/src/main/kotlin/device/SimctlIOSDevice.kt index 30bb388448..79abebecf7 100644 --- a/maestro-ios-driver/src/main/kotlin/device/SimctlIOSDevice.kt +++ b/maestro-ios-driver/src/main/kotlin/device/SimctlIOSDevice.kt @@ -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 { @@ -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") } @@ -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 { diff --git a/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt b/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt index 965fd417c8..3a4df71683 100644 --- a/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt +++ b/maestro-ios-driver/src/main/kotlin/util/LocalSimulatorUtils.kt @@ -656,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 = + 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) { @@ -677,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) diff --git a/maestro-ios-driver/src/main/resources/screenrecord.sh b/maestro-ios-driver/src/main/resources/screenrecord.sh index e4ecf84a8f..7d6a7ec8ef 100755 --- a/maestro-ios-driver/src/main/resources/screenrecord.sh +++ b/maestro-ios-driver/src/main/resources/screenrecord.sh @@ -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 diff --git a/maestro-ios-driver/src/test/kotlin/util/ScreenRecordCommandTest.kt b/maestro-ios-driver/src/test/kotlin/util/ScreenRecordCommandTest.kt new file mode 100644 index 0000000000..5db4f8dd98 --- /dev/null +++ b/maestro-ios-driver/src/test/kotlin/util/ScreenRecordCommandTest.kt @@ -0,0 +1,57 @@ +package util + +import com.google.common.truth.Truth.assertThat +import maestro.utils.TempFileHandler +import org.junit.jupiter.api.Test +import java.io.File +import java.nio.file.Files + +/** Covers which display `simctl io recordVideo` is pointed at: tvOS only has an external one. */ +class ScreenRecordCommandTest { + + private val simulatorUtils = LocalSimulatorUtils(TempFileHandler()) + + @Test + fun `tvOS records the external display`() { + assertThat(simulatorUtils.displayEnvironment(isTvOS = true)) + .containsExactly("RECORDING_DISPLAY", "external") + assertThat(recordVideoArgs(isTvOS = true)).contains("--display external") + } + + @Test + fun `iOS keeps simctl's default display`() { + assertThat(simulatorUtils.displayEnvironment(isTvOS = false)).isEmpty() + assertThat(recordVideoArgs(isTvOS = false)).doesNotContain("--display") + } + + /** Runs the real screenrecord.sh against a stub xcrun and returns the command line it saw. */ + private fun recordVideoArgs(isTvOS: Boolean): String { + val script = LocalSimulatorUtils::class.java.getResourceAsStream("/screenrecord.sh")!! + .bufferedReader().readText() + val dir = Files.createTempDirectory("screenrecord").toFile() + val argsFile = File(dir, "args.txt") + File(dir, "xcrun").apply { + writeText("#!/bin/bash\necho \"\$@\" > '${argsFile.path}'\nexec sleep 60\n") + setExecutable(true) + } + + val builder = ProcessBuilder("bash", "-c", script).redirectInput(ProcessBuilder.Redirect.PIPE) + builder.environment().apply { + put("PATH", "${dir.path}:${get("PATH")}") + put("DEVICE_ID", "device-id") + put("RECORDING_PATH", File(dir, "recording.mov").path) + putAll(simulatorUtils.displayEnvironment(isTvOS)) + } + val process = builder.redirectErrorStream(true).start() + try { + assertThat(process.inputStream.bufferedReader().readLine()).isEqualTo("RECORDING_STARTED") + return argsFile.readText().trim() + } finally { + simulatorUtils.stopScreenRecording( + LocalSimulatorUtils.ScreenRecording(process, File(dir, "recording.mov")), + timeout = java.time.Duration.ofSeconds(10), + ) + dir.deleteRecursively() + } + } +} From be908632b09796814fc3cece784549dc7fc53220 Mon Sep 17 00:00:00 2001 From: Douwe Bos Date: Thu, 3 Sep 2026 14:15:02 +0200 Subject: [PATCH 3/4] feat(web): record the screen over CDP in attach mode WebScreenRecorder is Selenium-backed, so attaching to a running Chrome/Electron left startScreenRecording a silent no-op that produced an empty file. Drive Page.startScreencast over the raw CDP socket instead and feed the frames to the same encoder, acking each frame so Chrome's delivery gates on the consumer. --- gradle/libs.versions.toml | 1 + .../main/java/maestro/drivers/CdpWebDriver.kt | 33 ++++++- maestro-web/build.gradle.kts | 2 + .../main/kotlin/maestro/web/cdp/CdpClient.kt | 74 +++++++++++++++ .../src/test/kotlin/CdpScreencastTest.kt | 92 +++++++++++++++++++ 5 files changed, 199 insertions(+), 3 deletions(-) create mode 100644 maestro-web/src/test/kotlin/CdpScreencastTest.kt diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index cc2454af85..0dc7ac12bb 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -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" } diff --git a/maestro-client/src/main/java/maestro/drivers/CdpWebDriver.kt b/maestro-client/src/main/java/maestro/drivers/CdpWebDriver.kt index dea9cdf64b..717ce63808 100644 --- a/maestro-client/src/main/java/maestro/drivers/CdpWebDriver.kt +++ b/maestro-client/src/main/java/maestro/drivers/CdpWebDriver.kt @@ -70,6 +70,7 @@ class CdpWebDriver( private var injectedArguments: Map = emptyMap() private var webScreenRecorder: WebScreenRecorder? = null + private var cdpScreenRecording: ScreenRecording? = null private val isAttachMode: Boolean get() = cdpUrl != null @@ -262,6 +263,7 @@ class CdpWebDriver( try { seleniumDriver?.quit() webScreenRecorder?.close() + cdpScreenRecording?.close() } catch (e: Exception) { // Swallow the exception to avoid crashing the whole process } @@ -269,6 +271,7 @@ class CdpWebDriver( seleniumDriver = null lastSeenWindowHandles = setOf() webScreenRecorder = null + cdpScreenRecording = null } override fun deviceInfo(): DeviceInfo { @@ -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() diff --git a/maestro-web/build.gradle.kts b/maestro-web/build.gradle.kts index 54ebb81925..61df585421 100644 --- a/maestro-web/build.gradle.kts +++ b/maestro-web/build.gradle.kts @@ -22,6 +22,8 @@ dependencies { implementation(libs.ktor.client.content.negotiation) testImplementation(libs.junit.jupiter.api) + testImplementation(libs.ktor.server.cio) + testImplementation(libs.ktor.server.websockets) testImplementation(libs.google.truth) testRuntimeOnly(libs.junit.jupiter.engine) } diff --git a/maestro-web/src/main/kotlin/maestro/web/cdp/CdpClient.kt b/maestro-web/src/main/kotlin/maestro/web/cdp/CdpClient.kt index 4a104232d2..66ba96d3cc 100644 --- a/maestro-web/src/main/kotlin/maestro/web/cdp/CdpClient.kt +++ b/maestro-web/src/main/kotlin/maestro/web/cdp/CdpClient.kt @@ -6,6 +6,14 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.serialization.kotlinx.json.* import io.ktor.websocket.* +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.serialization.Serializable @@ -285,6 +293,72 @@ class CdpClient( sendCommand("Input.dispatchMouseEvent", params, target) } + /** + * Streams screencast frames (JPEG bytes) from [target] to [onFrame] until the returned + * handle is closed. + * + * Runs on its own WebSocket: frames arrive as unsolicited events, which the + * request/response [sendCommand] path cannot consume. [onFrame] runs before each frame is + * acked, so Chrome's ack-gated delivery doubles as backpressure on the consumer. + */ + suspend fun startScreencast( + target: CdpTarget, + maxWidth: Int = 1280, + maxHeight: Int = 1280, + onFrame: (ByteArray) -> Unit, + ): AutoCloseable { + val wsUrl = target.webSocketDebuggerUrl ?: error("Target ${target.id} has no WebSocket debugger URL") + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val started = CompletableDeferred() + + val job = scope.launch { + httpClient.webSocketSession { url(wsUrl) }.use { session -> + session.send(Frame.Text("""{"id":${idCounter.getAndIncrement()},"method":"Page.enable"}""")) + session.send( + Frame.Text( + """{"id":${idCounter.getAndIncrement()},"method":"Page.startScreencast",""" + + """"params":{"format":"jpeg","quality":80,"maxWidth":$maxWidth,""" + + """"maxHeight":$maxHeight,"everyNthFrame":1}}""" + ) + ) + started.complete(Unit) + + for (frame in session.incoming) { + if (frame !is Frame.Text) continue + + val root = json.parseToJsonElement(frame.readText()).jsonObject + if (root["method"]?.jsonPrimitive?.content != "Page.screencastFrame") continue + + val params = root["params"]?.jsonObject ?: continue + val data = params["data"]?.jsonPrimitive?.content ?: continue + val sessionId = params["sessionId"]?.jsonPrimitive?.content ?: continue + + onFrame(Base64.getDecoder().decode(data)) + + session.send( + Frame.Text( + """{"id":${idCounter.getAndIncrement()},"method":"Page.screencastFrameAck",""" + + """"params":{"sessionId":$sessionId}}""" + ) + ) + } + } + } + + // Surface a connect/start failure to the caller instead of hanging on `started`. + job.invokeOnCompletion { cause -> + if (cause != null) started.completeExceptionally(cause) else started.complete(Unit) + } + started.await() + + return AutoCloseable { + // Join before returning: the caller closes its encoder next, and that must not + // race a frame still inside onFrame. Dropping the socket ends the screencast. + runBlocking { job.cancelAndJoin() } + scope.cancel() + } + } + private suspend fun sendCommand(method: String, params: JsonObject, target: CdpTarget): String { val messageId = idCounter.getAndIncrement() val paramsJson = Json.encodeToString(JsonObject.serializer(), params) diff --git a/maestro-web/src/test/kotlin/CdpScreencastTest.kt b/maestro-web/src/test/kotlin/CdpScreencastTest.kt new file mode 100644 index 0000000000..016c5ef38c --- /dev/null +++ b/maestro-web/src/test/kotlin/CdpScreencastTest.kt @@ -0,0 +1,92 @@ +import com.google.common.truth.Truth.assertThat +import io.ktor.server.application.install +import io.ktor.server.cio.CIO +import io.ktor.server.engine.embeddedServer +import io.ktor.server.routing.routing +import io.ktor.server.websocket.DefaultWebSocketServerSession +import io.ktor.server.websocket.WebSockets +import io.ktor.server.websocket.webSocket +import io.ktor.websocket.Frame +import io.ktor.websocket.readText +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Test +import java.net.ServerSocket +import java.util.Base64 +import java.util.concurrent.ConcurrentLinkedQueue +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit + +/** Drives startScreencast against a stand-in DevTools socket; Chrome is not involved. */ +class CdpScreencastTest { + + private val frameData = byteArrayOf(1, 2, 3) + + @Test + fun `streams frames to the consumer and acks each one`() { + val serverMessages = ConcurrentLinkedQueue() + val bothAcked = CountDownLatch(2) + val port = freePort() + + val server = embeddedServer(CIO, port = port) { + install(WebSockets) + routing { + webSocket("/devtools/page/A") { + for (frame in incoming) { + val text = (frame as? Frame.Text)?.readText() ?: continue + serverMessages += text + if (text.contains("Page.startScreencast")) { + repeat(2) { sendScreencastFrame(sessionId = it) } + } + if (text.contains("Page.screencastFrameAck")) bothAcked.countDown() + } + } + } + }.start(wait = false) + + val received = ConcurrentLinkedQueue() + val target = CdpTarget( + id = "A", + title = "", + url = "", + webSocketDebuggerUrl = "ws://127.0.0.1:$port/devtools/page/A", + ) + + val screencast = runBlocking { CdpClient().startScreencast(target, onFrame = { received += it }) } + try { + assertThat(bothAcked.await(10, TimeUnit.SECONDS)).isTrue() + } finally { + screencast.close() + server.stop(0, 0) + } + + assertThat(received.map { it.toList() }).containsExactly(frameData.toList(), frameData.toList()) + // Page.enable precedes the screencast start, and every delivered frame is acked. + assertThat(serverMessages.first()).contains("Page.enable") + assertThat(serverMessages.count { it.contains("Page.screencastFrameAck") }).isEqualTo(2) + } + + @Test + fun `surfaces a connection failure instead of hanging`() { + val target = CdpTarget( + id = "A", + title = "", + url = "", + webSocketDebuggerUrl = "ws://127.0.0.1:${freePort()}/devtools/page/A", + ) + + val result = runCatching { runBlocking { CdpClient().startScreencast(target) {} } } + + assertThat(result.isFailure).isTrue() + } + + private suspend fun DefaultWebSocketServerSession.sendScreencastFrame(sessionId: Int) { + val data = Base64.getEncoder().encodeToString(frameData) + send( + Frame.Text( + """{"method":"Page.screencastFrame","params":{"data":"$data","sessionId":"$sessionId"}}""" + ) + ) + } + + private fun freePort(): Int = ServerSocket(0).use { it.localPort } +} From 93acbcdb70f4d12662b4f1d150952aca8b2a9148 Mon Sep 17 00:00:00 2001 From: Douwe Bos Date: Thu, 3 Sep 2026 14:15:09 +0200 Subject: [PATCH 4/4] fix: handle unsupported screen recording uniformly Drivers signalled 'cannot record' three different ways - TODO(), error() and a silent no-op - so the same situation crashed, failed a flow or produced an empty file depending on the platform. Report it as ScreenRecordingUnsupported and let each caller decide: flows and debug artifacts skip the recording with a warning and no 0-byte file, while 'maestro record' fails with a clear message. Also stop marking a session as recording before the driver actually started, which left every later recording a silent no-op. --- CHANGELOG.md | 4 ++ .../java/maestro/cli/command/RecordCommand.kt | 8 ++- .../src/main/java/maestro/Maestro.kt | 6 +-- .../main/java/maestro/drivers/RokuDriver.kt | 3 +- .../main/java/maestro/drivers/VegaDriver.kt | 3 +- .../maestro/MaestroScreenRecordingTest.kt | 53 +++++++++++++++++++ .../ios/devicectl/DeviceControlIOSDevice.kt | 4 +- .../main/java/ios/xctest/XCTestIOSDevice.kt | 3 +- .../main/java/maestro/orchestra/Orchestra.kt | 12 ++++- .../orchestra/debug/ArtifactsGenerator.kt | 2 + .../kotlin/maestro/test/drivers/FakeDriver.kt | 5 ++ .../kotlin/maestro/test/IntegrationTest.kt | 23 ++++++++ .../main/kotlin/ScreenRecordingUnsupported.kt | 9 ++++ 13 files changed, 126 insertions(+), 9 deletions(-) create mode 100644 maestro-client/src/test/java/maestro/MaestroScreenRecordingTest.kt create mode 100644 maestro-utils/src/main/kotlin/ScreenRecordingUnsupported.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index d1763f4afd..309b8f3ef4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,12 @@ ## 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 diff --git a/maestro-cli/src/main/java/maestro/cli/command/RecordCommand.kt b/maestro-cli/src/main/java/maestro/cli/command/RecordCommand.kt index 55cf0ea459..6d55a8d88d 100644 --- a/maestro-cli/src/main/java/maestro/cli/command/RecordCommand.kt +++ b/maestro-cli/src/main/java/maestro/cli/command/RecordCommand.kt @@ -150,7 +150,13 @@ class RecordCommand : Callable { 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, diff --git a/maestro-client/src/main/java/maestro/Maestro.kt b/maestro-client/src/main/java/maestro/Maestro.kt index 6efbb2f3c0..e0020f6edc 100644 --- a/maestro-client/src/main/java/maestro/Maestro.kt +++ b/maestro-client/src/main/java/maestro/Maestro.kt @@ -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() { diff --git a/maestro-client/src/main/java/maestro/drivers/RokuDriver.kt b/maestro-client/src/main/java/maestro/drivers/RokuDriver.kt index c55229eee9..3b7b333ced 100644 --- a/maestro-client/src/main/java/maestro/drivers/RokuDriver.kt +++ b/maestro-client/src/main/java/maestro/drivers/RokuDriver.kt @@ -1,5 +1,6 @@ package maestro.drivers +import maestro.utils.ScreenRecordingUnsupported import maestro.Capability import maestro.DeviceInfo import maestro.Driver @@ -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) { diff --git a/maestro-client/src/main/java/maestro/drivers/VegaDriver.kt b/maestro-client/src/main/java/maestro/drivers/VegaDriver.kt index 92437667a8..e1cc049082 100644 --- a/maestro-client/src/main/java/maestro/drivers/VegaDriver.kt +++ b/maestro-client/src/main/java/maestro/drivers/VegaDriver.kt @@ -1,5 +1,6 @@ package maestro.drivers +import maestro.utils.ScreenRecordingUnsupported import maestro.Capability import maestro.DeviceInfo import maestro.Driver @@ -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) { diff --git a/maestro-client/src/test/java/maestro/MaestroScreenRecordingTest.kt b/maestro-client/src/test/java/maestro/MaestroScreenRecordingTest.kt new file mode 100644 index 0000000000..2725e3bf2e --- /dev/null +++ b/maestro-client/src/test/java/maestro/MaestroScreenRecordingTest.kt @@ -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(relaxed = true) + every { driver.startScreenRecording(any()) } throws + ScreenRecordingUnsupported("Roku") andThen recording + + val maestro = Maestro(driver) + + assertThrows { + 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()) } + assertThat(closed).isTrue() + } + + @Test + fun `a second recording while one is in progress is a no-op`() { + val driver = mockk(relaxed = true) + every { driver.startScreenRecording(any()) } 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()) } + } +} diff --git a/maestro-ios/src/main/java/ios/devicectl/DeviceControlIOSDevice.kt b/maestro-ios/src/main/java/ios/devicectl/DeviceControlIOSDevice.kt index 588942e029..dc97743601 100644 --- a/maestro-ios/src/main/java/ios/devicectl/DeviceControlIOSDevice.kt +++ b/maestro-ios/src/main/java/ios/devicectl/DeviceControlIOSDevice.kt @@ -1,5 +1,6 @@ package ios.devicectl +import maestro.utils.ScreenRecordingUnsupported import com.github.michaelbull.result.Result import device.IOSDevice import device.IOSScreenRecording @@ -84,7 +85,8 @@ class DeviceControlIOSDevice(override val deviceId: String) : IOSDevice { } override fun startScreenRecording(out: Sink): IOSScreenRecording { - TODO("Not yet implemented") + // devicectl exposes no capture API; only the simulator (simctl) can record. + throw ScreenRecordingUnsupported("physical iOS devices, only on simulators") } override fun setLocation(latitude: Double, longitude: Double): Result { diff --git a/maestro-ios/src/main/java/ios/xctest/XCTestIOSDevice.kt b/maestro-ios/src/main/java/ios/xctest/XCTestIOSDevice.kt index bf5759530c..0cf892e59e 100644 --- a/maestro-ios/src/main/java/ios/xctest/XCTestIOSDevice.kt +++ b/maestro-ios/src/main/java/ios/xctest/XCTestIOSDevice.kt @@ -1,5 +1,6 @@ package ios.xctest +import maestro.utils.ScreenRecordingUnsupported import com.github.michaelbull.result.Result import device.IOSDevice import hierarchy.ViewHierarchy @@ -170,7 +171,7 @@ class XCTestIOSDevice( } override fun startScreenRecording(out: Sink): IOSScreenRecording { - error("Not supported") + throw ScreenRecordingUnsupported("iOS devices driven over XCTest") } override fun setLocation(latitude: Double, longitude: Double): Result { diff --git a/maestro-orchestra/src/main/java/maestro/orchestra/Orchestra.kt b/maestro-orchestra/src/main/java/maestro/orchestra/Orchestra.kt index 015892c0a4..dc70944f61 100644 --- a/maestro-orchestra/src/main/java/maestro/orchestra/Orchestra.kt +++ b/maestro-orchestra/src/main/java/maestro/orchestra/Orchestra.kt @@ -1251,7 +1251,17 @@ class Orchestra( val outFile = artifactsGenerator .allocateCommandArtifact(ArtifactKind.START_SCREEN_RECORDING, "${command.path}.mp4", "startRecording") ?: File("${command.path}.mp4") - screenRecording = maestro.startScreenRecording(artifactSink(outFile, command.path, "startRecording")) + val sink = artifactSink(outFile, command.path, "startRecording") + screenRecording = try { + maestro.startScreenRecording(sink) + } catch (e: UnsupportedOperationException) { + // recording is incidental to the flow, so skip it rather than failing the run + logger.warn("Skipping startRecording: ${e.message}") + insights.report(Insight("Skipping startRecording: ${e.message}", Insight.Level.WARNING)) + sink.close() + outFile.delete() + null + } return false } diff --git a/maestro-orchestra/src/main/kotlin/maestro/orchestra/debug/ArtifactsGenerator.kt b/maestro-orchestra/src/main/kotlin/maestro/orchestra/debug/ArtifactsGenerator.kt index 33ba29dbf1..fdb5e8b5c9 100644 --- a/maestro-orchestra/src/main/kotlin/maestro/orchestra/debug/ArtifactsGenerator.kt +++ b/maestro-orchestra/src/main/kotlin/maestro/orchestra/debug/ArtifactsGenerator.kt @@ -303,6 +303,8 @@ internal class ArtifactsGenerator( val destFile = collector.allocate(ArtifactKind.SCREEN_RECORDING, ArtifactFormat.MP4, BundleLayout.SCREEN_RECORDING) fullRunRecordingFile = destFile fullRunRecording = runBlocking { maestro.startScreenRecording(destFile.sink()) } + } catch (e: UnsupportedOperationException) { + logger.info("Skipping full-run screen recording: ${e.message}") } catch (e: Exception) { logger.warn("Failed to start full-run screen recording", e) } diff --git a/maestro-test/src/main/kotlin/maestro/test/drivers/FakeDriver.kt b/maestro-test/src/main/kotlin/maestro/test/drivers/FakeDriver.kt index 7470dfd636..a6096e385e 100644 --- a/maestro-test/src/main/kotlin/maestro/test/drivers/FakeDriver.kt +++ b/maestro-test/src/main/kotlin/maestro/test/drivers/FakeDriver.kt @@ -66,6 +66,9 @@ open class FakeDriver : Driver { // Test seam: when set, launchApp() throws this — used to simulate a device death during setup. var launchError: Throwable? = null + // Test seam: when set, startScreenRecording() throws this — used to simulate a platform that cannot record. + var screenRecordingError: Throwable? = null + override fun name(): String { return "Fake Device" } @@ -270,6 +273,8 @@ open class FakeDriver : Driver { override fun startScreenRecording(out: Sink): ScreenRecording { ensureOpen() + screenRecordingError?.let { throw it } + out.buffer().writeUtf8("Screen recording").close() events += Event.StartRecording diff --git a/maestro-test/src/test/kotlin/maestro/test/IntegrationTest.kt b/maestro-test/src/test/kotlin/maestro/test/IntegrationTest.kt index c77ddedda2..506454728a 100644 --- a/maestro-test/src/test/kotlin/maestro/test/IntegrationTest.kt +++ b/maestro-test/src/test/kotlin/maestro/test/IntegrationTest.kt @@ -22,6 +22,7 @@ import maestro.Maestro import maestro.MaestroException import maestro.Point import maestro.SwipeDirection +import maestro.utils.ScreenRecordingUnsupported import maestro.orchestra.ApplyConfigurationCommand import maestro.orchestra.AssertConditionCommand import maestro.orchestra.AssertDarkModeCommand @@ -3037,6 +3038,28 @@ class IntegrationTest { assert(File("099_screen_recording.mp4").exists()) } + @Test + fun `Case 099 - Screen recording is skipped, not failed, when the platform cannot record`() { + // Given + val commands = readCommands("099_screen_recording") + + val driver = driver { + } + driver.screenRecordingError = ScreenRecordingUnsupported("Roku") + + // When + Maestro(driver).use { + runBlocking { + orchestra(it).runFlow(commands) + } + } + + // Then + // The flow still passes, and no empty recording is left behind. + driver.assertEvents(emptyList()) + assert(!File("099_screen_recording.mp4").exists()) + } + @Test fun `Case 100 - tapOn multiple times`() { // Given diff --git a/maestro-utils/src/main/kotlin/ScreenRecordingUnsupported.kt b/maestro-utils/src/main/kotlin/ScreenRecordingUnsupported.kt new file mode 100644 index 0000000000..ae2cfcd0a4 --- /dev/null +++ b/maestro-utils/src/main/kotlin/ScreenRecordingUnsupported.kt @@ -0,0 +1,9 @@ +package maestro.utils + +/** + * The target platform has no way to capture video. Callers decide whether to degrade (skip the + * recording and carry on) or fail, so this is reported uniformly instead of per-driver ad-hoc + * `TODO()`s, `error()`s and silent no-ops. + */ +class ScreenRecordingUnsupported(target: String) : + UnsupportedOperationException("Screen recording is not supported on $target")