Skip to content

fix: timing issue DCHECK crash in DesktopCapturer on macOS - #50960

Merged
ckerr merged 1 commit into
mainfrom
fix/macos-dcheck-desktop-capturer-is-ready
Apr 14, 2026
Merged

ckerr merged 1 commit into
mainfrom
fix/macos-dcheck-desktop-capturer-is-ready

Conversation

@ckerr

@ckerr ckerr commented Apr 11, 2026 •

Copy link
Copy Markdown
Member

Description of Change

Take @MarshallOfSound's suggestion in fix_add_support_for_skipping_first_2_no-op_refreshes_in_thumb_cap.patch to clean up the desktop capturer:

This [patch] really isn't ideal at all, we need to refactor desktopCapturer (read completely re-implement it) to use StartUpdating and handle the events instead of using the "get the list once" method.

I came across this while tracking down a recurring crash in macOS CI (example here) and found that refactoring DesktopCapturer to Sam's suggestion should also fix this crash.

  • Replace the one-shot Update() callback model with the continuous StartUpdating() observer model for NativeDesktopMediaList.

    This fixes a macOS DCHECK(can_refresh()) crash in UpdateSourceThumbnail(), where ScreenCaptureKit's recurrent thumbnail capturer would post UpdateSourceThumbnail callbacks after the one-shot refresh_callback_ had been consumed. Now, can_refresh() is always true because refresh_callback_ is repopulated via ScheduleNextRefresh().

  • Remove the skip_next_refresh_ Chromium patch, which was a workaround for the timing mismatch between the one-shot Update() model and ScreenCaptureKit's asynchronous thumbnail delivery.


I asked Claude to outline this refactor's logic flow. Previously it was a one-shot subscription, which didn't fit Chromium's model very well. The new workflow is like this:

JS: getSources({types: ['window', 'screen']})
  │
  ▼
StartHandling()
  ├─ creates window_capturer_, screen_capturer_
  ├─ creates ListObserver for each (separate from DesktopCapturer)
  ├─ pending_lists_ = 2
  │
  ▼
window_capturer_->StartUpdating(observer)
  │  refresh_callback_ = ScheduleNextRefresh   ← always re-set!
  │  Refresh(true) → worker enumerates → UpdateSourcesList()
  │    │  OnSourceAdded(0) → has_sources_ = true, MaybeNotifyReady()
  │    │  OnSourceAdded(1) → MaybeNotifyReady() (notified_=false still, but...)
  │    │  ...all sources added...
  │    ▼
  │  OnRefreshComplete() → ScheduleNextRefresh()
  │    │  refresh_callback_ = ScheduleNextRefresh  ← repopulated immediately
  │    │  posts next Refresh() after delay
  │    ▼
  │  thumbnails arrive one-by-one → OnSourceThumbnailChanged(i)
  │    │  → MaybeNotifyReady() → IsReady()? all thumbnails non-null?
  │    │    not yet → returns
  │    │  ...last thumbnail arrives...
  │    │  → IsReady() = true, notified_ = false → notified_ = true
  │    │  → PostTask(OnListReady)    ← POSTED, not called synchronously
  │    ▼
  │  [next message loop iteration]
  │  OnListReady(window_list)
  │    ├─ CollectSourcesFrom() — all sources present, all thumbnails populated
  │    ├─ --pending_lists_ → 1 (not zero yet, wait for screen)
  │
  ▼
screen_capturer_->StartUpdating(observer)
  │  ...same flow...
  │  → PostTask(OnListReady)
  │
  ▼
OnListReady(screen_list)
  ├─ CollectSourcesFrom() — populates display_ids
  ├─ --pending_lists_ → 0
  ├─ HandleSuccess() — safe: called from posted task, nothing on stack
  │   ├─ emits _onfinished to JS
  │   ├─ destroys observers, then capturers (clean, no re-entrancy)
  │   └─ Unpin()

Checklist

Release Notes

Notes: Fixed DesktopCapturer crash on macOS.

@ckerr
ckerr requested a review from a team as a code owner April 11, 2026 20:07
@ckerr ckerr added semver/patch backwards-compatible bug fixes target/40-x-y PR should also be added to the "40-x-y" branch. target/41-x-y PR should also be added to the "41-x-y" branch. target/42-x-y PR should also be added to the "42-x-y" branch. labels Apr 11, 2026
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Apr 11, 2026
@ckerr
ckerr marked this pull request as draft April 11, 2026 20:07

@MarshallOfSound MarshallOfSound left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Woooo delete the patch 🥳 That said I think we should hold off on backporting this initially, this area is fiddly and likely to reveal timing issues when tested in Real Apps ™️

@ckerr ckerr added no-backport and removed target/40-x-y PR should also be added to the "40-x-y" branch. target/41-x-y PR should also be added to the "41-x-y" branch. target/42-x-y PR should also be added to the "42-x-y" branch. labels Apr 11, 2026
@ckerr
ckerr force-pushed the fix/macos-dcheck-desktop-capturer-is-ready branch 2 times, most recently from 2d15f42 to a7271bc Compare April 12, 2026 12:35
Replace the one-shot Update() callback model with the continuous
StartUpdating() observer model for NativeDesktopMediaList.

Fixes a macOS DCHECK(can_refresh()) crash in UpdateSourceThumbnail(),
where ScreenCaptureKit's recurrent thumbnail capturer would post
UpdateSourceThumbnail callbacks after the one-shot refresh_callback_
had been consumed. Now, can_refresh() is always true because
refresh_callback_ is repopulated via ScheduleNextRefresh().

Each capturer (window, screen) gets its own ListObserver that tracks
readiness via OnSourceAdded and OnSourceThumbnailChanged events.
Once a list has both sources and thumbnails (or thumbnails aren't
requested), its data is snapshotted and the capturer checks if all
requested types are ready before resolving to JS.

Also remove the "skip_next_refresh_" Chromium patch, which was a
workaround for the timing mismatch between the one-shot Update()
model and ScreenCaptureKit's asynchronous thumbnail delivery.

refactor: simplify state logic in DesktopCapturer
@ckerr
ckerr force-pushed the fix/macos-dcheck-desktop-capturer-is-ready branch from a7271bc to 5931cd8 Compare April 12, 2026 12:39
@electron-cation electron-cation Bot removed the new-pr 🌱 PR opened recently label Apr 12, 2026
@ckerr
ckerr marked this pull request as ready for review April 13, 2026 13:00
@electron-cation electron-cation Bot added the new-pr 🌱 PR opened recently label Apr 13, 2026
@ckerr ckerr changed the title refactor: use StartUpdating() in desktopCapturer fix: timing issue DCHECK crash in DesktopCapturer on macOS Apr 13, 2026

@dsanders11 dsanders11 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nice! This is a clean solution to the issue. Code changes LGTM, and I manually validated that it works on my macOS machine.

@electron-cation electron-cation Bot removed the new-pr 🌱 PR opened recently label Apr 14, 2026
@ckerr
ckerr merged commit dad4ab6 into main Apr 14, 2026
165 of 172 checks passed
@ckerr
ckerr deleted the fix/macos-dcheck-desktop-capturer-is-ready branch April 14, 2026 14:03
@release-clerk

release-clerk Bot commented Apr 14, 2026

Copy link
Copy Markdown

Release Notes Persisted

Fixed DesktopCapturer crash on macOS.

@trop

trop Bot commented May 5, 2026

Copy link
Copy Markdown
Contributor

@jkleinsc has manually backported this PR to "42-x-y", please check out #51506

@trop trop Bot added the in-flight/42-x-y label May 5, 2026
ckerr added a commit that referenced this pull request May 6, 2026
* fix: timing issue DCHECK crash in DesktopCapturer on macOS (#50960)

refactor: use StartUpdating in desktopCapturer

Replace the one-shot Update() callback model with the continuous
StartUpdating() observer model for NativeDesktopMediaList.

Fixes a macOS DCHECK(can_refresh()) crash in UpdateSourceThumbnail(),
where ScreenCaptureKit's recurrent thumbnail capturer would post
UpdateSourceThumbnail callbacks after the one-shot refresh_callback_
had been consumed. Now, can_refresh() is always true because
refresh_callback_ is repopulated via ScheduleNextRefresh().

Each capturer (window, screen) gets its own ListObserver that tracks
readiness via OnSourceAdded and OnSourceThumbnailChanged events.
Once a list has both sources and thumbnails (or thumbnails aren't
requested), its data is snapshotted and the capturer checks if all
requested types are ready before resolving to JS.

Also remove the "skip_next_refresh_" Chromium patch, which was a
workaround for the timing mismatch between the one-shot Update()
model and ScreenCaptureKit's asynchronous thumbnail delivery.

refactor: simplify state logic in DesktopCapturer
(cherry picked from commit dad4ab6)

* fix: do not block indefinitely on thumbnails in desktopCapturer (#51128)

* fix: do not block indefinitely on thumbnails in desktopCapturer

fixes dad4ab6 regression

* fix: build error

* fixup! fix: do not block indefinitely on thumbnails in desktopCapturer

chore: remove unnecessary code

* Update shell/browser/api/electron_api_desktop_capturer.cc

Co-authored-by: Niklas Wenzel <[email protected]>

---------

Co-authored-by: Niklas Wenzel <[email protected]>
(cherry picked from commit a1d28e6)

* fix: dangling `raw_ptr` regression in `DesktopCapturer` (#51158)

fix: dangling raw_ptr in desktopCapturer
(cherry picked from commit bef68b6)

* fix: do not pass a `DesktopMediaList* to DesktopCapturer::OnListReady()` (#51399)

refactor: do not pass a DesktopMediaList* to DesktopCapturer::OnListReady()

The list pointer was being used as a proxy for its type, so just pass
the type instead. This solves a lifecycle issue occurring in CI where
the callack can outlive the DesktopMediaList.

Sample error log:

[48471:0428/193441.269750:FATAL:base/allocator/partition_alloc_support.cc:798] Detected dangling raw_ptr in unretained with id=0x0000013c02e14378:
 Task trace:
 0   Electron Framework  0x000000012283a0ba electron::api::DesktopCapturer::ListObserver::MaybeNotifyReady() + 170
 1   Electron Framework  0x0000000133246dc5 NativeDesktopMediaList::Worker::OnRecurrentCaptureResult(webrtc::DesktopCapturer::Result, std::__Cr::unique_ptr<webrtc::DesktopFrame, std::__Cr::default_delete<webrtc::DesktopFrame>>, long) + 357
 2   Electron Framework  0x000000013328dbcf (anonymous namespace)::ScreenshotManagerCapturer::OnRecurrentCaptureTimer() + 1343
 Stack trace:
 0   Electron Framework  0x000000012ade42f2 base::debug::CollectStackTrace(base::span<void const*, 18446744073709551615ul, void const**>) + 18
 1   Electron Framework  0x000000012add00e1 base::debug::StackTrace::StackTrace(unsigned long) + 225
 2   Electron Framework  0x000000012ade978a base::allocator::UnretainedDanglingRawPtrDetectedCrash(unsigned long) + 90
 3   Electron Framework  0x000000012ae437f7 base::internal::RawPtrBackupRefImpl<true>::ReportIfDanglingInternal(unsigned long) + 391

(cherry picked from commit f8d0412)

---------

Co-authored-by: Charles Kerr <[email protected]>
Co-authored-by: Niklas Wenzel <[email protected]>
@trop trop Bot added merged/42-x-y PR was merged to the "42-x-y" branch. and removed in-flight/42-x-y labels May 6, 2026
jeanfbrito added a commit to RocketChat/Rocket.Chat.Electron that referenced this pull request Jul 14, 2026
…e stack (#3414)

Electron 42's macOS ScreenCaptureKit backend bounds getSources() at ~3s
(upstream hang/crash fixes), returning an empty array or empty thumbnails
when enumerations run back-to-back. The picker's 3s polling plus the
post-selection re-enumeration turned those empty results into a blank
"No windows found" list and denied valid share attempts.

- Split the desktop capturer cache into per-type buckets: screen-only
  enumeration is fast (~700ms) and reliable; window enumeration is paced
  with a 4s post-completion cooldown (cold-start chain bypasses it once)
- Never overwrite a non-empty bucket with an empty enumeration result;
  keep the bucket stale so it retries on the next opportunity
- Merge thumbnails by source id so a source arriving with an empty
  thumbnail keeps its last good preview instead of being dropped
- Validate the selected source against the cache (the same list the
  picker rendered from) instead of re-enumerating on Share; fall back
  to one direct enumeration only when the cache is empty
- Keep the previous source list when a renderer fetch fails

Measured on macOS with Electron 42.5.0: tight-loop getSources returned
0 sources in ~75% of calls; screen-only calls never failed; alternating
per-type calls with 4s gaps returned complete results every round.

Documented in docs/KNOWN_ISSUES.md with upstream refs
(electron/electron#51128, electron/electron#50960) and the macOS 15+
useSystemPicker follow-up.
jeanfbrito added a commit to RocketChat/Rocket.Chat.Electron that referenced this pull request Jul 15, 2026
…icker, sidebar tooltip) (#3417)

* fix: #3244 sidebar tooltip null in shortcut formatting (#3326)

- index.tsx: order <= 9 -> order < 9 (off-by-one, server #10 showed shortcut)
- ServerButton.tsx: conditional shortcut string in tooltip (null rendered as '(^+null)')

(cherry picked from commit e405a6a)

* fix: keep screen picker sources stable under Electron 42 macOS capture stack (#3414)

Electron 42's macOS ScreenCaptureKit backend bounds getSources() at ~3s
(upstream hang/crash fixes), returning an empty array or empty thumbnails
when enumerations run back-to-back. The picker's 3s polling plus the
post-selection re-enumeration turned those empty results into a blank
"No windows found" list and denied valid share attempts.

- Split the desktop capturer cache into per-type buckets: screen-only
  enumeration is fast (~700ms) and reliable; window enumeration is paced
  with a 4s post-completion cooldown (cold-start chain bypasses it once)
- Never overwrite a non-empty bucket with an empty enumeration result;
  keep the bucket stale so it retries on the next opportunity
- Merge thumbnails by source id so a source arriving with an empty
  thumbnail keeps its last good preview instead of being dropped
- Validate the selected source against the cache (the same list the
  picker rendered from) instead of re-enumerating on Share; fall back
  to one direct enumeration only when the cache is empty
- Keep the previous source list when a renderer fetch fails

Measured on macOS with Electron 42.5.0: tight-loop getSources returned
0 sources in ~75% of calls; screen-only calls never failed; alternating
per-type calls with 4s gaps returned complete results every round.

Documented in docs/KNOWN_ISSUES.md with upstream refs
(electron/electron#51128, electron/electron#50960) and the macOS 15+
useSystemPicker follow-up.

(cherry picked from commit dddd2cc)

* fix: externalize dependency subpath imports in rollup bundles (#3411)

rollup externals matched module ids by exact name only, so subpath
entrypoints like `react-dom/client` (used by createRoot in
rootWindow.ts, log-viewer-window.tsx, and screenSharePickerMount.tsx)
did not match the `react-dom` external and got bundled as
build-time-NODE_ENV ReactDOM, while `react` stayed external and
resolved to a different (dev) copy from the asar at runtime — mixing
incompatible React internals and crashing the renderer
(SUP-1072, ReferenceError: exports is not defined).

makeExternal() now matches `id === moduleName || id.startsWith(moduleName + '/')`
so subpath imports are externalized alongside their base package.
scripts/check-bundle-externals.mjs guards the build against regressing
back to bundled React internals, wired into `yarn build`.

(backported to 4.15.x)

Adapted from master commit 0dafe39: 4.15.4 has no
`screen-picker-window.js` rollup entry (the screen picker mounts
inside the video-call-window bundle via screenSharePickerMount.tsx,
not a separate window/entry point in this release), so that entry and
its assertions were omitted from check-bundle-externals.mjs. All other
bundle configs and the check script are ported as-is.

* fix: correct auto-merge artifact in ScreenSharingRequestTracker backport

The cherry-pick of dddd2cc (#3414) auto-merged with references to
master's entry/finishActive queue API, which doesn't exist in 4.15.4's
flat cb/markComplete structure — this failed typecheck. Replaced with
4.15.4's existing cb(...) calling convention, matching the fallback
path directly below it in the same function.

Also fixed the corresponding cherry-picked spec assertion: it expected
cb to be called with `null` (master's deny convention), but 4.15.4's
DisplayMediaCallback deny convention is `{ video: false }` throughout
this file — updated the assertion to match.

* fix: remove leftover merge-conflict marker fragment from KNOWN_ISSUES.md

The docs/KNOWN_ISSUES.md merge during the backport left a trailing
`>>>>>>> dddd2cc (...)` conflict-marker remnant appended to the last
line of the file. Removed; no other content was affected.
MarshallOfSound pushed a commit that referenced this pull request Sep 7, 2026
* chore: remove dump_syms.patch

It patches generate_breakpad_symbols.py, which Electron has not invoked
since #19042.

* chore: remove crashpad_pid_check.patch

Its removal condition (crashpad initialized before the sandbox) was met in
#23265; what remained disabled is crashpad's client PID verification on
Windows.

* chore: remove disable_compositor_recycling.patch

Since #44628 macOS uses the views WebContentsView with a parent
ui::Compositor, so the recyclable-compositor path this targeted is not taken;
its remaining effect was suppressing DelegatedFrameHost::WasHidden.

* chore: remove chore_provide_iswebcontentscreationoverridden_with_full_params.patch

Nothing overrides IsWebContentsCreationOverridden or CreateCustomWebContents
since #52472.

* chore: remove fix_select_the_first_menu_item_when_opened_via_keyboard.patch

Upstream selects the first item for keyboard-opened menus on Windows since
M133 (https://chromium-review.googlesource.com/c/chromium/src/+/5868220)
behind PlatformStyle::kAutoSelectFirstMenuItemFromKeyboard.

* chore: remove revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch

Nothing in Electron references the feature; backgroundThrottling: false and
--disable-background-timer-throttling cover the use case.

* chore: remove fix_fire_menu_popup_start_for_dynamically_created_aria_menus.patch

Upstream fires the popup events for dynamically created menus since M150
(https://chromium-review.googlesource.com/c/chromium/src/+/7804599), and the
hunk here was gated on a feature nothing enabled.

* chore: remove build_disable_llvm_unroll-add-parallel-reductions_on_apple_targets.patch

The miscompile was fixed by llvm/llvm-project#210957, which is in the bundled
clang (llvmorg-24-init-3796).

* chore: remove refactor_unfilter_unresponsive_events.patch

web-contents.ts re-applied the same three conditions (not ignored, visible,
renderer initialized) before emitting 'unresponsive', so the unfiltered
notification was never observable. Let Chromium filter and emit directly.

* chore: remove fix_disable_enable_resource_allowlist_generation_on_windows.patch

The siso-incompatible link wrapper it worked around was reverted upstream
(https://chromium-review.googlesource.com/c/chromium/src/+/8275653, in this
Chromium), so set enable_resource_allowlist_generation from all.gn as intended.

* chore: remove nan test_use_v8_version_check_instead_of_node_version_check.patch

With Node 24 the upstream nodeVersion > 22 check already selects the same
expectations, so the V8-version check changes nothing.

* chore: remove nan fix_remove_deprecated_propertycallbackinfo_holder.patch

V8 re-added PropertyCallbackInfo::Holder(), so nan's tests compile unchanged.

* chore: remove reclient-configs fix_disable_compression_threshold.patch

reproxy.cfg is not read under siso.

* chore: remove reclient-configs build_on_windows_provide_clang_wrapper_as_toolchain_input.patch

siso merges inputs and toolchain_inputs from the rewrapper cfg and passes the
remote_wrapper itself, so the distinction no longer matters.

* chore: remove reclient-configs fix_temporarily_use_toolchain_inputs_exclusively_instead_of_inputs.patch

Same as the Windows one: a no-op under siso's merged input list, and the python
cfgs it also touched have no consumer since Chromium dropped python remote
actions.

* chore: remove reclient-configs reland_mojo_use_large_worker_for_mojom_parser_action.patch

The rewrapper_<os>_large.cfg consumer was removed upstream in
https://chromium-review.googlesource.com/c/chromium/src/+/6325750.

* chore: reduce fix_add_python_remote_wrapper.patch to the clang wrapper chmod

Chromium removed python remote actions
(https://chromium-review.googlesource.com/c/chromium/src/+/6289606), so the
python wrapper and cfg hunks have no consumer; the exec bit on the generated
clang_remote_wrapper is the part siso still relies on from macOS hosts.

* chore: trim dead hunks from render_widget_host_view_mac.patch

Nothing has implemented shouldIgnoreMouseEvent since #38404.

* chore: trim dead hunks from desktop_media_list.patch

The Update(callback, refresh_thumbnails) signature change is unused since
#50960 moved DesktopCapturer to StartUpdating().

* chore: trim dead hunks from allow_in-process_windows_to_have_different_web_prefs.patch

enable_websql has no reader (WebSQL is gone from Blink) and none of the
added fields use base::FilePath, so drop the field and the three file_path
includes/imports.

* chore: trim dead hunks from chore_restore_some_deprecated_wrapper_utility_in_gin.patch

gin::DeprecatedWrappable(Base), its Converter, internal::FromV8Impl and
gin/wrapper_info.cc duplicate what shell/common/gin_helper already defines
(including gin::DeprecatedWrapperInfo::From) and are not referenced; keep the
DeprecatedWrapperInfo struct, the per-isolate template maps and the internal
field setup that gin_helper relies on.

* chore: trim dead hunks from refactor_expose_file_system_access_blocklist.patch

Electron does not compile chrome_file_system_access_permission_context.cc,
so the #if 0 blocks in it did nothing; keep the header refactor.

* chore: trim dead hunks from feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch

The show-hidden plumbing has had no caller since #51704 (showHiddenFiles is
macOS/Windows only), and the portal file carried two unused includes, one of
them into electron/.

* chore: trim dead hunks from support_mixed_sandbox_with_zygote.patch

The RendererSandboxedProcessLauncherDelegateWin hunk was guarded by
USE_ZYGOTE, which is never set on Windows.

* chore: trim dead hunks from chore_grandfather_in_electron_views_and_delegates.patch

MenuBar and InspectableWebContentsView never construct the passkeys
themselves (RootView and DevToolsWindowDelegate do it for them).

* chore: trim dead hunks from web_contents.patch

The RenderWidgetHostViewBase forward declaration was unused.

* chore: trim dead hunks from boringssl feat_expose_several_extra_cipher_functions.patch

cipher.h already declares EVP_aes_256_cfb128.

* chore: trim dead hunks from the webrtc pipewire patch

The capturer_failed_ assignment inside the if duplicated the unconditional
one upstream added below it, and the description still listed two items that
no longer correspond to any hunk; what remains is the X11 fallback, so name
it that.

* chore: update patches

* chore: gn format build/args/all.gn

* Revert "chore: remove refactor_unfilter_unresponsive_events.patch"

This reverts commit 03a3bd1.

* Revert "chore: remove revert_remove_the_allowaggressivethrottlingwithwebsocket_feature.patch"

This reverts commit 9db932e.

* Revert "chore: remove disable_compositor_recycling.patch"

This reverts commit 9d53659.

* chore: update patches

* chore: make refactor_expose_file_system_access_blocklist.patch header-only

The earlier trim restored the .cc from Chromium trunk rather than the pinned
revision, which pulled unrelated upstream lines into the export.

* Revert "chore: remove fix_select_the_first_menu_item_when_opened_via_keyboard.patch"

This reverts commit 1fe5f4e.

* chore: keep first-menu-item selection for keyboard-opened menus off Windows

Upstream only auto-selects behind PlatformStyle::kAutoSelectFirstMenuItemFromKeyboard,
which is Windows-only, so keep the patch for the other views platforms and
skip it on Windows where upstream now handles it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merged/42-x-y PR was merged to the "42-x-y" branch. no-backport platform/macOS semver/patch backwards-compatible bug fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants