Repository navigation
macOS desktop crash hardening - #1777
Conversation
Made-with: Cursor
Made-with: Cursor
Made-with: Cursor
Made-with: Cursor
Made-with: Cursor
Made-with: Cursor
|
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. |
| Err(err) => { | ||
| tracing::warn!(error = %err, "No tokio runtime available; dropping background task"); | ||
| } |
There was a problem hiding this comment.
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.
| 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); | |
| } |
| 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"); | ||
| } | ||
| } | ||
| } |
There was a problem hiding this 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.
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.|
please re-review the pr bigman @greptileai |
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 incatch_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_unwindin 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_stateguards, bounded arithmetic, and bounds-checked slice copies all reduce crash surface without introducing new failure modes. The two flagged concerns (broadcatch_unwindscope and post-panic mutable state) are valid quality suggestions but do not represent regressions.crates/scap-screencapturekit/src/capture.rsandapps/desktop/src-tauri/src/lib.rs(run-event handler) for thecatch_unwindscope questions.Important Files Changed
.state()with.try_state()across window lifecycle handlers; extractedhandle_run_eventwrapped incatch_unwind; introducedspawn_on_runtimeguard helper. The blanketcatch_unwindaround the entire run-event handler is broader than necessary.schedule_macos_dock_visibility_syncdebounce helper using a generation counter; atomic ordering is Relaxed (flagged in a prior outside-diff review comment as needing AcqRel/Acquire on Apple Silicon).suppress_delegate_panicwrapper around every ObjC window delegate selector. Fallback values are sensible (NO for BOOL selectors, pass-through for presentation options).sync_macos_dock_visibilitycalls withschedule_macos_dock_visibility_sync, and threeset_activation_policycall-sites withprepare_macos_panel_window. Clean refactor.catch_unwind;mach_time_to_microsecondsrewritten 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).copy_from_slicefor audio buffer planes. Correct fix for the original panic.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] endComments Outside Diff (2)
apps/desktop/src-tauri/src/permissions.rs, line 499-506 (link)The generation counter uses
Relaxedfor both thefetch_add(caller) and theload(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 invokesync_macos_dock_visibility. For a debounce intended to coalesce multiple rapid calls into one,AcqRelon thefetch_addandAcquireon theloadwould correctly enforce the happens-before relationship.Prompt To Fix With AI
crates/camera-avfoundation/src/lib.rs, line 959-961 (link)u64::MAXproduces a wildly incorrect timestampWhen the computed microseconds exceeds
u64::MAX(≈ 584,542 years),.min(u64::MAX as u128) as u64silently saturates tou64::MAXand passes it upstream as a valid timestamp rather than returningDuration::ZEROor an error. Downstream code will interpret this as a ~584,542-year timestamp delta, likely corrupting any PTS-based synchronization logic. ReturningDuration::ZERO(matching the existingdenom == 0guard) would be safer.Prompt To Fix With AI
Prompt To Fix All With AI
Reviews (2): Last reviewed commit: "Merge branch 'main' into crashing-stuff" | Re-trigger Greptile