Skip to content

fix: don't ack device.screenrecord until the broadcast is confirmed live - #339

Open
gmegidish wants to merge 2 commits into
mainfrom
fix/screenrecord-broadcast-race
Open

fix: don't ack device.screenrecord until the broadcast is confirmed live#339
gmegidish wants to merge 2 commits into
mainfrom
fix/screenrecord-broadcast-race

Conversation

@gmegidish

@gmegidish gmegidish commented Aug 11, 2026

Copy link
Copy Markdown
Member

Summary

device.screenrecord was acking status: "recording" the instant its handler goroutine was scheduled, not once the recording was actually confirmed live. On real iOS devices, "live" requires DeviceKit to launch, DeviceKitH264 to start, and the ReplayKit "Start Broadcast" system sheet to be clicked (devices/ios.go's clickStartBroadcastButton) — all of which happens asynchronously, after the ack was already sent.

Any device command (device.dump.ui, device.io.tap, etc.) issued right after device.screenrecord returns could therefore race the still-in-progress broadcast picker. If it collided with DeviceKit's own click attempt, the picker got stuck on "Press to Start Broadcasting" and the failure only surfaced ~13s later, when device.screenrecord.stop was called — by which point the caller had already been driving the app blind against a system sheet instead of the real UI.

Reproduced and root-caused via a real device run cross-referencing the mobilewright driver log with mobilefleet-client's server logs:

  • Handling device.screenrecordScreen recording started 1.7ms later, acked before DeviceKit had even presented the picker.
  • device.io.tap landed right as the picker appeared.
  • dump.ui showed "Press to Start Broadcasting" stuck for ~8s.
  • screenrecord.stop, called 13s after start, is where the failure first surfaced: failed to click Start Broadcast button: timeout waiting for BroadcastUploadExtension button to appear.

Fix

Thread a "ready" signal from the point DeviceKit is actually confirmed running up to the RPC handler:

  • devices.ScreenCaptureConfig.OnReady — fired in devices/ios.go right after DeviceKit is confirmed running (reused or freshly started with the broadcast picker clicked), before connecting to the H.264 stream.
  • commands.ScreenRecordRequest.Ready / signalReady() — plumbs that (or an early error) up through ScreenRecordCommand. Android/simulator/remote devices signal ready immediately since they have no equivalent async on-device UI step; every early-error return now also signals the error.
  • server.RecordingSession.Ready — a buffered channel carrying the signal into the RPC layer.
  • handleScreenRecord now selects on Ready / Done / a 60s timeout instead of acking unconditionally:
    • success → ack only once the broadcast is confirmed live
    • startup failure → returned synchronously from device.screenrecord itself, instead of silently surfacing later at stop time
    • stuck start → times out at 60s (sized above a worst-case cold DeviceKit start) and clears the session so it doesn't wedge the recorder for subsequent calls

handleScreenRecord fired the DeviceKit/ReplayKit startup in a goroutine
and returned status:"recording" immediately, racing any device command
sent right after against the still-in-progress (and sometimes failing)
broadcast picker click on real iOS devices.
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Screen recording startup now reports readiness or failure through Ready channels and an iOS capture callback. The server waits for this result, handles premature termination and startup errors, and applies a 60-second timeout before acknowledging success.

Changes

Screen recording readiness

Layer / File(s) Summary
Readiness contracts
commands/screenrecord.go, server/recording.go, devices/common.go
ScreenRecordRequest, RecordingSession, and ScreenCaptureConfig now expose readiness signaling fields.
Command and capture signaling
commands/screenrecord.go, devices/ios.go
Recording paths report startup errors or success. AVC capture invokes OnReady after DeviceKit starts and before streaming begins.
Server startup gate
server/server.go
handleScreenRecord waits for readiness, handles startup failures and premature completion, and applies a 60-second timeout.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant handleScreenRecord
  participant ScreenRecordCommand
  participant iOSCapture
  Client->>handleScreenRecord: request screen recording
  handleScreenRecord->>ScreenRecordCommand: start with Ready channel
  ScreenRecordCommand->>iOSCapture: start capture with OnReady
  iOSCapture-->>ScreenRecordCommand: capture is live
  ScreenRecordCommand-->>handleScreenRecord: readiness result
  handleScreenRecord-->>Client: success or startup error
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: delaying device.screenrecord acknowledgment until the broadcast is confirmed live.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/screenrecord-broadcast-race

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/server.go`:
- Around line 1159-1161: In the screen-recording startup timeout branch, call
recorder.stop() before recorder.clear() so the active session is stopped before
its reference is removed. Preserve the existing timeout error return and apply
this ordering within the timeout case handling the screenRecordReadyTimeout
event.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 76a8d952-1005-4442-bf4d-56ab2d13f865

📥 Commits

Reviewing files that changed from the base of the PR and between 79bf822 and 00bdd50.

📒 Files selected for processing (5)
  • commands/screenrecord.go
  • devices/common.go
  • devices/ios.go
  • server/recording.go
  • server/server.go

Comment thread server/server.go
Comment on lines +1159 to +1161
case <-time.After(screenRecordReadyTimeout):
recorder.clear()
return nil, fmt.Errorf("timed out waiting for recording to start")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Stop the recording before clearing the session.

recorder.clear() only removes the session reference. It does not close session.StopChan.

If startup exceeds 60 seconds, the command goroutine can continue. A real iOS user can then confirm the broadcast after this RPC returns a timeout. The capture can start without an active session, and a later request can start another recording.

Close the session through recorder.stop() before clearing it.

Proposed fix
 case <-time.After(screenRecordReadyTimeout):
+	_, _ = recorder.stop()
 	recorder.clear()
 	return nil, fmt.Errorf("timed out waiting for recording to start")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case <-time.After(screenRecordReadyTimeout):
recorder.clear()
return nil, fmt.Errorf("timed out waiting for recording to start")
case <-time.After(screenRecordReadyTimeout):
_, _ = recorder.stop()
recorder.clear()
return nil, fmt.Errorf("timed out waiting for recording to start")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/server.go` around lines 1159 - 1161, In the screen-recording startup
timeout branch, call recorder.stop() before recorder.clear() so the active
session is stopped before its reference is removed. Preserve the existing
timeout error return and apply this ordering within the timeout case handling
the screenRecordReadyTimeout event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant