Skip to content

[release/11.0.1xx-preview7] Preserve Android Entry text during handler reuse - #37052

Closed
kubaflo wants to merge 6 commits into
release/11.0.1xx-preview7from
kubaflo/fix-preview7-entry-long-text
Closed

kubaflo wants to merge 6 commits into
release/11.0.1xx-preview7from
kubaflo/fix-preview7-entry-long-text

Conversation

@kubaflo

@kubaflo kubaflo commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!

Root Cause

Preview 7 Android device tests fail when an Entry starts with 5,001 characters or when a handler is reused after previously applying a restrictive MaxLength. Android can retain or reinstall the native length filter while mapping input-type properties, truncating text before MaxLength and Text finish mapping. The same ordering gap existed in both the standard EntryHandler and Material3 EntryHandler2 paths.

Description of Change

This change keeps the shared cross-platform mapper order unchanged and makes the Android dependency explicit for both handlers:

  • during bulk mapping, update the native length filter before writing text without prematurely trimming stale native text from a reused handler;
  • force the bulk Controls text write so an identical incoming value still passes through a newly restrictive MaxLength filter;
  • preserve normal MaxLength truncation when the property changes outside bulk mapping;
  • retain the two-sided cursor clamp after input-type changes so restoring selection cannot address outside the native text.

Keeping the shared Text then MaxLength order preserves WinUI programmatic truncation behavior. Do not solve this by globally reordering the shared mapper.

Tests

Expanded Android device coverage to reuse one handler in both directions for both EntryHandler and Material3 EntryHandler2:

  • restrictive MaxLength to unlimited 5,001-character text;
  • unlimited 5,001-character text to an identical value with restrictive MaxLength.

Local isolated red/green proof at 1c034b9573:

  • without only the Material3 implementation, the standard row passed and the Material3 row alone failed (63/64, expected 5,001 characters, actual "AA");
  • with the implementation restored, all Android Entry tests passed (64/64).

Current-head CI at 1c034b9573:

  • Main build 1538560 succeeded.
  • Device build 1538562 succeeded. Android Mono and CoreCLR each reported 1,031 total, 1,004 passed, and 0 failed. The long-text crash, long-to-short update, and handler-reuse MaxLength tests passed in both runtimes.
  • UI build 1538561 completed all Entry runs with 0 failures, including the WinUI MaxLength regression tests. Its remaining red status is limited to pre-existing WinUI Controls Label visual baseline failures also reproduced on base-branch builds 1538409 and 1538078.

Issues Fixed

Release-branch CI regression; no standalone issue.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9be49656-7117-4235-9d96-404779ab6b16
Copilot AI review requested due to automatic review settings August 3, 2026 18:43
@kubaflo
kubaflo temporarily deployed to copilot-pat-pool August 3, 2026 18:43 — with GitHub Actions Inactive
@github-actions

github-actions Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37052

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37052"

@kubaflo

kubaflo commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

/azp run maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

Copilot AI left a comment

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.

Pull request overview

This PR addresses an Android crash in EditTextExtensions.SetInputType where restoring the cursor position after resetting InputType can exceed the (re-applied) max-length-truncated text, leading to IndexOutOfBoundsException from Android span/selection handling.

Changes:

  • Clamp the restored cursor position to the current native text length when calling SetSelection after an InputType reset.

@kubaflo

kubaflo commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

/azp run maui-pr-devicetests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

@PureWeen PureWeen 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.

Adversarial Multi-Model Review

Methodology: 3 independent reviewers with adversarial consensus, plus this repo's own expert-reviewer domain rules (routed dimensions for src/Core/src/Platform/Android/**: Android Platform Specifics, Async/Threading, Memory Leak Prevention, plus always-active Logic & Correctness and Testing).

Verdict: no blocking issues

