Skip to content

Record selected macOS windows natively with ScreenCaptureKit - #17012

Draft
vkodithala wants to merge 4 commits into
masterfrom
factory/macos-native-window-recording
Draft

vkodithala wants to merge 4 commits into
masterfrom
factory/macos-native-window-recording

Conversation

@vkodithala

@vkodithala vkodithala commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Record one explicitly selected macOS window with ScreenCaptureKit instead of silently recording the main display. A display crop cannot retain occluded window content. The native stream pins the window ID and owner, keeps a fixed H.264 canvas, and finalizes a partial recording when the target disappears. Screen recording stays on the existing ffmpeg path; Linux/Windows capture and overlays are unchanged. Shared smart trimming and thumbnail/upload handling remain in place.

The bridge loads ScreenCaptureKit dynamically on macOS 12.3+, preserving the older whole-screen path. Aspect-preservation and shadow configuration are guarded at macOS 14. Manual runtime verification covers macOS 26.6.2 arm64 only. Detached dialogs are not automatically included or retargeted.

Blocked on covered-content freshness at current head 310c1efaa9681f86354373148238f4f106790965: native rebuild passed, but synchronous locked BGRA copying did not fix stale covered frames. A corrected native-main-loop harness and confirmed floating-cover occlusion reproduce the failure. In the latest diagnostic, incoming ScreenCaptureKit callbacks stopped for 29.662s while fully covered and resumed 0.0067s after uncovering. Received source frames, private copies and encoded images match when callbacks arrive. This localizes the observed gap to callback delivery or upstream backing refresh, not demonstrated copy/encoder corruption; it does not establish an Apple bug or why delivery stops. Fixture drawing callbacks continue, but returning from a draw is not proof of WindowServer publication. The SDK describes ignoreGlobalClipSingleWindow as offscreen-placement clipping, not an occluded-refresh guarantee.

Current310c confirmed floating-cover diagnostic: before · after · completed. Earlier intermediate runs without genuine occlusion are unoccluded baselines, not freshness passes. Videos below remain explicitly earlier-head3807 evidence, not current-head passing proof.

Linked Issue

APP-5102 — supersedes only the crop-based window-capture portion of #14811. Broader parity/overlay work remains separate; this PR does not close the shared issue.

  • The linked issue is labeled ready-to-spec or ready-to-implement. Implementation was explicitly authorized; a spec was explicitly skipped.
  • Screenshots or a short video are included below.

Testing

  • Current 310c1ef: Linux cargo check -p computer_use --lib passed; rustfmt and clang-format applied. macOS native rebuild passed; covered-content freshness verification failed as described above. Current-head full native tests/lint and final acceptance proof remain outstanding.
  • Earlier 3807ffd1ec6198701664ad5fc80560127c216b15, macOS 26.6.2 arm64 / SDK 26.4: 95 computer_use lib tests passed, two intentional thumbnail tests skipped; targeted Clippy passed with warnings denied. Native compilation produced no candidate warnings.
  • Earlier3807 real production Recorder API, no mock/test-util: movement/resize retained identity and fixed 1440×944 output; circle aspect ratios 0.986–1.000; no cover pixels found in reduced-resolution frame scan. Close produced playable TargetUnavailable/StoppedEarly output. Invalid window/owner requests failed closed. Two-second limit finalized at 2.000s. Active-drop/start-cancel cleanup left no partials.
  • Earlier3807 raw 60.940s → prepared 40.730s; both action text markers survived. Overall raw clock delta was approximately 1× wall time, with the local stale-frame failure described above. GUI playback was sampled/seeking, not continuous frame-by-frame inspection.
  • Earlier3807 Linux: 92 targeted lib tests passed; Clippy and cargo check -p warp --lib passed. The unchanged real-X11 raise/visibility test fails in this sandbox and was excluded from the passing run.
  • CI run46189752778 at310c: build/test/lint jobs skipped because this PR is draft; aggregate fails on the deliberately skipped params job. This is not a validated matrix or a workflow defect.
  • Manually tested locally with ./script/run. Native recorder was exercised through an external production-API harness on the macOS runner, not the full desktop app.

Screenshots / Videos

Earlier3807 macOS GUI flow and actual output playback · still

Earlier3807 prepared native-window video · raw capture · 2s limit sample · checks, lifecycle and frame evidence

Agent Mode

  • Warp Agent Mode - This PR was created via Warp's AI Agent Mode

Run lifecycle checks, capture target with cover/move/resize/close, finalize, then play final and raw output in QuickTime.
Exact3807 native capture proof flow: Run lifecycle checks, capture target with cover/move/resize/close, finalize, then play final and raw output in QuickTime.

View video recording - 3807ffd exact-head native selected-window original MP4,60.940s,1440x944; covered clock freezes remain an unresolved observation.

