Repository navigation
[main] [iOS] Fix MediaPicker throwing UIKitThreadAccessException when picking 2+ items - #38488
Conversation
…g 2+ items (#37879) ### Description of Change `PickerResultsToMediaFiles` reads `PHPickerResult.ItemProvider` — a UIKit call guarded by `UIApplication.EnsureUIThread()` — inside a loop that awaits with `ConfigureAwait(false)`: ```csharp foreach (var file in results) { fileResult = new PHPickerFileResult(file.ItemProvider); // UIKit call await fileResult.LoadFileRepresentationAsync().ConfigureAwait(false); fileResults.Add(fileResult); fileResult = null; } ``` The first iteration runs on the main thread, because the picker delegate invokes it from the dismissal completion. But `LoadFileRepresentationAsync` completes through a `TaskCompletionSource<bool>` created with `TaskCreationOptions.RunContinuationsAsynchronously`, so the continuation never runs inline. From the second iteration onwards the read happens on the thread pool and throws `UIKitThreadAccessException`. This makes it deterministic rather than a race — picking 2 or more items always fails, picking 1 always works. This is a regression from #35805, which replaced the previous `Select(...).ToList()` materialization — where every `ItemProvider` was read before the first await — with the loop above. **Change:** read every `ItemProvider` up front, before the first await, then load the file representations in a second loop. `NSItemProvider` is a Foundation type with no UI-thread guard, so holding the providers across the awaits is safe. This preserves what #35805 set out to fix: `FullPath` is assigned in the `PHPickerFileResult` constructor via `CreateTemporaryFilePath`, not by the load, so it still points at a real temp-backed file. Ordering, image processing and video handling are untouched. It also fixes a leak in the error path: previously, when a load threw, results already constructed by earlier iterations were disposed, but ones constructed later were not. Results are now only added to the returned list once loaded, and any left unloaded by a failure are disposed separately. ### Verification - `dotnet format src/Essentials/src/Essentials.csproj --no-restore --include src/Essentials/src/MediaPicker/MediaPicker.ios.cs --verify-no-changes` — clean - `dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=false` — 0 warnings, 0 errors - `dotnet build src/Essentials/src/Essentials.csproj -f net10.0-maccatalyst26.0 --no-restore /p:EnableSourceLink=false /p:UseSharedCompilation=false` — 0 warnings, 0 errors - Ran on the iOS 26.4 simulator (iPhone 17) by dropping the built `Microsoft.Maui.Essentials.dll` into the repro app from the issue, so the real fixed code was exercised through `MediaPicker.Default.PickPhotosAsync`: - picking 3 photos no longer throws - every returned `FileResult.FullPath` exists, is non-empty, and `File.Copy(result.FullPath, ...)` succeeds — i.e. the #32832 scenario that #35805 fixed still works No unit test is included: the affected path needs a real `PHPickerResult`, which cannot be constructed in `Essentials.UnitTests`. Happy to add coverage if you can point me at a suitable seam. ### Issues Fixed Fixes #37878
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@github-actions[bot] — new AI review results are available based on commit
9b51655.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ SKIPPED
No tests were detected in this PR.
Recommendation: Add tests to verify the fix using the write-tests-agent.
📋 Pre-Flight — Context & Validation
PR #38488 Pre-Flight
Context
- Title:
[iOS] Fix MediaPicker throwing UIKitThreadAccessException when picking 2+ items (#37879) - Linked issue: #37878,
[iOS] MediaPicker.PickPhotosAsync throws UIKitThreadAccessException when 2 or more items are selected (regression in 10.0.100) - Branch/base: local materialized branch
pr-review-38488; merge base3823473d7d581aed7a51a9ab3d56973e12b4d1dc - PR commit:
b007cae26090c693b4320d6d75d27c63688a01e4 - Platform: iOS
- Gate: skipped because the PR adds no tests. Do not rerun the gate and do not modify
gate/content.md.
Problem
PickerResultsToMediaFiles starts on the iOS main thread, reads
PHPickerResult.ItemProvider, then awaits
PHPickerFileResult.LoadFileRepresentationAsync() with
ConfigureAwait(false). That load completes asynchronously, so the next loop
iteration resumes on a thread-pool thread. Reading the second
PHPickerResult.ItemProvider then deterministically throws
UIKitThreadAccessException. One selected item does not reach a second
property read and therefore succeeds.
The regression was introduced by #35805, which replaced eager provider
materialization with a sequential construct/load loop in order to ensure each
returned PHPickerFileResult.FullPath refers to a real temporary file.
Existing PR Approach
The PR changes only
src/Essentials/src/MediaPicker/MediaPicker.ios.cs. It constructs every
PHPickerFileResult before the first await, then loads each representation
sequentially. It adds separate cleanup for constructor failure and load
failure, disposing both loaded and not-yet-loaded wrappers.
Any candidate must use a different mechanism, preserve result ordering and
the #35805 FullPath behavior, and dispose every constructed
PHPickerFileResult on partial failure.
Validation Contract
No primary automated test was detected, and the request provides no additional
mandatory regression-test filters. Do not invent or run a full suite. Use only
this narrow iOS compile check:
dotnet build src/Essentials/src/Essentials.csproj -f net10.0-ios26.0 --no-restore /p:BuildIpa=false /p:EnableSourceLink=false /p:UseSharedCompilation=falseCompilation alone does not prove the behavioral fix. If the command succeeds
but the real two-photo picker flow cannot run, record the candidate as
Blocked, not Pass, and state that simulator/device interaction is missing.
Each attempt gets one implementation/check pass and at most one focused
correction/recheck. It must restore through
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore.
Environment
gh is unauthenticated, so public GitHub API/patch data and the materialized
local branch were used. The worktree contains many pre-existing changes under
.github/ and eng/; they are unrelated and must not be altered or reverted.
🔬 Code Review — Deep Analysis
Code Review — PR #38488
Independent Assessment
What this changes: PickerResultsToMediaFiles now constructs every
PHPickerFileResult before its first asynchronous load, then loads the
representations sequentially. This keeps every UIKit-backed
PHPickerResult.ItemProvider access on the initiating thread while preserving
result order and the temporary-file behavior introduced by #35805. Failure
cleanup now disposes both loaded and not-yet-loaded wrappers.
Inferred motivation: After the first ConfigureAwait(false), the old loop
could resume on a worker thread and access the next ItemProvider, causing
UIKitThreadAccessException whenever a selection contained at least two
items.
Reconciliation with PR Narrative
The submitted change agrees with the stated iOS MediaPicker backport and
addresses the described multi-selection failure mechanism directly.
Prior Review Reconciliation
No prior error-level findings were found in top-level reviews, inline review
comments, or PR issue comments. The existing human review contains no
unresolved code concern.
Blast Radius Assessment
- Runs for all instances: No. The changed path is limited to iOS 14+
PHPicker result processing for multi-select photo/video operations. - Startup impact: None; this executes only after picker completion.
- Static/shared state: None added.
- Ordering and cleanup: Input order remains stable. If construction or
loading fails, every wrapper constructed so far is disposed.
CI Status
Required-check status was pending or otherwise undetermined during review.
Anonymous check-run data showed jobs still in progress and two macOS build
jobs reporting failure, without enough completed evidence to classify the
overall result. Confidence is therefore capped at low.
Findings
⚠️ Warning — No regression test covers multi-item picker processing
src/Essentials/src/MediaPicker/MediaPicker.ios.cs:266
The PR changes thread-affinity sequencing but adds no test that exercises the
two-or-more-item path and demonstrates that processing continues after the
first asynchronous load without a UIKitThreadAccessException. The Gate was
accordingly skipped because no tests were detected.
Failure-Mode Probing
- Empty or null results still return through the existing guard.
- Single-item and multi-item results preserve their original order.
- No subscriptions, handler lifecycle state, or shared state are introduced.
- A construction failure disposes all preceding wrappers; a load failure
disposes both the loaded prefix and the unprocessed suffix. - The code no longer performs any UIKit-backed
ItemProvideraccess after the
first await.
External Output Contract
Not applicable.
Verdict: NEEDS_DISCUSSION
Confidence: low
Summary: The submitted implementation is mechanically sound for the
identified thread-affinity bug and improves partial-failure cleanup. It is not
eligible for an unconditional approval from this review because required CI
was not resolved and the PR contains no regression test for the affected
multi-selection flow.
🛠️ Try-Fix — Analysis & Comparison
PR #38488 Try-Fix Aggregate
Candidate 1 — Provider Snapshot
Model: gpt-5.3-codex
Approach: Read all UIKit-backed ItemProvider properties into an
NSItemProvider[] before the first await, then lazily construct and load one
PHPickerFileResult at a time. Unlike the PR, it does not eagerly construct
all wrappers.
Result: Fail
The mandatory narrow iOS build failed with NETSDK1004 because
artifacts/obj/Essentials/project.assets.json is missing while the command
requires --no-restore. No further command was permitted. The mechanism was
not behaviorally exercised; inline expert self-review reported zero findings,
and restore completed with Restored True.
Full narrative and diff:
CustomAgentLogsTmp/PRState/38488/PRAgent/try-fix-1/content.md
Candidate 2 — Per-Access Main-Thread Dispatch
Model: gpt-5.6-sol
Approach: Keep sequential wrapper construction/loading, but explicitly
marshal every UIKit-backed ItemProvider getter to the main thread at the
point of use. Unlike both the PR and candidate 1, this performs no eager
wrapper or provider collection.
Result: Blocked
Baseline establishment rejected the pre-existing unrelated dirty-worktree
state and created no modification allow-list. No source edit or verification
command was permitted, so the candidate has an empty diff and no compile or
behavioral evidence. Inline expert self-review reported zero findings, and
the required restore command reported the expected no-state result
(Restored False).
Full narrative and diff:
CustomAgentLogsTmp/PRState/38488/PRAgent/try-fix-2/content.md
Aggregate Outcome
Two candidates were attempted, in order, with no cross-pollination or
additional reviewer agents:
| Candidate | Mechanism | Result | Evidence |
|---|---|---|---|
| 1 | Snapshot only NSItemProvider values before awaiting |
Fail | Required iOS no-restore build failed with NETSDK1004; no behavioral run |
| 2 | Marshal each UIKit getter to the main thread at point of use | Blocked | Baseline guard prevented edits; empty diff and no test run |
Neither candidate passed. Candidate 1 produced a concrete, self-reviewed diff
but could not compile in the un-restored environment. Candidate 2 was stopped
before implementation by the mandatory baseline boundary.
📝 PR Finalize — Recommended Title & Description
Assessment: ✏️ Recommend updating — the current title identifies the symptom, but the description only names the backport and omits the root cause, implementation, affected iOS flow, and linked regression issue.
Recommended title
[iOS] MediaPicker: Fix UIKitThreadAccessException when selecting 2+ items
Recommended description
Backport of #37879 to main.
/cc @kubaflo @pierre-galaup
### Description of Change
`PickerResultsToMediaFiles` previously read each UIKit-backed `PHPickerResult.ItemProvider` in a loop that also awaited `LoadFileRepresentationAsync().ConfigureAwait(false)`. When two or more items were selected, the continuation could resume off the main thread before reading the next provider and throw `UIKitThreadAccessException`.
The iOS implementation now constructs all `PHPickerFileResult` instances before the first await, then loads their file representations sequentially. It preserves selection order and disposes every constructed result if construction or loading fails.
### Issues Fixed
Fixes #37878
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr
The submitted PR is the strongest candidate: it directly removes the
post-await UIKit access, preserves result ordering and #35805 temporary-file
semantics, and has complete cleanup for constructor and load failures. The
expert review found no concrete production-code defect. Approval is not
recommended because the trusted Gate was skipped, required CI remained
undetermined, and no regression test exercises the two-or-more-item picker
flow.
Comparative Ranking
| Rank | Candidate | Mechanism | Validation | Assessment |
|---|---|---|---|---|
| 1 | pr |
Construct all PHPickerFileResult wrappers before the first await, then load sequentially |
Gate skipped; no behavioral regression test; CI undetermined | Most complete implementation. It fixes the exact thread-affinity transition, preserves ordering and file semantics, and disposes every constructed wrapper on partial failure. |
| 2 | try-fix-1 |
Snapshot every NSItemProvider before awaiting, then construct and load one wrapper at a time |
Fail: required no-restore iOS build hit NETSDK1004; no behavioral run |
A plausible lower-retained-resource alternative with a concrete diff, but it has no compile or runtime evidence and therefore cannot displace the submitted fix. |
| 3 | pr-plus-reviewer |
Submitted PR plus expert feedback | Fail: required no-restore iOS build hit NETSDK1004; no behavioral run |
No safe test patch was possible without a system-picker harness or mockable PHPickerResult; reviewer.patch is empty, so this candidate adds no value over pr and has weaker validation evidence. |
| 4 | try-fix-2 |
Marshal each ItemProvider access to the main thread |
Blocked: baseline guard prevented edits; empty diff; no validation | Concept only. It has neither an implementation nor evidence and introduces repeated dispatch complexity absent from the winning approach. |
No candidate passed a regression test. The failed commands for try-fix-1
and pr-plus-reviewer were environment failures caused by missing restore
assets, not behavioral failures; neither may be treated as a pass. The blocked
try-fix-2 candidate ranks last because it never produced a patch.
Why pr Wins
- It is the only fully implemented candidate whose ownership and cleanup
behavior were reviewed in the submitted source. - It materializes all UIKit-backed values before the asynchronous boundary,
eliminating the specific second-item exception without introducing
dispatch or synchronization. - It retains input order and the real temporary-file
FullPathbehavior
required after #35805. - The alternatives provide no successful targeted or behavioral validation,
andpr-plus-reviewercontains no reviewer delta.
Required Follow-up
Add credible iOS regression coverage for selecting at least two items, or
document why the system picker cannot be automated and provide equivalent
manual device evidence. Required CI must also reach a classified result before
human approval.
🔗 Regression Cross-Reference
🔍 Regression Cross-Reference
⚠ Overlaps with prior bug-fix PRs — same files modified, but no exact line revert detected.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
Button, Label, Layout) started (the HostApp built and dotnet test launched) but produced no results — the app failed to launch or the test host crashed before a .trx was written (an app-launch/Appium failure or an emulator flake). These categories exited quickly, well under their time budget, so raising the budget will not help — re-run the review to try again. If it recurs, check the build-output.log + logcat in the drop-deep-uitests artifact for an app-startup crash.
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
Backport of #37879 to main
/cc @kubaflo @pierre-galaup