All three reviewers independently verified the root cause rather than accepting the description at face value, and all three concluded the change is correct and appropriately scoped:

  • The 5000-char ceiling is Android's own single-line LengthFilter fallback injected on setInputType/setSingleLine, not a MAUI-side limit — so the truncation is pre-existing OS behavior, not data loss introduced or masked by this PR. The diff only guards the SetSelection index; it does not touch Text, InputFilters, or InputType logic.
  • editText.Length() is the correct upper bound (Editable length; valid SetSelection range is 0..length), and it costs a single JNI crossing — no repeated bridge access.
  • This fixes the crash at its actual site. The same IndexOutOfBoundsException: setSpan (5001 … 5001) ends beyond length 5000 was previously worked around in #30242 by reordering mappers (MaxLength before IsPassword), which only covers one ordering. Clamping at the restore site is the more durable fix and complements that change.
  • No cross-platform impact (Android-only path), no new threading, race, or lifetime concerns.

What looks right

The cited device tests EntryWithLongTextDoesNotCrash and EntryWithLongTextAndShortText_UpdatesTextCorrectly were confirmed to exist on release/11.0.1xx-preview7 and each construct an Entry with a 5001-character string — they genuinely reproduce the original scenario, so the "no new test" decision is justified here rather than a coverage gap.

Findings

Severity Category Location Consensus
⚠️ Error Handling EditTextExtensions.cs:402 3/3 reviewers (severity split: 1 rated blocking, 2 rated non-blocking/pre-existing)

See the inline comment for detail. In short: the clamp is upper-bound only, and EditText.SelectionStart returns -1 when no cursor/selection is expressed, so Math.Min(-1, Length()) is still -1. All three reviewers agreed the hazard is real; two noted it is pre-existing (the old unclamped line had identical exposure) and therefore not a regression from this PR. Raised because you are already hardening this exact line — Math.Clamp(previousCursorPosition, 0, editText.Length()) closes it completely at no cost.

Test coverage

Changed path is covered by the two existing Android device tests named above. One reviewer suggested linking the green maui-pr-devicetests run to this PR as the concrete red→green evidence; that was a single-reviewer process suggestion and is not tracked as a finding.

Prior reviews

copilot-pull-request-reviewer has commented; no unresolved human review threads found. No findings above duplicate prior feedback.

CI status is intentionally out of scope for this review.

@PureWeen

PureWeen commented Aug 3, 2026

Copy link
Copy Markdown
Member

Device-test verification: rerun needed

The implementation review found no blocking code issue, but the Android device-test run did not verify the two tests this PR is intended to fix.

In maui-pr-devicetests build 1537906, the Android Controls work item (com.microsoft.maui.controls.devicetests-Signed) terminated before producing test results:

INSTRUMENTATION_RESULT: shortMsg=Process crashed.
XHarness exit code: 80 (APP_CRASH)
No results file found in any of the following formats: xunit, junit, trx
Packing 0 test reports

Consequently, EntryWithLongTextDoesNotCrash and EntryWithLongTextAndShortText_UpdatesTextCorrectly have no recorded outcome in this run. The Helix infrastructure classified this as an infrastructure error and requested an automatic retry, and the base branch has also had repeated device-test failures, so this may be transient/unrelated to the PR.

Recommendation: rerun maui-pr-devicetests once. Before merging, confirm that the Android Controls work item completes and that both target tests are explicitly reported as passing. If it crashes again, investigate the Controls device-test app crash rather than treating the PR as verified.

Handle SelectionStart returning -1 while retaining the upper bound needed
after Android truncates text during input type changes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9be49656-7117-4235-9d96-404779ab6b16
Copilot AI review requested due to automatic review settings August 3, 2026 21:31
@kubaflo

kubaflo commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

Map MaxLength before IsPassword and Text so changing the native input type cannot truncate long initial values.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 9be49656-7117-4235-9d96-404779ab6b16
Copilot AI review requested due to automatic review settings August 3, 2026 22:45

Copilot AI left a comment

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.

Copilot's findings

Suppressed comments (2)

