Skip to content

macOS desktop crash hardening - #1777

Merged
richiemcilroy merged 7 commits into
mainfrom
crashing-stuff
May 1, 2026
Merged

richiemcilroy merged 7 commits into
mainfrom
crashing-stuff

Conversation

@richiemcilroy

@richiemcilroy richiemcilroy commented May 1, 2026 •

Copy link
Copy Markdown
Member

Hardens desktop window lifecycle and macOS capture callbacks against panics and missing state during shutdown/cleanup. Also debounces macOS dock visibility sync and validates audio plane slices before copying.

Greptile Summary

This PR hardens the macOS desktop against panics and missing state during shutdown by replacing .state() with .try_state() across window lifecycle handlers, wrapping ObjC delegate callbacks and ScreenCaptureKit/AVFoundation output callbacks in catch_unwind, debouncing dock-visibility sync, and validating audio buffer slice bounds before copying.

The changes are well-targeted and the overall approach is sound; two P2 concerns are noted inline regarding the breadth of the catch_unwind in the Tauri run-event handler and the risk of operating on inconsistent mutable Obj-C state after a suppressed panic.

Confidence Score: 5/5

Safe to merge; all findings are P2 suggestions with no blocking logic errors on the changed paths.

Only P2 findings present. The hardening changes are additive and conservative — try_state guards, bounded arithmetic, and bounds-checked slice copies all reduce crash surface without introducing new failure modes. The two flagged concerns (broad catch_unwind scope and post-panic mutable state) are valid quality suggestions but do not represent regressions.

crates/scap-screencapturekit/src/capture.rs and apps/desktop/src-tauri/src/lib.rs (run-event handler) for the catch_unwind scope questions.

Important Files Changed

Filename Overview
apps/desktop/src-tauri/src/lib.rs Systematic replacement of .state() with .try_state() across window lifecycle handlers; extracted handle_run_event wrapped in catch_unwind; introduced spawn_on_runtime guard helper. The blanket catch_unwind around the entire run-event handler is broader than necessary.
apps/desktop/src-tauri/src/permissions.rs Added schedule_macos_dock_visibility_sync debounce helper using a generation counter; atomic ordering is Relaxed (flagged in a prior outside-diff review comment as needing AcqRel/Acquire on Apple Silicon).
apps/desktop/src-tauri/src/platform/macos/delegates.rs Introduced suppress_delegate_panic wrapper around every ObjC window delegate selector. Fallback values are sensible (NO for BOOL selectors, pass-through for presentation options).
apps/desktop/src-tauri/src/windows.rs Replaced four direct sync_macos_dock_visibility calls with schedule_macos_dock_visibility_sync, and three set_activation_policy call-sites with prepare_macos_panel_window. Clean refactor.
crates/camera-avfoundation/src/lib.rs Sample-buffer callback wrapped in catch_unwind; mach_time_to_microseconds rewritten to use u128 arithmetic with a saturating u64 cast (saturation to u64::MAX producing a wildly incorrect timestamp is flagged in the prior outside-diff review comment).
crates/recording/src/sources/screen_capture/macos.rs Added bounds-checked slice access and plane-size validation before copy_from_slice for audio buffer planes. Correct fix for the original panic.
crates/scap-screencapturekit/src/capture.rs Both ScreenCaptureKit callbacks wrapped in catch_unwind + AssertUnwindSafe. Mutable Obj-C delegate state after a suppressed panic may be inconsistent for subsequent frames.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Tauri RunEvent] --> B[catch_unwind AssertUnwindSafe]
    B --> C{handle_run_event}
    C -->|Reopen| D[show/focus window]
    C -->|ExitRequested| E[try_state AppExitState\nprevent_exit + spawn request_app_exit]
    C -->|Exit| F[try_state AppExitState\nspawn cleanup_app_resources_for_exit]
    C -->|panic| G[log to tracing + sentry\ncontinue processing]

    subgraph Window CloseRequested
        H[try_state CameraWindowCloseGate] -->|None or deny| I[prevent_close + spawn_on_runtime cleanup]
        J[try_state ArcLock App] -->|None| K[warn + return]
        J -->|Some| L[check is_recording]
    end

    subgraph macOS ObjC Delegates
        M[suppress_delegate_panic] --> N{delegate fn}
        N -->|panic| O[log error\nreturn fallback value]
        N -->|ok| P[forward to super_delegate]
    end

    subgraph Capture Callbacks
        Q[did_output_sample_buf] --> R[catch_unwind AssertUnwindSafe]
        R -->|panic| S[warn + skip frame]
        R -->|ok| T[process frame / invoke cb]
    end

    subgraph Audio Buffer Validation
        U[buf_list buffers 0] --> V{slice.get start..end}
        V -->|None| W[warn + drop chunk]
        V -->|Some| X{dest.len == src.len}
        X -->|no| W
        X -->|yes| Y[copy_from_slice]
    end
Loading

Comments Outside Diff (2)

  1. apps/desktop/src-tauri/src/permissions.rs, line 499-506 (link)

    P2 Relaxed ordering insufficient for debounce correctness on ARM

    The generation counter uses Relaxed for both the fetch_add (caller) and the load (spawned task). On weakly-ordered architectures like Apple Silicon, there is no guarantee the spawned task will observe the latest counter value written by a concurrent caller — two rapid callers could each observe a stale generation and both proceed to invoke sync_macos_dock_visibility. For a debounce intended to coalesce multiple rapid calls into one, AcqRel on the fetch_add and Acquire on the load would correctly enforce the happens-before relationship.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: apps/desktop/src-tauri/src/permissions.rs
    Line: 499-506
    
    Comment:
    **Relaxed ordering insufficient for debounce correctness on ARM**
    
    The generation counter uses `Relaxed` for both the `fetch_add` (caller) and the `load` (spawned task). On weakly-ordered architectures like Apple Silicon, there is no guarantee the spawned task will observe the latest counter value written by a concurrent caller — two rapid callers could each observe a stale generation and both proceed to invoke `sync_macos_dock_visibility`. For a debounce intended to coalesce multiple rapid calls into one, `AcqRel` on the `fetch_add` and `Acquire` on the `load` would correctly enforce the happens-before relationship.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
  2. crates/camera-avfoundation/src/lib.rs, line 959-961 (link)

    P2 Clamping to u64::MAX produces a wildly incorrect timestamp

    When the computed microseconds exceeds u64::MAX (≈ 584,542 years), .min(u64::MAX as u128) as u64 silently saturates to u64::MAX and passes it upstream as a valid timestamp rather than returning Duration::ZERO or an error. Downstream code will interpret this as a ~584,542-year timestamp delta, likely corrupting any PTS-based synchronization logic. Returning Duration::ZERO (matching the existing denom == 0 guard) would be safer.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: crates/camera-avfoundation/src/lib.rs
    Line: 959-961
    
    Comment:
    **Clamping to `u64::MAX` produces a wildly incorrect timestamp**
    
    When the computed microseconds exceeds `u64::MAX` (≈ 584,542 years), `.min(u64::MAX as u128) as u64` silently saturates to `u64::MAX` and passes it upstream as a valid timestamp rather than returning `Duration::ZERO` or an error. Downstream code will interpret this as a ~584,542-year timestamp delta, likely corrupting any PTS-based synchronization logic. Returning `Duration::ZERO` (matching the existing `denom == 0` guard) would be safer.
    
    
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
crates/scap-screencapturekit/src/capture.rs:21-40
**Mutable delegate state may be inconsistent after a suppressed panic**

`AssertUnwindSafe` tells the compiler "trust me, this is safe to unwind through", but it doesn't actually make the invariant true. If `(cb)(frame)` panics mid-execution, the closure unwinds while `self.inner_mut()` holds a live mutable borrow on the underlying `CapturerCallbacksInner`. For Obj-C-bridged types that use raw-pointer interior mutability, the object's internal state can be left partially written. Every subsequent frame callback then operates on that inconsistent state, potentially producing corrupted frames or a secondary panic. At minimum, consider setting a `poisoned` flag on the `CapturerCallbacks` after a caught panic and skipping future callbacks (returning early) until the stream is restarted.

### Issue 2 of 2
apps/desktop/src-tauri/src/lib.rs:4433-4446
**`catch_unwind` + `AssertUnwindSafe` on the Tauri event loop is broad**

Wrapping all of `handle_run_event` in `catch_unwind(AssertUnwindSafe(...))` suppresses any panic, including ones that indicate corrupted Tauri-internal state (e.g., a partially-updated window table). After such a panic the application continues processing future run-events against that corrupted state rather than crashing cleanly and giving the user a clear error report. Consider scoping the unwind boundary to the narrow call-sites actually known to panic (as was done in `delegates.rs`), rather than using a blanket catch over the entire event dispatch path.

Reviews (2): Last reviewed commit: "Merge branch 'main' into crashing-stuff" | Re-trigger Greptile

@polarityinc

polarityinc Bot commented May 1, 2026

Copy link
Copy Markdown

Paragon Review Skipped

Hi @richiemcilroy! Your Polarity credit balance is insufficient to complete this review.

Please visit https://app.paragon.run to finish your review.

Comment on lines +4529 to +4531
Err(err) => {
tracing::warn!(error = %err, "No tokio runtime available; dropping background task");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

spawn_on_runtime currently drops the task if it’s called from a thread without a current Tokio runtime (which can happen from Tauri event handlers). Consider falling back to tauri::async_runtime::spawn so cleanup paths still run.

Suggested change
Err(err) => {
tracing::warn!(error = %err, "No tokio runtime available; dropping background task");
}
Err(err) => {
tracing::warn!(error = %err, "No tokio runtime available; spawning on tauri runtime");
tauri::async_runtime::spawn(future);
}

Comment on lines +4521 to 4533
fn spawn_on_runtime<F>(future: F)
where
F: Future<Output = ()> + Send + 'static,
{
match tokio::runtime::Handle::try_current() {
Ok(handle) => {
handle.spawn(future);
}
Err(err) => {
tracing::warn!(error = %err, "No tokio runtime available; dropping background task");
}
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Silently dropped cleanup tasks could leave resources unreleased

spawn_on_runtime logs a warning and silently drops the future when no Tokio runtime is found. Several call-sites pass critical cleanup futures (camera feeds, mic feeds, cleanup_app_resources_for_exit, EditorInstances::remove, etc.). If called during teardown when the runtime has already been shut down, those cleanup paths are silently skipped rather than executed synchronously or deferred. Consider documenting that callers relying on cleanup must not use this helper, or alternatively provide a synchronous fallback for cleanup-critical tasks.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src-tauri/src/lib.rs
Line: 4521-4533

Comment:
**Silently dropped cleanup tasks could leave resources unreleased**

`spawn_on_runtime` logs a warning and silently drops the future when no Tokio runtime is found. Several call-sites pass critical cleanup futures (camera feeds, mic feeds, `cleanup_app_resources_for_exit`, `EditorInstances::remove`, etc.). If called during teardown when the runtime has already been shut down, those cleanup paths are silently skipped rather than executed synchronously or deferred. Consider documenting that callers relying on cleanup must not use this helper, or alternatively provide a synchronous fallback for cleanup-critical tasks.

How can I resolve this? If you propose a fix, please make it concise.

@richiemcilroy

Copy link
Copy Markdown
Member Author

please re-review the pr bigman @greptileai

@richiemcilroy
richiemcilroy merged commit be0a832 into main May 1, 2026
16 checks passed
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