View video recording - 3807ffd exact-head prepare_recording output40.730s,1440x944, both real text actions and undistorted tall resize; retains observed raw clock freezes.

View video recording - 3807ffd native2.000-second duration-bound output,LimitReached,StoppedEarly,1440x944.

Final.mp4 playback at 0:41 end: tall target top-left with FIRST and SECOND FINAL3807 strings, round circle, square, clock 101.5s, black padding on right
Final.mp4 playback at 0:41 end: tall target top-left with FIRST and SECOND FINAL3807 strings, round circle, square, clock 101.5s, black padding on right

Native utility baseline final-status capture — QA fixture on macOS 26.6.2 (25G83) arm64 / Xcode 26.4.1, not this PR's production candidate. This desktop/status screenshot is not visual proof of decoded resize cropping or signal outcomes.

Native utility prerequisite assessment (not implemented)

The separate QA AppKit fixture exercised /usr/sbin/screencapture -v -o -l<ID> -V10 <private.mov> on macOS 26.6.2 arm64. No source or permission changes were made.

  • Baseline: exit 0 at 10.304s; fully decoded H.264/yuv420p 1280×864, 9.98s / 561 frames. Requested path was absent at 100ms polls until after exit; stdout/stderr stayed empty. Appearance within the last polling interval cannot be excluded; no staging location was established.
  • Early stop: SIGINT at 4.093s exited with signal 2; SIGTERM at 4.010s exited with signal 15. Neither left a movie at the requested path. Installed help/man documented timed -V stop; no graceful CLI/signal stop mechanism was found.
  • Target loss: minimize/close produced fully decodable 4.58s / 4.22s partial movies ending black, while processes remained alive until approximately 10.2s. Minimize included the Dock animation. These were not ten-second frozen movies.
  • Resize: outer 640×432 → 400×590 (content 640×400 → 400×558). Encoded canvas stayed 1280×864; the live target occupied x=0…799 with black on the right, but lower circle/square content disappeared below the canvas and part of the title clipped. This is cropping, not aspect-preserving fit.
  • Shadow control: without -o, output was 1504×1088 surrounding the same 1280×864 target with opaque black; with -o the target filled the frame. This does not establish soft-shadow fidelity.

Publication limitation: the helper's 20-file artifact cap rejected raw movies, decoded frames, and the evidence archive; no retries were made. The linked baseline status screenshot remains recoverable, but it does not show the failure symptoms above. Movies, decoded frames, logs and aggregate results were local-only and may be lost after helper reset; do not treat them as downloadable proof. The selected direct utility route is not yet compatible with agreed early-stop and full-resize behavior. A bounded screenshot-to-ffmpeg feasibility proposal is awaiting user authorization; this PR remains draft at 310c1ef.

warp-agent-staging Bot and others added 3 commits November 28, 2026 20:19
Keep window identity isolated across occlusion and movement, encode a fixed canvas, and finalize partial captures when the target becomes unavailable. Preserve the existing screen recorder and shared smart trim.

Co-authored-by: vkodithala <varoon@warp.dev>
Co-authored-by: vkodithala <varoon@warp.dev>
Co-authored-by: vkodithala <varoon@warp.dev>
@cla-bot cla-bot Bot added the cla-signed label Nov 28, 2026
@warp-agent-staging

Copy link
Copy Markdown
Contributor

This PR was generated with Warp, requested by @vkodithala.

Comment @warp-staging-factory on this PR to send it follow-up work.

View run View on Slack

@warp-agent-staging warp-agent-staging Bot added the factory:eng-factory-slim Label associated to the "eng-factory-slim" factory label Nov 28, 2026
Remove CoreImage from the BGRA handoff so capture buffers cannot be retained by deferred image rendering. Native covered-content freshness still requires macOS verification.

Co-authored-by: vkodithala <varoon@warp.dev>
@warp-agent-staging

Copy link
Copy Markdown
Contributor

Freshness still blocks 310c1ef: independent Terminal reproduces starvation with callback-only SCK, SCRecordingOutput, and OS-default configuration (57.49s gap). The built-in explicit-window screencapture video stays fresh under cover in the same macOS26.6.2 session. Root cause remains unknown; no more speculative SCK changes. Backend approach decision pending.

View in factory

@warp-agent-staging

Copy link
Copy Markdown
Contributor

First principles: what works, what stopped updating, and the smaller option

I have not demonstrated a regression in the shipped recorder. The failure is in this proposed new selected-window video path when another window covers the target. The earlier demo does show useful things working: window isolation, movement/resize, and playable output. Calling it generally frozen—or presenting it as complete passing proof—was imprecise.

What ‘freeze’ means

The movie keeps playing, but the target's picture stops changing. Think of a recorded stopwatch: the playback scrubber advances while the stopwatch holds an old number, then jumps forward after uncovering. It is not a black frame or a player crash.

There are several different evidence files, with different timelines. The earlier GUI demonstration is not the same file as the raw or trimmed output; timestamps must not be transferred between them. A later precisely timed diagnostic, using Terminal printing a counter once per second, held counter 2727 from movie time 1.847s to 59.333s, then jumped to 2784. That diagnostic used OS-default ScreenCaptureKit settings and Apple's own SCRecordingOutput, without our custom copying/encoding machinery. Its original movie remains on the verification runner, not a published video artifact, so this is a recorded diagnostic finding, not a seek instruction for the earlier shared demo.

The built-in screencapture utility separately recorded that Terminal window under cover with counters advancing throughout sampled offsets 0–45s. Fresh isolated-window video is therefore possible in that tested macOS 26.6.2 session. We have not established why the tested direct-SCK path differs, or proved an Apple bug.

Three separate jobs

  1. Input: deliver clicks and keys to a particular app/window.
  2. Capture: obtain pictures of that window.
  3. Recording: turn pictures into a timed movie, then use our existing trim/upload pipeline.

Background input and individual screenshots do not automatically provide a continuous video stream. Adding recording does not require rebuilding input.

Linux today

Rust resolves the X11 window and dimensions, checks visibility at startup, raises the target if necessary, then launches ffmpeg x11grab -window_id to capture and encode. Rust supervises the process and sends SIGINT to finalize it.

Importantly, Linux requires a foreground-visible target at startup; it is not an established background/covered-window video guarantee. The visibility check is not continuous. Treating occlusion-proof Mac video as already-achieved Linux parity overstated the baseline.

Sources: window selection and ffmpeg, visibility and raise, stop/finalization.

Existing Mac background computer use

Pictures: we already invoke Apple's /usr/sbin/screencapture -l <windowID> -o for a window PNG, without raising it. This asks for the window itself; it does not crop the desktop. Screenshot code.

Input: we send Quartz events to the owning process with CGEventPostToPid. Mouse events carry window identity/local coordinates, and an activation handshake lets the target accept background input while suppressing the foreground-focus transition. This uses existing native interop, including private event fields and a dynamically resolved window-location setter—not SCK. Sources: posting, activation, targeted mouse events.

What the new .m file does

The draft calls ScreenCaptureKit inside our process: find a matching windowID/ownerPID; create a single-window filter and stream; receive and copy pixel buffers; encode H.264 through AVAssetWriter; manage timing/limits/window loss; expose start/status/stop/dispose to Rust. A timer writes the latest received picture. When fresh callbacks stop, that means writing the old picture repeatedly.

Sources: selection/configuration/encoder, timer/callbacks, Rust boundary.

It is Objective-C, not merely plain C. ARC manages Objective-C object lifetimes here, but raw buffers, pointer copies, callbacks, and Rust FFI still require real safety reasoning. Warp has longstanding precedent: existing Objective-C window code, its unsafe Rust boundary, and native build setup.

Precedent does not make this minimal. This adds 434 lines of Objective-C and a 217-line Rust wrapper before integration changes. No other SCK capture implementation was found in the pinned tree. Moving it to Rust Objective-C bindings would not remove the capture/lifetime/encoding machinery.

What crop means

A desktop crop records the display, then keeps rectangle (x, y, width, height). If a red window covers the target, those pixels are red; cropping cannot recover the hidden target. A fixed crop also loses the target when it moves; tracking bounds fixes movement, not overlap or unrelated content leaking into the video.

Window capture instead asks the source for a windowID. Linux's -window_id and Mac's screencapture -l are window-selection mechanisms, not desktop crops. Smart trimming is different again: it removes stretches of time, not unwanted spatial pixels, and cannot reconstruct missed pictures.

Cropping is reasonable for ‘record this visible region, including whatever covers it.’ It was dismissed for isolated background-window recording, not because it is inherently bad. Before this PR, Mac video captured the main display through ffmpeg/avfoundation and ignored window targeting; there was no working Mac background-window movie stream being replaced.

Smallest proposed direction

Use the Linux architecture: Rust supervises an external capture process, which writes the movie; keep our existing preparation/upload path. On Mac, try the same preinstalled screencapture utility already used for screenshots, now in video mode with an explicit windowID. This is not a desktop crop and avoids a custom in-process frame-copy/encoder stack. I should have prioritized that smaller route.

The covered-window success on macOS 26.6.2 makes it a candidate, not a finished fix. Early stop, cancellation, target loss, resize/fixed output geometry, limits, and supported OS behavior still need validation; ffmpeg's stop protocol cannot simply be assumed for Apple's tool.

No backend change has been made in response to these questions. This PR remains draft; the approach choice is still open.

View in factory

@warp-agent-staging

Copy link
Copy Markdown
Contributor

Inspectable evidence and availability correction

In the original 60.940s RAW video, prior samples show clock 71.0 across 31–36s and 80.6 across 41–46s. These are RAW-movie offsets, not timestamps in the shared GUI demonstration; its exact seek offset was not established.

A separate, later 38.430s diagnostic at the same3807 head gives the clearer comparison: at capture offset 29.082s, the recorded frame reads56.1, while the contemporaneous independent target image reads64.9—about8.8s stale. Earlier in that run, at19.270s, the values were55.0 versus55.1, so this is not a permanent clock offset. That diagnostic's original RAW movie.

At current310c, a separate confirmed-cover diagnostic at15.091s likewise shows recorded37.5 versus independent46.5. These two artifacts are screenshots of the images displayed in Preview.

Correction to the explanation above: the later OS-default57.49s diagnostic movie was never published and its scratch directory is no longer present in the resumed runner. Its measurements survive in the investigation record, but the movie is not currently available to inspect. The published comparisons above are the recoverable evidence. None establishes a regression from the previously shipped recorder.

View in factory

@warp-agent-staging

Copy link
Copy Markdown
Contributor

Linux comparison: stop/save is the difference; resize parity was overstated

Both signals stop both processes. The difference is whether stopping leaves a usable movie.

Stop, finalization, and upload are separate

On Linux, x11grab supplies the window pixels; ffmpeg handles signals, encoding, and finalizing the MP4. Our normal Stop sends SIGINT to that specific child and waits up to 15 seconds for finalization. FFmpeg also installs a SIGTERM handler, so a single SIGINT or SIGTERM after recording starts normally takes its graceful shutdown path. This is source-backed expected behavior, not a new live X11 test performed for this answer.

The Mac utility tests showed something different: SIGINT and SIGTERM stopped screencapture, but neither left a movie at the requested path. Letting its 10-second timer finish produced a playable movie. Thus the precise limitation is no demonstrated way to stop early and keep the requested movie with the tested invocation, not an inability to stop the process.

pkill selects processes and sends a signal; by default that is SIGTERM. If it reaches only the ffmpeg child and Warp stays alive, ffmpeg can finalize and Warp's exit watcher can attempt preparation/upload. Neither pkill nor x11grab uploads anything. Killing Warp/the uploader too, upload failures, or a recording without committed actions can prevent publication. SIGKILL (-9) bypasses cleanup; the ordinary MP4 is not guaranteed playable after that, even with +faststart. Repeated/forced termination is not the graceful-stop guarantee.

Sources: Linux recorder and finalization, exit watcher and preparation/upload, FFmpeg signal handling. The FFmpeg reference is upstream source, not a claim that this run tested a particular deployed binary.

Resize: Linux does not promise full-content fitting either

I held this Mac draft to a stronger standard than the existing Linux implementation. Linux resolves the initial dimensions once and passes a fixed -video_size; it has no dynamic scale/pad/reconfiguration loop. FFmpeg's window-capture documentation says enlarging a window does not record the added area; closing, unmapping/minimizing, or shrinking below the capture size ends recording. Primary documentation addition. No new live Linux resize test was performed.

Mac screencapture does react to resizing, but did not fit the complete new window into the fixed canvas in our test. A 640×432 window became 400×590; output stayed 1280×864. The narrower live window occupied the left 800 pixels, with black to its right, while added vertical content was clipped. ‘Does not adapt’ was too broad; ‘does not preserve all resized content by fitting it into the canvas in this test’ is accurate.

Full-content aspect-preserving resize was an approach I proposed and carried into the draft—not existing Linux parity or a separate requirement independently demanded by the requester. Accepting Linux-like resize limitations is a reasonable v1 scope choice and should not, by itself, force a more elaborate backend.

What remains to choose

The simple utility remains a plausible timed-only v1 if that workflow is acceptable: choose a duration, let the timer finish, then prepare/upload; document resize limitations. Early-stop/save is the important remaining difference. For example, a Stop at 4 seconds cannot currently return its saved movie promptly; with a preselected 10-minute timer, availability could wait until that timer expires. Killing early produced no requested movie.

This does not prove that no better Mac mechanism exists. It establishes the tested invocation's behavior on macOS 26.6.2 with SIGINT/SIGTERM. The raw diagnostic publication failed at the artifact cap, as documented in the PR; the available baseline screenshot is not visual proof of signal/cropping failures.

No code has changed. The decision remains open: accept timed-only behavior, authorize the proposed bounded screenshot-to-ffmpeg feasibility check, or pause. This comparison does not itself accept limitations or authorize another backend.

View in factory

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

Labels

cla-signed factory:eng-factory-slim Label associated to the "eng-factory-slim" factory

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant