Repository navigation
Add SaveToGallery option to MediaPickerOptions for capture operations - #34641
Conversation
|
@copilot this should target the net11.0 branch. Update the target and rebase on that. |
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 34641Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 34641" |
Done — I merged Warning Firewall rules blocked me from connecting to one or more addresses (expand for details)I tried to connect to the following addresses, but was blocked by firewall rules:
If you need me to access, download, or install something from one of these locations, you can either:
|
|
Will probably have a conflict with #34287 when that is merged up to the net11.0 branch. Afterwards I think this will be nice to have for .NET 11. |
There was a problem hiding this comment.
Pull request overview
Adds an opt-in SaveToGallery flag to MediaPickerOptions so capture operations can avoid requesting gallery/photo-library permissions unless the app explicitly asks to save captured media to the user’s gallery.
Changes:
- Introduces
MediaPickerOptions.SaveToGallery(defaultfalse) with platform behavior documented in XML docs. - Updates iOS and Android capture flows to conditionally request permissions and save captured media to the gallery/library when enabled.
- Updates PublicAPI unshipped files and the Essentials sample UI to expose a “Save to Gallery” toggle.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| src/Essentials/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the netstandard API surface. |
| src/Essentials/src/PublicAPI/net/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the net API surface. |
| src/Essentials/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the Windows API surface. |
| src/Essentials/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the Tizen API surface. |
| src/Essentials/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the MacCatalyst API surface. |
| src/Essentials/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the iOS API surface. |
| src/Essentials/src/PublicAPI/net-android/PublicAPI.Unshipped.txt | Adds SaveToGallery getter/setter to the Android API surface. |
| src/Essentials/src/MediaPicker/MediaPicker.shared.cs | Defines and documents the new SaveToGallery option on MediaPickerOptions. |
| src/Essentials/src/MediaPicker/MediaPicker.ios.cs | Gates PhotosAddOnly permission and saves captured media to the photo library only when requested. |
| src/Essentials/src/MediaPicker/MediaPicker.android.cs | Gates StorageWrite permission (<29) and saves captured media to MediaStore when requested. |
| src/Essentials/samples/Samples/ViewModel/MediaPickerViewModel.cs | Adds a viewmodel toggle and wires SaveToGallery into capture calls. |
| src/Essentials/samples/Samples/View/MediaPickerPage.xaml | Adds a UI switch to control “Save to Gallery (Capture)”. |
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
… implementations Add a new `SaveToGallery` boolean property (default: false) to `MediaPickerOptions`. When true during capture operations, the captured image/video is saved to the device photo gallery and the necessary permissions are requested. iOS/macOS: Uses PHPhotoLibrary.PerformChangesAsync with PHAssetChangeRequest. Requests PhotosAddOnly permission only when SaveToGallery is true. Android: Uses MediaStore ContentResolver insert for API 29+. Requests StorageWrite permission only when SaveToGallery is true on older API levels. Windows/Tizen: Property is ignored (not supported, documented in API docs). Fixes #34246 Co-authored-by: jfversluis <939291+jfversluis@users.noreply.github.com> Agent-Logs-Url: https://github.com/dotnet/maui/sessions/31e2becf-8873-4347-a7a7-bb89d6e3647f
…cleanup, unique temp paths - Use file extension for MIME type detection instead of hardcoded values - Clean up pending MediaStore entries when OutputStream is null on Android - Use unique temp file names in iOS to avoid collisions - Add XML doc comments to save methods - Fix nullable annotation in non-nullable context Co-authored-by: jfversluis <939291+jfversluis@users.noreply.github.com> Agent-Logs-Url: https://github.com/dotnet/maui/sessions/31e2becf-8873-4347-a7a7-bb89d6e3647f
Co-authored-by: jfversluis <939291+jfversluis@users.noreply.github.com> Agent-Logs-Url: https://github.com/dotnet/maui/sessions/28acf19d-68b5-463b-9de7-4e822741ce9a
Fix the Android capture save path, harden gallery save cleanup, surface opt-in save failures, and ensure iOS temporary photo-library files are cleaned up on failure.\n\nCo-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Update the SaveToGallery XML docs to reference Mac Catalyst only and remove duplicate PublicAPI entries left after rebasing onto net11.0. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
e672776 to
ea4e1f1
Compare
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 2 findings
See inline comments for details.
| // Save to gallery if requested | ||
| if (capturePath is not null && options?.SaveToGallery == true) | ||
| { | ||
| await SaveToGalleryAsync(capturePath, photo); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
SaveToGalleryAsync runs after capture has already produced capturePath, but any gallery-publish exception (IOException from MediaStore insert/write/publish, or the cleanup AggregateException) escapes the surrounding try because only OperationCanceledException is caught. On low storage or OEM MediaStore failure, callers who explicitly opted into SaveToGallery lose the successfully captured FileResult and cannot recover the cache file. Consider catching gallery-save failures separately and still returning the captured result (or exposing a distinct save-to-gallery failure signal).
| // Save captured media to the photo gallery if requested | ||
| if (!pickExisting && result is not null && options?.SaveToGallery == true) | ||
| { | ||
| await SaveToPhotoLibraryAsync(result); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
SaveToPhotoLibraryAsync is awaited after result has already been created, but NSErrorException/InvalidOperationException from PHPhotoLibrary.PerformChanges will escape PhotoAsync and prevent the caller from receiving the captured FileResult. This turns a post-capture photo-library publishing failure into an overall capture failure, matching the Android failure mode. Consider isolating gallery-save errors from the primary capture result so the captured file can still be returned.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@copilot — new AI review results are available based on this last commit:
ea4e1f1. To request a fresh review after new comments or commits, comment/review rerun.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ INCONCLUSIVE
Platform: ANDROID
⚠️ verify-tests-fail.ps1exited before writing a verification report. Diagnostics below.
Exit code: 3
Likely cause:
- Test detection failed — no runnable tests were found in the PR diff.
Gate output log (last 60 lines)
📁 Output directory: CustomAgentLogsTmp/PRState/34641/PRAgent/gate/verify-tests-fail
🔍 Detecting base branch and merge point...
No PR detected, scanning remote branches for closest base...
✅ Base branch: net11.0 (via closest-merge-base)
✅ Merge base commit: 9ee0adb3
(1 commits ahead of net11.0)
╔═══════════════════════════════════════════════════════════╗
║ FULL VERIFICATION MODE ║
╠═══════════════════════════════════════════════════════════╣
║ Fix files detected - will verify: ║
║ 1. Tests FAIL without fix ║
║ 2. Tests PASS with fix ║
╚═══════════════════════════════════════════════════════════╝
✅ Fix files (12):
- src/Essentials/samples/Samples/View/MediaPickerPage.xaml
- src/Essentials/samples/Samples/ViewModel/MediaPickerViewModel.cs
- src/Essentials/src/MediaPicker/MediaPicker.android.cs
- src/Essentials/src/MediaPicker/MediaPicker.ios.cs
- src/Essentials/src/MediaPicker/MediaPicker.shared.cs
- src/Essentials/src/PublicAPI/net-android/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/net-ios/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/net-maccatalyst/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/net-tizen/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/net-windows/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/net/PublicAPI.Unshipped.txt
- src/Essentials/src/PublicAPI/netstandard/PublicAPI.Unshipped.txt
🔍 Auto-detecting test filter from changed test files...
⚠️ No tests detected in this PR.
Searched for: UI tests, unit tests, XAML tests, device tests
Consider adding tests via write-tests-agent.
📱 UI Tests — Essentials
Detected UI test categories: Essentials
⏭️ Deep UI tests — 0 passed, 0 failed across 1 category on platform-pool agent (replaces in-process counts above). 1 category reported 0 tests.
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Essentials |
0 tests | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
📋 Pre-Flight — Context & Validation
Issue: #34246 - iOS MediaPicker CapturePhotoAsync without "PhotosAddOnly" permission
PR: #34641 - Add SaveToGallery option to MediaPickerOptions for capture operations
Platforms Affected: iOS, MacCatalyst, Android; documented no-op on Windows/Tizen/netstandard
Files Changed: 10 implementation/API/sample, 0 test
Key Findings
- Original issue reports
CapturePhotoAsyncon iOS requestingPhotosAddOnlyeven when the app only needs the captured file and does not save to Photos. - PR adds an opt-in
MediaPickerOptions.SaveToGalleryAPI, removes unconditional iOS photo-library-add permission from plain capture, and implements opt-in gallery publishing on iOS/MacCatalyst and Android. - No regression tests were added; prior gate was inconclusive due build/environment failure and must not be treated as a code failure.
ghmetadata/check queries were blocked by missing authentication, so pre-flight used local squashed PR diff plus public GitHub API context.
Code Review Summary
Verdict: NEEDS_DISCUSSION
Confidence: low
Errors: 0 | Warnings: 1 | Suggestions: 0
Key code review findings:
- ⚠ Android
MediaPicker.android.cs:180and iOSMediaPicker.ios.cs:175now throw if gallery publishing fails after capture succeeds; this is defensible for explicit opt-in but means callers lose the capturedFileResultand needs semantic confirmation/documentation. - Prior ❌ findings about Android pending MediaStore rows, stream disposal ordering, silent failures, and iOS temp-file cleanup appear addressed in the current diff.
- Failure mode: default/null options do not request gallery permissions;
SaveToGallery=truecan fail before or after capture depending on permission/gallery write result. - Blast radius: opt-in capture paths only; no startup or static/shared-state impact.
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| PR | PR #34641 | Add SaveToGallery option and opt-in platform gallery publishing for capture operations |
MediaPicker.android.cs, MediaPicker.ios.cs, MediaPicker.shared.cs, PublicAPI, sample |
Original PR; prior gate could not build/run in environment |
🔬 Code Review — Deep Analysis
Code Review — PR #34641
Independent Assessment
What this changes: Adds MediaPickerOptions.SaveToGallery; Android/iOS save captured media to gallery only when opted in.
Inferred motivation: Avoid unconditional iOS PhotosAddOnly permission while enabling explicit gallery save.
Reconciliation with PR Narrative
Author claims: Conditional permission/save support; unsupported platforms ignore property.
Agreement/disagreement: Matches implementation and API docs.
Prior Review Reconciliation
| Prior ❌ Error Finding | Source | Status | Evidence |
|---|---|---|---|
Undefined captureResult |
MauiBot | ✅ Fixed | Current Android uses capturePath at lines 178-184. |
MediaStore IsPending cleared before stream disposal |
MauiBot/kubaflo | ✅ Fixed | Stream scope ends before update at lines 604-616. |
| MediaStore orphan on copy failure | MauiBot/kubaflo | ✅ Fixed | Catch deletes inserted URI at lines 618-629. |
| Silent gallery-save failure | MauiBot/kubaflo | ✅ Fixed | Exceptions now propagate from Android/iOS helpers. |
| iOS temp file leak | MauiBot/kubaflo | ✅ Fixed | Cleanup is in finally at lines 526-529. |
Blast Radius Assessment
- Runs for all instances: No — only capture calls with
SaveToGallery=true. - Startup impact: No.
- Static/shared state: No new static state.
CI Status
- Required-check result: undetermined via
gh(gh auth loginrequired); public check-runs show pending/queued checks. - Classification: undetermined/pending.
- Action taken: capped confidence low; no LGTM.
Findings
No ❌ Error findings found.
⚠️ Warning — Gallery-save failure semantics need confirmation
Android MediaPicker.android.cs:180 and iOS MediaPicker.ios.cs:175 now throw if gallery publishing fails after capture succeeds. That is defensible for explicit opt-in, but it means callers lose the captured FileResult. Confirm this is intended API behavior or document it.
Failure-Mode Probing
- Default/null options: unchanged behavior; no gallery save or extra permissions.
- Permission denied: fails before capture when opt-in requires permission.
- Gallery write failure after capture: exception propagates; captured temp result is not returned.
- Android MediaStore partial write: pending row is deleted on failure.
Verdict: NEEDS_DISCUSSION
Confidence: low
Summary: Code issues from prior reviews appear fixed, and the implementation is scoped to opt-in capture paths. CI is still undetermined/pending, so this cannot be LGTM yet.
🛠️ Fix — Analysis & Comparison
Fix Candidates
| # | Source | Approach | Test Result | Files Changed | Notes |
|---|---|---|---|---|---|
| 1 | try-fix-1 | Minimal iOS permission-only fix: drop the new SaveToGallery API/Android publishing and keep only capture without PhotosAddOnly |
12 files reverted/adjusted | Lower risk for #34246 only, but incomplete for PR's expanded gallery-save feature | |
| 2 | try-fix-2 | Keep SaveToGallery, but make Android gallery publish best-effort and return captured FileResult if publish fails |
src/Essentials/src/MediaPicker/MediaPicker.android.cs |
Rejected by self-review: reintroduces silent explicit opt-in failure | |
| 3 | try-fix-3 | Keep fatal failure but wrap Android gallery-publish exception with captured-file recovery metadata | src/Essentials/src/MediaPicker/MediaPicker.android.cs |
Best alternative for failure semantics, but unverified and uses weakly typed Exception.Data |
|
| PR | PR #34641 | Add SaveToGallery option and opt-in Android/iOS gallery publishing; gallery publish failures propagate |
12 files | Original PR; prior review issues appear fixed, but gate/build environment could not verify |
Cross-Pollination
| Model | Round | New Ideas? | Details |
|---|---|---|---|
| gpt-5.5 / maui-expert-reviewer | 1 | Yes | Proposed minimal permission-only fix, Android direct-to-MediaStore target, and separate gallery-publish API/service. |
| gpt-5.5 / maui-expert-reviewer | 2 | Yes | After try-fix-1 environment blocker, proposed best-effort Android gallery publishing to preserve captured FileResult. |
| gpt-5.5 / maui-expert-reviewer | 3 | Yes | After try-fix-2 self-review failure, proposed explicit captured-but-gallery-save-failed exception with recovery metadata. |
| Orchestrator | 4 | No | Remaining distinct idea, a separate public gallery-publish API/service, is a larger new API design rather than a surgical alternative for this PR and would need API review; direct-to-MediaStore capture target is high risk with camera EXTRA_OUTPUT, processing, and recovery semantics. |
Exhausted: Yes — no candidate passed tests, and remaining ideas require larger API design or risky Android capture-path rewrites.
Selected Fix: PR #34641 — no alternative is demonstrably better. Candidate #3 is the only potentially useful refinement, but it remains unverified and adds weakly typed recovery semantics rather than improving the core fix.
Environment/Test Notes
ghwas unavailable because authentication is missing, so CI/check context is undetermined.- Android candidate validation was blocked.
dotnet build src/Essentials/test/DeviceTests/Essentials.DeviceTests.csproj -f net11.0-android -p:IncludeAndroidTargetFrameworks=true --no-restorefailed immediately withMaui.InTree.targetsreporting build tasks not built. - The one setup attempt,
dotnet build Microsoft.Maui.BuildTasks.slnf --no-restore --nologo, failed due missingproject.assets.jsonfiles and missing .NET Framework 4.7.2 reference assemblies on Linux. - Per instructions, the environment blocker was recorded and the loop continued with partial results instead of stopping.
Per-Candidate Narrative
See:
CustomAgentLogsTmp/PRState/34641/PRAgent/try-fix-1/content.mdCustomAgentLogsTmp/PRState/34641/PRAgent/try-fix-2/content.mdCustomAgentLogsTmp/PRState/34641/PRAgent/try-fix-3/content.md
📝 Recommended PR Title & Description
Assessment: ✏️ Recommend updating — the current description is mostly accurate but overstates macOS coverage, includes process/boilerplate text, and the title can be more searchable with the component prefix.
Recommended title
[Essentials] MediaPicker: Add opt-in SaveToGallery for capture operations
Recommended description
### Description of Change
Adds `MediaPickerOptions.SaveToGallery` as an opt-in flag for media capture operations. The default is `false`, so capture no longer requests gallery/photo-library write permissions unless the caller explicitly asks to save the captured media to the device gallery.
- [x] Add `SaveToGallery` property to `MediaPickerOptions` with default `false`
- [x] iOS: request `PhotosAddOnly` permission and save to the photo library only when `SaveToGallery=true`
- [x] Android: request `StorageWrite` on API < 29 only when `SaveToGallery=true`; use `MediaStore` insert on API 29+
- [x] MacCatalyst: uses the shared `.ios.cs` code path
- [x] Windows: documented as not supported in API docs; property is ignored
- [x] Tizen/netstandard: property is ignored; no save-to-gallery support
- [x] Update all `PublicAPI.Unshipped.txt` files with the new API entry
- [x] Update the Essentials sample with a `SaveToGallery` toggle for capture operations
Key behavior:
- `CapturePhotoAsync` / `CaptureVideoAsync` without `SaveToGallery` keep returning the captured file without requesting photo-library/gallery-write permissions.
- `SaveToGallery=true` is capture-only and does not affect pick operations.
- Gallery-publish failures are surfaced to the caller rather than silently ignored.
### Issues Fixed
Fixes #34246
🏁 Report — Final Recommendation
Comparative Analysis — PR #34641
Candidate ranking
| Rank | Candidate | Regression result | Code-review result | Assessment |
|---|---|---|---|---|
| 1 | pr |
2 warning-level findings, no unresolved error-level findings | Best balance: implements the requested opt-in API across Android/iOS/MacCatalyst, fixes the original iOS permission issue, keeps explicit SaveToGallery=true failures visible, and preserves prior MediaStore/temp-file cleanup fixes. |
|
| 2 | try-fix-3 |
No self-review findings | Potentially improves Android failure diagnostics by wrapping gallery-save failure with captured-path metadata, but it only addresses Android, leaves the iOS/MacCatalyst post-capture failure semantics unchanged, and uses weakly typed Exception.Data. |
|
| 3 | pr-plus-reviewer |
Addresses expert warning by returning captured result | Applies the expert reviewer feedback on both Android and iOS/MacCatalyst, but does so by swallowing explicit gallery-publish failures into Debug-only output. That is a behavior tradeoff, not a clear correctness improvement. | |
| 4 | try-fix-1 |
No self-review findings | Lowest implementation risk for the narrow iOS permission bug, but it removes the PR's new SaveToGallery API and Android/iOS gallery-save feature, so it is incomplete for the PR's intended scope. |
|
| 5 | try-fix-2 |
❌ Self-review major finding | Rejected because it silently ignores Android gallery-save failure for an explicit opt-in operation and only addresses Android. |
Winning candidate: pr
The raw PR fix wins. It fixes the original issue by making iOS PhotosAddOnly permission opt-in, implements the new SaveToGallery API consistently across the intended platforms, and avoids the silent-failure behavior introduced by try-fix-2 and pr-plus-reviewer.
The remaining concern is semantic rather than a proven correctness bug: when SaveToGallery=true, a gallery-publish failure after capture causes the capture API to throw instead of returning the captured file. Because this is an explicit opt-in operation and all alternatives are unverified, the safest winning candidate is the PR as submitted, with the expert warning left for maintainer judgment.
Regression-test rule
No candidate passed regression tests. No candidate has a confirmed regression-test failure either; all validation outcomes were blocked or inconclusive due the local MAUI build-task environment. Therefore the ranking is based on code correctness, completeness, and review findings rather than pass/fail test precedence.
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
SaveToGalleryproperty toMediaPickerOptions(defaultfalse)PhotosAddOnlypermission and save to photo library only whenSaveToGallery=trueStorageWrite(API < 29) /MediaStoreinsert (API 29+) only whenSaveToGallery=true.ios.csfile)PublicAPI.Unshipped.txtfiles with new API entrySaveToGallerytogglenet11.0branch into PR — PR base should be changed tonet11.0Fixes #34246
⌨️ Start Copilot coding agent tasks without leaving your editor — available in VS Code, Visual Studio, JetBrains IDEs and Eclipse.