src/Controls/src/Core/Entry/Entry.Android.cs:35

  • The new bulk-mapping ordering workaround is applied for EntryHandler/IEntryHandler, but the Material3 path (EntryHandler2) still maps Text before MaxLength during IsMappingProperties(). Since EntryHandler2.MapText writes to the native EditText before MapMaxLength runs, a pre-existing/default LengthFilter (e.g. 5000) can still truncate an initial 5,001+ character value and permanently lose the extra characters.

To keep behavior consistent when RuntimeFeature.IsMaterial3Enabled is on, EntryHandler2 likely needs the same pattern: ensure the current length filter is applied/updated before setting text during bulk mapping (and consider forcing the text write even when the incoming value matches the old native value).

			var isMappingProperties = handler.IsMappingProperties();
			if (isMappingProperties)
				handler.UpdateValue(nameof(IEntry.MaxLength));

			Platform.EditTextExtensions.UpdateText(handler.PlatformView, entry, isMappingProperties);
		}

src/Core/src/Handlers/Entry/EntryHandler.Android.cs:79

  • This bulk-mapping workaround updates MaxLength from inside MapText, but EntryHandler2 (Material3) still maps Text before MaxLength and can hit the same truncation problem when a handler is reused with an existing/default native LengthFilter (e.g. 5000). If the intent is to preserve 5,001+ character initial values across Android Entry variants, the Material3 handler should get an equivalent ordering/force-update treatment during IsMappingProperties().
		public static void MapText(IEntryHandler handler, IEntry entry)
		{
			if (handler.IsMappingProperties())
				handler.UpdateValue(nameof(IEntry.MaxLength));

			handler.PlatformView?.UpdateText(entry);
		}
  • Files reviewed: 5/5 changed files
  • Comments generated: 0 new

@PureWeen

PureWeen commented Aug 4, 2026

Copy link
Copy Markdown
Member

/azp run maui-pr-devicetests

@PureWeen

PureWeen commented Aug 4, 2026

Copy link
Copy Markdown
Member

/azp run maui-pr-uitests

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

1 similar comment
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 9be49656-7117-4235-9d96-404779ab6b16
Copilot AI review requested due to automatic review settings August 4, 2026 02:35
@kubaflo

kubaflo commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

Extended the fix at 1c034b9573 to cover the Material3 EntryHandler2 path and expanded the handler-reuse test to exercise both Android handlers.

Local isolated red/green proof (Category=Entry):

  • Without only the new Material3 implementation: 63/64 passed. The standard handler row passed; the Material3 row alone failed because the reused native filter truncated 5,001 characters to "AA".
  • With the implementation restored: 64/64 passed, including both handler-reuse rows.

Fresh exact-head CI is being queued now; I will post the Helix result when it settles.

@kubaflo

kubaflo commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Copilot AI left a comment

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.

Pull request overview

Copilot reviewed 6 out of 6 changed files in this pull request and generated no new comments.

@kubaflo kubaflo changed the title [release/11.0.1xx-preview7] Preserve Android Entry text longer than 5000 characters [release/11.0.1xx-preview7] Preserve Android Entry text during handler reuse Aug 4, 2026
@kubaflo

kubaflo commented Aug 4, 2026

Copy link
Copy Markdown
Contributor Author

@PureWeen current head 1c034b9573 is now proven in exact-head maui-pr-devicetests build 1538562; the build changes API contains this commit.

  • Android CoreCLR Helix job a2ac39c1-a1f1-49ec-aaee-11936b991ce1: all 6 work items passed. Controls XML: 1,099 total, 1,087 passed, 0 failed, 12 skipped.
  • Android Mono Helix job 39b338ec-507c-45d6-994c-36cd8a7af6cd: all 6 work items passed. Controls XML: 1,099 total, 1,087 passed, 0 failed, 12 skipped.
  • In both runtimes, EntryTextRespectsMaxLengthWhenHandlerIsReused passed for useMaterial3: False and useMaterial3: True.

This exact head covers both the standard Android Entry handler and Material3 handler reuse path. Please merge this Preview 7 fix.

@PureWeen PureWeen 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.

Adversarial Multi-Model Validation — Current Head

Verdict: not ready as-is. Three independent reviewers completed adversarial consensus. One concrete selection-state regression and one Material3 coverage gap remain; see the inline comments.

(var oldText, var newText) = GetTexts(editText, inputView);

if (oldText != newText)
if (forceUpdate || oldText != newText)

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.

❌ Logic — forceUpdate now rewrites identical text during bulk handler mapping. On reuse where the old and incoming text already match and are within the same MaxLength, but the incoming Entry specifies CursorPosition/SelectionLength, editText.Text = newText followed by SetSelection(end) fires the still-subscribed SelectionChanged callback before the cursor mappers run. That callback overwrites the incoming virtual selection, and the later mappers see matching corrupted values and no-op. Pre-PR, this identical-text/in-range case skipped both UpdateText and UpdateMaxLength's setText, so the selection was preserved.

Please either restrict the forced write to cases where the newly installed filter must actually re-filter the current text, or suppress native-to-virtual selection propagation during bulk mapping, and add an equal-text handler-reuse test with explicit cursor/selection values.

Flagged by: 2/3 reviewers after adversarial dispute; the narrower equal-text scenario was source-validated.

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.

Addressed in d214ebc535. Both Android Entry handlers now capture the incoming cursor/selection, detach native selection callbacks during bulk remapping, restore and remap those incoming values, then reattach callbacks. The reuse regression test uses identical text with explicit virtual/native cursor and selection assertions for both handlers. Local Android Category=Entry: 64/64 passed. Exact-head device build: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1539389


if (useMaterial3)
{
var handler = await CreateHandlerAsync<EntryHandler2>(firstEntry);

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.

💡 Testing — The useMaterial3: true row constructs EntryHandler2, but the device-test app calls RemapForControls() while RuntimeFeature.IsMaterial3Enabled is still at its default false. That means EntryHandler2.Mapper never receives the changed Controls MapText override, so this row exercises the Core handler path rather than Entry.Android.cs:48-65 and its Material3 forceUpdate wiring.

Enable Material3 before the app performs RemapForControls() (or use a dedicated Material3-enabled test configuration) and assert the feature is enabled, so this test actually covers the changed Controls path.

Flagged by: 2/3 reviewers; confirmed from the test app setup and mapper registration guard.

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.

Addressed in d214ebc535. Device-test startup now enables Material3 only while Entry.RemapForControls() registers the Controls mappings, then restores the original feature-switch value. The direct EntryHandler2 theory row therefore exercises the changed Controls Material3 mapper without changing the suite default. Local Android Category=Entry: 64/64 passed. Exact-head device build: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1539389

@sheiksyedm

Copy link
Copy Markdown
Contributor

The root cause of this test failure is the changes introduced in this PR. #35892

@kubaflo kubaflo closed this Aug 4, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: ac5d2f3f-f484-47b1-9bc7-8e45e9cef498
@PureWeen PureWeen reopened this Aug 4, 2026
@PureWeen

PureWeen commented Aug 4, 2026

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

@PureWeen PureWeen closed this Aug 4, 2026
PureWeen pushed a commit that referenced this pull request Aug 4, 2026
<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

### Description of Change

Bundles independently valid Preview 7 test and test-infrastructure
stabilizations into one merge path. Changes are cherry-picked or
extracted from their source PRs without modifying MAUI runtime or
product behavior.

The aggregate currently covers:

- exact DragEvents label polling and shared Appium text-wait behavior;
- waiting for the iOS Entry keyboard before its snapshot;
- adaptive ListView and CollectionView screenshot stabilization;
- RefreshView gesture retry and SwipeView callback-result waiting;
- stable initial SafeArea layout measurement;
- deterministic iOS Picker-to-Entry keyboard transition handling;
- a bounded Android screenshot tolerance for stable post-rotation
antialiasing variance;
- independent iOS and MacCatalyst Graphics image-scaling device
coverage;
- a bounded UIKit cleanup wait for the CarouselView leak assertion;
- Android-only scoping for the Android modal-animation leak regression
test;
- an exact detached-page transition with a synchronous alert-request
return signal; and
- resilient Windows test-machine resolution setup, with focused Pester
coverage for each fallback and failure path.

Eligible UI tests, device tests, unit tests, test infrastructure, and
screenshot baselines can all be included here when they are
independently valid without a corresponding product-code change.

### Source PRs

The standalone source PRs below are closed in favor of this aggregate.
For #37057, only the independently valid test subset is included; its
product-code rewrite remains excluded.

| PR | Included test-side fix |
|---|---|
| #37044 | Windows screen-resolution test infrastructure and Pester
coverage |
| #37045 | DragEvents exact-text waits and Appium helper |
| #37053 | iOS Entry keyboard readiness |
| #37055 | ListView screenshot retry window |
| #37057 | Graphics image-scaling device tests that pass without the
runtime rewrite |
| #37058 | RefreshView pull-to-refresh retry |
| #37059 | SwipeView result-label wait |
| #37066 | SafeArea initial-layout retry |
| #37069 | Picker keyboard transition stabilization |
| #37074 | Empty CollectionView footer screenshot retry/tolerance |
| #37086 | iOS/MacCatalyst CarouselView leak-test cleanup wait |
| #37088 | Detached-page alert request synchronization |
| #37091 | Android modal-animation leak-test platform scope |
| #37092 | Android Issue22306 post-rotation screenshot tolerance |

### Scope exclusions

Mixed runtime/test fixes are included only when their test-side changes
pass independently against the unmodified product code. The current
device tests in #37052, the four nonpositive-size cases in #37057, and
the device test plus screenshots in #37062 remain excluded because they
expose or describe behavior that requires those PRs' functional fixes.
#37070 has no test-side changes. Closed ineffective or unsafe fixes are
also excluded.

### Validation

- All 25 directly reusable source commits were cherry-picked in their
original order.
- The #37057 device-test subset was extracted into one additional
test-only commit after proving it against the unmodified product
implementation.
- Every directly cherry-picked aggregate file matches the corresponding
included source PR head.
- The aggregate diff contains no MAUI runtime or product files.
- Targeted Release builds pass for `UITest.Appium`,
`Controls.TestCases.iOS.Tests`, `Controls.TestCases.Mac.Tests`, and
`Controls.TestCases.Android.Tests`.
- The focused screen-resolution Pester suite passes 14/14.
- Exact local xUnit XML reports 46/46 Graphics device tests passing on
both iOS 26 and MacCatalyst, including all 13 extracted cases.
- The Graphics deadlock regression now asserts the bounded five-second
completion result before awaiting the scaling task.
- The CarouselView category passes 6 consecutive MacCatalyst runs at 4/4
each and passes 4/4 on iOS 26 with the final 100 ms cleanup wait.
- The Android modal-animation leak test passes in both discovered
Android variants, while the iOS device-test assembly excludes that
Android-specific regression test.
- The Issue22306 Android failure's three retries were byte-for-byte
identical at a 1.85% visual difference, below the new Android-only 2%
tolerance.
- The unloaded-page alert probe now signals immediately after
`DisplayAlertAsync` returns, avoiding a teardown-order dependency on the
detached page task.
- Rebased the aggregate onto release head `dee83edd121`; the resulting
diff remains limited to tests and test infrastructure.
- The Pester workflow now triggers when
`eng/scripts/Set-ScreenResolution.ps1` changes.
- A standalone `/azp run` was posted for aggregate head `83da465424b`;
exact merge `bad9e4e9a57` builds `1539860`, `1539861`, and `1539862` are
required before merge.

### Issues Fixed

Contributes to stabilizing the .NET 11 Preview 7 test branch.

---------

Co-authored-by: Vally Fixture <vally-fixture@example.invalid>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: kubaflo <34349119+kubaflo@users.noreply.github.com>
Copilot-Session: 9be49656-7117-4235-9d96-404779ab6b16
Copilot-Session: d00747b7-96f3-4e7a-8dfb-e3a48db04b2d
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 4, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants