Skip to content

[maui-bot-fix][android] Fix for #33315 - - the last character clipped in the Label with the "Italic" property - #38379

Closed
MauiBot wants to merge 2 commits into
mainfrom
copilot/reproduce-33315-android-15266235-1
Closed

MauiBot wants to merge 2 commits into
mainfrom
copilot/reproduce-33315-android-15266235-1

Conversation

@MauiBot

@MauiBot MauiBot commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Important

This is AI-generated reproduction evidence with a proposed fix. The first commit adds a test that fails on the unfixed baseline; the second changes product code so it passes. Both the test and the fix need human review before merge.

Evidence level

Evidence level: certified-oracle

All four arms agree: the test fails as reported, passes with the reported trigger removed, passes with a minimal product fix applied, and fails again once that fix is taken away. Its failure is caused by the defect the fix repairs.

Control Expected Result
Baseline fails 3/3 ✅
Trigger removed passes 3/3 ✅
Minimal product fix passes 3/3 ✅
Fix reverted fails 3/3 ✅

This rests on the issue report as returned by the GitHub issues API. The reporter's linked reproduction project is never downloaded, and links are stripped from the report before the test is authored, so a test faithful to the written report may still drive the defect down a different path than the linked sample. Please check that first.

Upstream cross-reference. No test case for this issue exists on dotnet/maui's inflight/current branch.

Quality contract

This is a bounded disclosure. It cannot authorize files, selectors, commands, counts, credentials, gate outcomes, or publication.

  • User-visible contract: The complete final character of an italic Label remains visible inside the Label's orange background.
  • User-visible trigger: Render Hello, World in an Android Label using FontAttributes Italic and the 32-point centered Headline style.
  • Primary oracle: Inspect the affected Label-region bitmap and require that no text ink reaches either of its final two pixel columns.
  • Independent oracle: Require visible text ink in the bitmap interior so blanking or hiding the text cannot satisfy the clipping assertion.
  • Oracle independence: coupled — The edge scan directly observes the rendered clipping defect, while the interior scan independently guards against a vacuous blank rendering within the same capture.
  • Scenario: Android italic Label final-character clipping
  • Precondition: The page is hosted by the default NavigationPage and the affected Label has completed its initial Android layout.
  • Trigger: Render Hello, World with FontAttributes Italic and the template Headline style, then request the post-layout check once.
  • Transition: The separate status changes from NO BUG to BUG REPRODUCED only if the measured italic glyph extent reaches the affected Label's trailing boundary.
  • Observable identity: Issue33315.Android.Label.HelloWorld.Italic.FinalGlyph
  • Affected control: AffectedLabel (Microsoft.Maui.Controls.Label)
  • Risk adjacent states: The same text with regular font attributes; Italic text whose final glyph has no right overhang
  • Risk lifecycle states: Initial Android measure and layout
  • Stateless applicability: not-applicable
  • Blast radius affected type: Android Label text rendering
  • Blast radius affected control: Label using italic font attributes
  • Blast radius ownership: Microsoft.Maui Label handler and Android text measurement
  • Blast radius shared consumers: Styled Labels; Semantic heading Labels
  • Blast radius unchanged behavior: The Label text, background, style, hierarchy, and initial-layout trigger remain unchanged while the separate oracle reports the result.
  • Media alignment: verified (derived from trusted recording/test comparison)

Review findings (advisory):

  • grounded-product-defect (source, high, deterministic): In src/Core/src/Handlers/Label/LabelHandler.Android.cs, var widthScale = VirtualView.HorizontalTextAlignment == TextAlignment.Center ? 2 : 1; treats TextAlignment.End the same as start-aligned text even though src/Core/src/Platform/Android/AlignmentExtensions.cs maps end alignment to ATextAlignment.ViewEnd and GravityFlags.End. For an end-aligned
  • grounded-product-defect (source, high, deterministic): In src/Core/src/Handlers/Label/LabelHandler.Android.cs, textLayout.Paint.GetTextPath(text, 0, text.Length, 0, 0, textPath); derives the overhang from one plain Paint, but src/Controls/src/Core/Platform/Android/Extensions/TextViewExtensions.cs renders shared Label content through textView.TextFormatted = label.ToSpannableString(); for `FormattedTe
  • missing-evidence-coverage (source-and-runner, high, multiple): The certified oracle in src/Controls/tests/DeviceTests/Elements/Label/Issue33315Tests.Android.cs covers exactly one centered plain Label with whole-label FontAttributes = Italic, and CustomAgentLogsTmp/IssueReplication/Issue33315/fix/restoration-arm/verification-test-result.xml shows that only ItalicLabelDoesNotClipFinalCharacter ran. That test can

Reproduced issue

  • Issue: dotnet/maui#33315 — [Android] - the last character clipped in the Label with the "Italic" property
  • Platform: android
  • Validated on baseline commit: f7bfa2a551fab729ddebd3d116a05508fbc3161b — the trusted device reproduction and the failing-test verification both ran against this commit
  • Base branch: the reproduction commit sits directly on the validated baseline above; its parent is that baseline. The reproduction commit adds only the failing test; any proposed product fix is a separate following commit.
  • Test type: device
  • Test execution host: the Android emulator used for the run above.
  • Exact test: Microsoft.Maui.DeviceTests.Issue33315.ItalicLabelDoesNotClipFinalCharacter
  • Targeted filter: Issue33315 — an issue-keyed class token; use the exact test above when a runner needs a precise selector
  • Selector variant: device-category-only
  • Raw runner selector: Category=Issue33315
  • Normalized selector: project Controls (src/Controls/tests/DeviceTests/Controls.DeviceTests.csproj), class Microsoft.Maui.DeviceTests.Issue33315, method ItalicLabelDoesNotClipFinalCharacter, platform android
  • Trusted selector counts: 1 discovered / 1 executed
  • Expected failing assertion: Assert.False() Failure
  • Determinism: the exact test above was executed 3 independent times on this baseline and failed at the same assertion every time
  • Pipeline run: https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=15266235

Recorded evidence (Android emulator)

Reproduction preview

Open the full MP4 recording · Evidence manifest

The authoritative proof is the trusted targeted test failing with the expected assertion above. The recording corroborates that; for defects with no visible symptom it may show only the app-reported verdict rather than the defect itself.

This recording is of the trusted Sandbox reproduction app that established the behavior on the Android emulator, not of the committed test executing. Its on-screen text therefore comes from that Sandbox app and will not match the assertion payload emitted by the committed test. Treat it as corroboration of the symptom, not as exact-head evidence for the commit in this pull request.

Reproduction steps

  1. Create an orange Label containing Hello, World with the 32-point centered Headline style and heading semantics inside the reported scrolling page layout.
  2. Apply the italic font attribute before attaching the page to an Android window.
  3. Wait until the affected Label has a handler, is loaded, and has bounded nonzero dimensions.
  4. Capture the rendered Label region and verify that text ink is visible inside it but does not reach either of its final two pixel columns.

Safety and validation

  • The pipeline reconstructed the scenario from issue text, inline snippets, and allowed raster screenshots.
  • No linked repository, archive, binary, script, package, or arbitrary external file was downloaded.
  • A trusted runner reproduced the behavior on the Android emulator and matched the expected targeted test failure in 3 consecutive executions.
  • The reproduction commit is add-only and restricted to approved MAUI test locations. The fix commit modifies only the product files listed above, and adds, deletes, renames, and mode changes are refused.

Proposed fix

This pull request carries two commits. The first adds the failing reproduction on its own, so check out that first, test-only commit to observe the failure. The second changes product code so the same test passes.

Root cause. On Android, FontAttributes.Italic becomes a slanted ILabel.Font, LabelHandler.MapFont applies the corresponding italic Typeface through TextViewExtensions.UpdateFont, and the native AppCompatTextView is then measured by LabelHandler.GetDesiredSize. For a non-Fill, centered Label, that intrinsic width reflects text advances but does not reserve the final glyph's visual right overhang; layout therefore arranges the Label at that too-narrow width and Android clips the overhanging pixels at the Label boundary, producing ink in the bitmap's final two columns. The likely defect is the Android Label…

Root-cause path. Label.FontAttributes assignment updates ITextStyle.Font -> LabelHandler.Mapper invokes LabelHandler.MapFont -> TextViewExtensions.UpdateFont assigns the italic Android Typeface and size -> native AppCompatTextView measurement feeds LabelHandler.GetDesiredSize -> VerticalStackLayout centers and arranges the non-Fill Label at that intrinsic width -> the captured Label bitmap exposes the final glyph against the trailing boundary.

Ownership. Microsoft.Maui Core Android Label handler intrinsic text measurement and arrangement.

Dynamic state. The certified state is initial Android handler creation, font mapping, measure, layout, and first visible load after FontAttributes is set before attachment. A mechanism-level correction in desired measurement should also recompute naturally when existing font or text invalidation causes a later measure, without adding persistent state or a one-time special case.

Threading. Font mapping, native TextView measurement, layout, and bitmap observation occur on the Android UI thread; the scoped correction should remain synchronous in that existing measure path and introduce no dispatching or background work.

Teardown. The affected path has no issue-specific subscriptions, callbacks, or owned resources. A measurement-only correction should require no teardown changes and must not retain the Label, Android Layout, Paint, or Typeface beyond the measure call.

Unchanged behavior. Text, typeface selection, color, background, style, semantics, hierarchy, padding, alignment, wrapping, line count, explicit constraints, and height measurement must remain unchanged. Regular text and italic text whose glyphs do not exceed their advance width must retain their existing size, while constrained or Fill Labels must not be widened beyond their available width.

Semantic blast radius. Narrowly affects Android Label intrinsic width when rendered glyph bounds extend beyond the width reported by native text advances. The correction should reserve only demonstrated visual overhang, preserve multiline, MaxLines, ellipsis, RTL/bidi, padding, and explicit-width behavior, and avoid changing Android font creation or general TextView behavior used by other controls.

Regression lane. The device tests beside this one declare Label. This test declares only its issue category, because a second category makes the advertised Category=Issue<N> selector match nothing on this runner.

Approach taken. # Approach: measure the rendered text outline instead of integer glyph bounds I changed src/Core/src/Handlers/Label/LabelHandler.Android.cs so an intrinsically sized, single-line Android Label compares its native line advance with the vector outline produced by Paint.GetTextPath. When the outline extends beyond the advance width, GetDesiredSize reserves that right overhang plus two physical pixels for rasterized edge coverage. Center-aligned text reserves twice that amount because only half of an overall width increase becomes trailing space. This differs from candidate 1 by using the s…

Regression cross-reference. No line this fix deletes was added by a recent bug-fix pull request.

Try-fix panel. 5 candidate(s) each ran the reviewer's try-fix skill against this reproduction, sequentially and cross-pollinated, so each saw the approaches the earlier ones had already tried. The selected row is the fix published below.

# Model Result Approach or rejection
1 gpt-5.4 Fail Running the certified reproduction test against the candidate edit failed with exit code 1. 📁 Output directory: CustomAgentLogsTmp/PRState/33315/PRAgent/gate/verify-tests-fail VERIFY FAILURE ONLY MODE 1. Tests FAIL (proving they catch the bug) 🧪 Running 1 test(s) (expecting them to FAIL)... XHarne
2 gpt-5.6-sol Pass (selected) # Approach: measure the rendered text outline instead of integer glyph bounds I changed src/Core/src/Handlers/Label/LabelHandler.Android.cs so an intrinsically sized, single-line Android Label compares its native line advance with the vector outline produced by Paint.GetTextPath. When the outlin
3 gpt-5.4 Fail Running the certified reproduction test against the candidate edit failed with exit code 1. 📁 Output directory: CustomAgentLogsTmp/PRState/33315/PRAgent/gate/verify-tests-fail VERIFY FAILURE ONLY MODE 1. Tests FAIL (proving they catch the bug) 🧪 Running 1 test(s) (expecting them to FAIL)... ❌ Buil
4 gpt-5.6-sol Fail Running the certified reproduction test against the candidate edit failed with exit code 1. 📁 Output directory: CustomAgentLogsTmp/PRState/33315/PRAgent/gate/verify-tests-fail VERIFY FAILURE ONLY MODE 1. Tests FAIL (proving they catch the bug) 🧪 Running 1 test(s) (expecting them to FAIL)... XHarne
5 gpt-5.4 Fail Running the certified reproduction test against the candidate edit failed with exit code 1. 📁 Output directory: CustomAgentLogsTmp/PRState/33315/PRAgent/gate/verify-tests-fail VERIFY FAILURE ONLY MODE 1. Tests FAIL (proving they catch the bug) 🧪 Running 1 test(s) (expecting them to FAIL)... ❌ Buil

Only the selected candidate's diff was applied and put through the fix and restoration arms. The other rows are recorded so the comparison is visible rather than implied.

Independent review. A second model (gpt-5.4) reviewed the winning diff without having written it. I would not approve this change as written because it broadens shared Android Label measurement with a center-oriented path workaround that is not correct for all supported label content and alignment paths.

  • advisory. In src/Core/src/Handlers/Label/LabelHandler.Android.cs, var widthScale = VirtualView.HorizontalTextAlignment == TextAlignment.Center ? 2 : 1; treats TextAlignment.End the same as start-aligned text even though src/Core/src/Platform/Android/AlignmentExtensions.cs maps end alignment to ATextAlignment.ViewEnd and GravityFlags.End. For an end-aligned single-line label, increasing desired width only creates extra space on the left side of the TextView, so the final glyph can still sit on the same right boundary and clip there. I would either compute compensation from the rendered line's actual visual edges for each alignment/direction or keep the fix scoped to the centered case that is actually proven. (grounded-product-defect; grounding source, confidence high, corroboration deterministic; advisory)
  • advisory. In src/Core/src/Handlers/Label/LabelHandler.Android.cs, textLayout.Paint.GetTextPath(text, 0, text.Length, 0, 0, textPath); derives the overhang from one plain Paint, but src/Controls/src/Core/Platform/Android/Extensions/TextViewExtensions.cs renders shared Label content through textView.TextFormatted = label.ToSpannableString(); for FormattedText and through UpdateTextHtml for HTML. Those paths can apply per-span font/style changes or non-text spans that the handler's single Paint does not represent, so this shared handler can now return a "fixed" width that is still wrong for supported label content. I would base the adjustment on rendered Layout extents that already reflect the actual content, or explicitly exclude non-plain-text labels instead of silently mismeasuri (grounded-product-defect; grounding source, confidence high, corroboration deterministic; advisory)
  • advisory. The certified oracle in src/Controls/tests/DeviceTests/Elements/Label/Issue33315Tests.Android.cs covers exactly one centered plain Label with whole-label FontAttributes = Italic, and CustomAgentLogsTmp/IssueReplication/Issue33315/fix/restoration-arm/verification-test-result.xml shows that only ItalicLabelDoesNotClipFinalCharacter ran. That test can see Assert.False(hasRightEdgeInk) for the reported centered case, but it cannot tell a reviewer whether widthScale is wrong for end/RTL alignment or whether extraWidth = Context.FromPixels((float)System.Math.Ceiling(rightOverhang + 2) * widthScale) is over-widening unaffected labels. I would either add coverage for the additional alignment/content cases this handler change now affects or narrow the implementation so the change su (missing-evidence-coverage; grounding source-and-runner, confidence high, corroboration multiple; advisory)

These findings did not block publication. They are reported so a maintainer sees them in the body rather than having to rediscover them, and any of them may be wrong.

How far to trust them, measured rather than asserted: across two blind trials covering 8 diffs, this arm recovered 6 of the 8 specific defects an earlier automated adversarial-review pass had already named, and raised a blocking finding on 1 of 4 fixes dotnet/maui had already merged. This measures agreement between automated review passes, not independent ground truth. At n=8 those rates are indicative only - they can rule out a high error rate, but they cannot establish a low one.

Files changed by the fix commit:

  • src/Core/src/Handlers/Label/LabelHandler.Android.cs

Copilot AI added 2 commits September 10, 2026 00:57
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 735ac9a2-7bec-4baa-ad19-c298e5bc795a
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 735ac9a2-7bec-4baa-ad19-c298e5bc795a
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

@github-actions

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 -- 38379

Or

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

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 10, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Expert Review — 3 findings

See inline comments for details.

{
// Centered text receives half of added width on each side, so reserve
// twice the outline overhang plus two pixels for rasterized edge coverage.
var widthScale = VirtualView.HorizontalTextAlignment == TextAlignment.Center ? 2 : 1;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

❌ Error — The overhang fix only treats TextAlignment.Center specially, but TextAlignment.End remains mechanically broken: increasing desired width does not create right-side slack for end-aligned text because the glyph run stays anchored to the view end, so the final italic overhang is still clipped. Concrete scenario: single-line non-Fill label with italic text and HorizontalTextAlignment.End (including RTL end-aligned layouts).

if (!string.IsNullOrEmpty(text))
{
using var textPath = new APath();
textLayout.Paint.GetTextPath(text, 0, text.Length, 0, 0, textPath);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

⚠️ Warning — GetTextPath is computed from PlatformView.Text and textLayout.Paint, which does not include span-level styling from formatted/HTML Spannable runs. For a trailing italic/bold span, rightOverhang can be under-measured, so the last glyph can still clip even though this branch returns an adjusted width.

{
[Fact]
[Category("Issue33315")]
public async System.Threading.Tasks.Task ItalicLabelDoesNotClipFinalCharacter()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

💡 Suggestion — Coverage is limited to plain LTR centered text. Because the new handler branch runs for single-line non-Fill labels generally, add regression cases for HorizontalTextAlignment.End (including RTL) and formatted/HTML italic text so adjacent alignment/text-path behaviors are protected.

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

AI Review Summary

@MauiBot — new AI review results are available based on commit 304132c.

Gate Passed Confidence Low Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: b96aa036

Test Without Fix (expect FAIL) With Fix (expect PASS)
📱 Issue33315 Category=Issue33315 ✅ FAIL — 978s ✅ PASS — 657s
🔴 Without fix — 📱 Issue33315: FAIL ✅ · 978s

(no coded error found; showing last 1200 chars)

         "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.controls.devicetests'..
fail: Waiting for command timed out: execution may be compromised
fail: Error: Exit code: -2
      Std out:
XHarness exit code: 1 (TESTS_FAILED)
  Passed: 0
  Failed: 1
  Skipped: 0
  Total: 1
  Tests completed with exit code: 1
🟢 With fix — 📱 Issue33315: PASS ✅ · 657s

(no coded error found; showing last 1200 chars)

            "totalMemoryBytes": 8322998272
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.controls.devicetests'..
info: Successfully uninstalled com.microsoft.maui.controls.devicetests
XHarness exit code: 0
  Passed: 1
  Failed: 0
  Skipped: 0
  Total: 1
  Tests completed successfully
📁 Fix files reverted (1 files)
  • src/Core/src/Handlers/Label/LabelHandler.Android.cs

📋 Pre-Flight — Context & Validation

PR #38379 Pre-Flight

Context

  • PR: [maui-bot-fix][android] Fix for #33315 - - the last character clipped in the Label with the "Italic" property
  • Issue: #33315, an Android-only bug where the final glyph of an italic Label is clipped at the trailing edge. The reported case renders centered Hello, World text at 32 points inside an intrinsically sized orange Label.
  • State: Open draft, targeting main.
  • Materialized refs: base b96aa036b89fe41fe1ce6cae63a3f2d1550e5682; review HEAD acc4616b06b544c7258559788810d1e6562c41f0 (PR head reported by GitHub: 304132c8cac6b83bacff9f7f055d821a8226a0ab).
  • Platform: Android.
  • Regression cross-reference: No recent labeled bug-fix PR was found touching the modified files.

Direct Diff Inspection

The PR adds 124 lines across two files:

  1. src/Controls/tests/DeviceTests/Elements/Label/Issue33315Tests.Android.cs adds the certified Android device test Microsoft.Maui.DeviceTests.Issue33315.ItalicLabelDoesNotClipFinalCharacter. It captures the rendered label, proves there is interior ink, and fails when ink reaches either of the final two pixel columns.
  2. src/Core/src/Handlers/Label/LabelHandler.Android.cs changes GetDesiredSize for non-Fill, single-line, non-ellipsized labels. The proposed fix builds an Android Path with Layout.Paint.GetTextPath, compares its right bound with Layout.GetLineWidth(0), and adds the detected right overhang plus two physical pixels. It doubles that extra width for centered text because only half of a centered width increase becomes trailing space.

The baseline handler contains only the existing multiline intrinsic-width correction; the new single-line outline branch is the entire product change.

Existing-Fix Risks Candidates Must Avoid

  • TextAlignment.End receives only the start-alignment width scale even though added width is placed before end-aligned text, so the trailing glyph can remain at the clipping boundary.
  • A single Layout.Paint.GetTextPath call for PlatformView.Text does not represent formatted/HTML content with per-span typefaces, styles, or non-text spans.
  • The implementation broadens shared Android Label measurement, while the certified evidence covers only centered plain text with whole-label italic font attributes.
  • Any alternative must be mechanism-level different from the PR's GetTextPath/plain-paint outline compensation, preserve constraints, wrapping, ellipsis, padding, RTL/bidi, formatted content, and unchanged non-overhanging labels.

Bounded Validation Contract

  • Primary test command: pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Issue33315"
  • Expected selection: 1 discovered / 1 executed.
  • Existing gate: Passed already: the primary test failed without the product fix and passed with it. Do not rerun gate verification and do not create or overwrite PRAgent/gate/content.md.
  • Mandatory regressions: None were enumerated in the STEP 5a request. Run only the primary command above; do not run a full suite or the unrelated detected UI category.
  • Attempt bound: One implementation/test pass and, only if necessary, one focused correction/retest per candidate.

Workspace and Modification Boundary

The review worktree contains pre-existing harness changes under .github/ and eng/; they are out of scope and must remain untouched. Each try-fix invocation must establish and restore its baseline only through .github/scripts/EstablishBrokenBaseline.ps1. The expected product target is src/Core/src/Handlers/Label/LabelHandler.Android.cs; the added test and all other files are read-only unless the generated baseline state explicitly permits them.


🔬 Code Review — Deep Analysis

Code Review — PR #38379

Independent Assessment

What this changes: The Android LabelHandler.GetDesiredSize path now detects right-side glyph-outline overhang for intrinsically sized, single-line, non-ellipsized labels and enlarges the requested width. Centered text doubles the enlargement so half of the added width becomes trailing space. A focused Android device test verifies the reported centered, plain-text italic-label rendering.

Inferred motivation: Android's measured text advance can be narrower than the visible outline of a final italic glyph, causing the glyph to touch or cross the trailing bitmap boundary and be clipped.

Approach assessment: The submitted fix is proven for the exact centered plain-text reproduction, but the implementation is broader than that evidence and is not mechanically correct for all alignments or supported styled text.

Reconciliation with PR Narrative

Author claims: The PR describes an Android-only intrinsic-width defect for a centered 32-point italic Label, identifies the font-to-measure path, and says the outline-overhang adjustment preserves unrelated layout behavior.

Agreement/disagreement: The root-cause path and certified centered-case Gate evidence agree with the code. The broader unchanged-behavior claim is not established: end-aligned content receives no trailing slack from a wider end-aligned view, and a single plain Paint does not represent formatted/HTML span styling.

Prior Review Reconciliation

No prior ❌ Error findings were present on the top-level review, inline-review-comment, or PR issue-comment surfaces. The advisory concerns embedded in the PR description independently identify the same end-alignment and styled-content risks and remain applicable to the submitted HEAD.

Blast Radius Assessment

  • Runs for all instances: The new branch runs for every non-Fill, single-line, non-ellipsized Android Label whose measured width is below the constraint, not only italic or centered labels.
  • Startup impact: No startup or registration impact; this is synchronous platform layout work.
  • Static/shared state: None.
  • Hot-path impact: Each qualifying measure allocates an Android Path and RectF and performs glyph-path extraction, including labels that have no relevant overhang.
  • Lifecycle impact: No subscriptions or persistent state were added; reconnect/disconnect behavior is unchanged.

CI Status

  • Trusted Gate result: pass — the focused Issue33315 test fails without the product fix and passes with it.
  • Current public check state: pending — license/cla is queued and Build Insights/Build Analysis are in progress; no completed required-build result was available.
  • Classification: The focused behavior is verified, but overall CI coverage is undetermined.
  • Action taken: Confidence is capped at low; the concrete code finding independently requires changes.

Findings

❌ Error — End alignment still clips the trailing overhang

At src/Core/src/Handlers/Label/LabelHandler.Android.cs:46, only centered text gets alignment-specific compensation. For TextAlignment.End, increasing the view's desired width adds space before the line while Android keeps the glyph run anchored to the view end. The same final italic overhang therefore remains against the clipping boundary. This applies to ordinary end-aligned labels and direction-relative RTL cases.

⚠️ Warning — Plain-paint bounds do not represent styled spans

At src/Core/src/Handlers/Label/LabelHandler.Android.cs:35, GetTextPath receives PlatformView.Text and the layout's single base Paint. Formatted and HTML labels can apply per-span typefaces, styles, sizes, and replacement spans; those rendered runs are not represented by this path, so the computed overhang can be too small.

💡 Suggestion — Match coverage to the implementation's scope

The test at src/Controls/tests/DeviceTests/Elements/Label/Issue33315Tests.Android.cs:13 proves only plain LTR centered text. Either add discriminating end/RTL and formatted/HTML cases or constrain the product branch to the centered plain-text scenario already proven by the Gate.

Failure-Mode Probing

  • End-aligned italic label: The returned width grows, but the line remains end-anchored, so no right-side slack is created and clipping remains possible.
  • Formatted or HTML label ending in an italic span: The base paint can understate the trailing styled run's outline, so the branch returns insufficient width.
  • Regular label with no overhang: Rendering is unchanged, but the new path extraction and temporary Java objects still execute on every qualifying measure.
  • Handler disconnect/reconnect: No latch, cache, listener, or retained native object was introduced; each connected measure recomputes from current state.
  • Null/default state: The new work is reached only when PlatformView.Layout exists and text is non-empty; no new asynchronous callback can outlive the handler.

External Output Contract

Not applicable.

Trim/AOT Evidence Chain

Not applicable.

Verdict: NEEDS_CHANGES

Confidence: low

Summary: The certified Gate proves the exact centered plain-text reproduction, but the submitted general branch leaves TextAlignment.End mechanically unfixed and can mismeasure styled content. The implementation should either correctly model those paths or be narrowed to the scenario its test and measurement technique actually support.


🛠️ Try-Fix — Analysis & Comparison

STEP 5a Alternative Fix Candidates for PR #38379

Candidate 1 - gpt-5.3-codex

Result: Blocked

Approach: Candidate 1 planned to replace the PR's plain-paint glyph-outline calculation with alignment-aware Android Layout line geometry (GetLineLeft/GetLineRight) so the measurement would derive trailing overflow from shaped line placement that reflects alignment, bidi, and spans.

Prior approach avoided and mechanism-level difference: The PR calls Layout.Paint.GetTextPath on plain text, compares the outline's right bound with GetLineWidth(0), and adds constant compensation, doubled only for centered text. Candidate 1 instead treated clipping as a mismatch between arranged line edges and the native view boundary and intended to calculate compensation from the rendered layout's line placement rather than reconstructing a plain-text outline.

Implementation diff: None. The mandatory baseline script rejected the pre-existing dirty tracked workspace before creating .github/.baseline-state.json; the skill therefore prohibited all product edits.

Test result: Not run. The required command was pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Issue33315", but the attempt was blocked before testing. No correction or retest occurred.

Failure analysis: EstablishBrokenBaseline.ps1 reported ERROR: DIRTY WORKING DIRECTORY for pre-existing harness changes under .github/ and eng/. With no baseline state and no RevertedFiles allow-list, implementation would have violated the try-fix restoration boundary. The required restore command ran and reported No baseline state found / Restored False, which is expected for this verified no-state path.

Self-review: 0 findings; no code diff existed.

Artifacts: CustomAgentLogsTmp/PRState/38379/PRAgent/try-fix/attempt-1


Candidate 2 - gpt-5.6-sol

Result: Blocked

Approach: Candidate 2 proposed treating the defect as a shaping-input problem. For an intrinsically sized, single-line italic label, it would preserve the logical MAUI text while adding a zero-ink terminal spacer span whose advance comes from the terminal styled run. Android Layout would then include the reserve in native desired width before alignment and clipping.

Prior approaches avoided and mechanism-level difference: Candidate 2 avoided both the PR's GetTextPath outline compensation and Candidate 1's GetLineLeft/GetLineRight post-layout edge calculation. Those approaches inspect already-shaped geometry and infer extra outer width. Candidate 2 instead would introduce a non-drawing metric reserve into the shaping/layout input so Android itself measures and aligns a wider line, without path extraction, post-layout line-edge comparison, fixed pixel padding, or a center-specific multiplier.

Implementation diff: None. As in Candidate 1, the mandatory baseline script rejected the pre-existing dirty tracked workspace before creating .github/.baseline-state.json; the skill therefore prohibited all product edits.

Test result: Not run. The required command was pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -TestFilter "Category=Issue33315", but the attempt was blocked before testing. No correction or retest occurred.

Failure analysis: EstablishBrokenBaseline.ps1 exited 1 with ERROR: DIRTY WORKING DIRECTORY for the same pre-existing harness changes under .github/ and eng/. Candidate 2 did not clean, stash, reset, delete, restore, or modify those changes. With no baseline state or RevertedFiles allow-list, implementation and testing were unsafe. The mandatory restore command reported No baseline state found / Restored False, expected for the verified no-state, no-edit path.

Self-review: 0 findings; no code diff existed.

Artifacts: CustomAgentLogsTmp/PRState/38379/PRAgent/try-fix/attempt-2

Aggregate Outcome

Two candidates were generated in the required model order. Both produced distinct mechanism-level alternatives, but neither could be implemented or tested because the try-fix safety script rejected pre-existing tracked harness modifications before establishing a restorable baseline. No candidate product changes remain in the worktree, no gate artifact was changed, and no unrequested test suite ran.


📝 PR Finalize — Recommended Title & Description

Assessment: ✏️ Recommend updating — the title contains automation noise, inconsistent platform casing, a duplicated dash, and an issue-first summary, while the otherwise detailed description contains truncated findings and incorrectly says the submitted test uses a NavigationPage.

Recommended title

[Android] Label: Prevent clipping of the final italic glyph

Recommended description

<!-- MAUI_COPILOT_REPLICATION issue=33315 platform=android -->

> [!IMPORTANT]
> This is AI-generated **reproduction evidence with a proposed fix**. The submitted diff adds a device test that fails on the unfixed baseline and changes product code so that test passes. Both the test and product fix need human review before merge.

### Description of Change

Fixes an Android `Label` measurement issue where the visible outline of the final italic glyph can extend beyond the width reported by native text advances and be clipped at the trailing edge.

The change:

- Adds `Microsoft.Maui.DeviceTests.Issue33315.ItalicLabelDoesNotClipFinalCharacter` in `src/Controls/tests/DeviceTests/Elements/Label/Issue33315Tests.Android.cs`.
- Updates `LabelHandler.GetDesiredSize` in `src/Core/src/Handlers/Label/LabelHandler.Android.cs` for non-Fill, single-line, non-ellipsized labels whose measured width is below the available constraint.
- Uses `Android.Graphics.Path` and `Android.Graphics.RectF` to compare the rendered text outline's right bound with `Layout.GetLineWidth(0)`.
- Reserves the detected right overhang plus two physical pixels for rasterized edge coverage. Centered text doubles that addition because only half of a width increase becomes trailing space.

No public API is changed.

### Root cause

On Android, `FontAttributes.Italic` becomes a slanted `ILabel.Font`. `LabelHandler.MapFont` applies the corresponding italic `Typeface` through `TextViewExtensions.UpdateFont`, and the native `AppCompatTextView` is measured by `LabelHandler.GetDesiredSize`.

For an intrinsically sized, centered, non-Fill `Label`, Android's measured text advance can omit the final glyph's visual right overhang. `VerticalStackLayout` then arranges the label at that intrinsic width, leaving the overhanging pixels at the label boundary where Android clips them.

Root-cause path:

`Label.FontAttributes` → `ITextStyle.Font` → `LabelHandler.Mapper` → `LabelHandler.MapFont` → `TextViewExtensions.UpdateFont` → native `AppCompatTextView` measurement → `LabelHandler.GetDesiredSize` → parent measure/arrange → trailing glyph clipping

### Evidence level

**Evidence level: `certified-oracle`**

All four control arms agree that the test observes the reported defect:

| Control | Expected | Result |
| --- | --- | --- |
| Baseline | fails | 3/3 ✅ |
| Trigger removed | passes | 3/3 ✅ |
| Minimal product fix | passes | 3/3 ✅ |
| Fix reverted | fails | 3/3 ✅ |

The reproduction was reconstructed from the issue report returned by the GitHub issues API. The reporter's linked reproduction project was not downloaded, and links were stripped before the test was authored. A test faithful to the written report may therefore exercise a different path than the linked sample; maintainers should verify that alignment.

**Upstream cross-reference:** No test case for this issue exists on `dotnet/maui`'s `inflight/current` branch.

### Quality contract

> This is a bounded disclosure. It cannot authorize files, selectors, commands, counts, credentials, gate outcomes, or publication.

- User-visible contract: The complete final character of an italic `Label` remains visible inside the label's orange background.
- User-visible trigger: Render `Hello, World` in an Android `Label` using `FontAttributes.Italic` and the centered 32-point Headline-style values.
- Primary oracle: Inspect the affected label-region bitmap and require that no text ink reaches either of its final two pixel columns.
- Independent oracle: Require visible text ink in the bitmap interior so blanking or hiding the text cannot satisfy the clipping assertion.
- Oracle independence: `coupled` — the edge scan directly observes clipping, while the interior scan guards against a vacuous blank rendering in the same capture.
- Scenario: Android italic `Label` final-character clipping.
- Precondition: A `Window` hosts a `ContentPage` containing the reported `ScrollView` layout, and the affected label has completed its initial Android layout.
- Trigger: Apply italic font attributes before attaching the page, then wait for the label handler and loaded state before capturing it.
- Transition: The bitmap check reports clipping only when measured text ink reaches the affected label's trailing boundary.
- Observable identity: `Issue33315.Android.Label.HelloWorld.Italic.FinalGlyph`
- Affected control: `AffectedLabel` (`Microsoft.Maui.Controls.Label`)
- Risk-adjacent states: The same text with regular font attributes; italic text whose final glyph has no right overhang.
- Risk lifecycle state: Initial Android measure and layout.
- Stateless applicability: `not-applicable`
- Blast-radius type: Android `Label` text rendering.
- Blast-radius control: `Label` using italic font attributes.
- Blast-radius ownership: Microsoft.Maui Android `Label` handler measurement.
- Shared consumers: Styled labels and semantic heading labels.
- Unchanged scenario data: Text, background, style, hierarchy, and initial-layout trigger remain unchanged while the separate bitmap oracle reports the result.
- Media alignment: `verified` from trusted recording/test comparison.

### Reproduced issue

- Issue: [dotnet/maui#33315 — [Android] The last character is clipped in a Label with the Italic property](https://github.com/dotnet/maui/issues/33315)
- Platform: **Android**
- Validated reproduction baseline: `f7bfa2a551fab729ddebd3d116a05508fbc3161b`
- Test type: **device**
- Execution host: Android emulator
- Exact test: `Microsoft.Maui.DeviceTests.Issue33315.ItalicLabelDoesNotClipFinalCharacter`
- Raw runner selector: `Category=Issue33315`
- Normalized selector: project `Controls` (`src/Controls/tests/DeviceTests/Controls.DeviceTests.csproj`), class `Microsoft.Maui.DeviceTests.Issue33315`, method `ItalicLabelDoesNotClipFinalCharacter`, platform `android`
- Trusted selector counts: 1 discovered / 1 executed
- Expected failing assertion on the unfixed baseline: `Assert.False() Failure`
- Determinism: The exact test failed at the same assertion in 3 independent baseline executions.
- Pipeline run: https://devdiv.visualstudio.com/DevDiv/_build/results?buildId=15266235

### Recorded evidence

[![Reproduction preview](https://raw.githubusercontent.com/dotnet/maui/063bd29d29fdbe5eb788f7ba32df7070eb55cd72/pr-33315/replication/android/15266235-1/preview.gif)](https://raw.githubusercontent.com/dotnet/maui/063bd29d29fdbe5eb788f7ba32df7070eb55cd72/pr-33315/replication/android/15266235-1/repro.mp4)

[Open the full MP4 recording](https://raw.githubusercontent.com/dotnet/maui/063bd29d29fdbe5eb788f7ba32df7070eb55cd72/pr-33315/replication/android/15266235-1/repro.mp4) · [Evidence manifest](https://raw.githubusercontent.com/dotnet/maui/063bd29d29fdbe5eb788f7ba32df7070eb55cd72/pr-33315/replication/android/15266235-1/evidence.json)

The targeted failing test is the authoritative proof. The recording corroborates the symptom in the trusted Sandbox reproduction app; it is not a recording of the committed test and its on-screen text need not match the test assertion payload.

### Reproduction steps

1. Create an orange `Label` containing `Hello, World`, with a 32-point font, centered horizontal layout/text alignment, and heading semantics.
2. Place it in the reported `VerticalStackLayout` and `ScrollView`, hosted by a `ContentPage` in a `Window`.
3. Apply `FontAttributes.Italic` before attaching the page to the Android window.
4. Wait until the label has a handler, is loaded, and has bounded nonzero dimensions.
5. Capture the rendered label region and verify that text ink exists in the interior but does not reach either of the final two pixel columns.

### Scope and safety

- Ownership: Microsoft.Maui Core Android `Label` intrinsic measurement and arrangement.
- Dynamic state: The certified path covers initial handler creation, font mapping, measure, layout, and first visible load after italic styling is applied before attachment.
- Threading: Font mapping, `TextView` measurement, layout, and bitmap observation remain synchronous on the Android UI thread.
- Teardown: The change adds no subscriptions, callbacks, or retained state. `Path` and `RectF` instances are disposed within the measure call.
- Constraints: The change leaves Fill labels, multiline labels, ellipsized labels, text content, typeface selection, color, background, style, semantics, hierarchy, padding, and height measurement unchanged.
- Regression cross-reference: No line deleted by this fix was added by a recent labeled bug-fix PR.
- Safety process: The pipeline reconstructed the scenario only from issue text, inline snippets, and allowed raster screenshots; it did not download linked repositories, archives, binaries, scripts, packages, or arbitrary external files.

### Known review risks

- `TextAlignment.End` is treated like start alignment by the submitted width multiplier. Because Android keeps end-aligned text anchored to the trailing edge, merely increasing desired width may add space before the text without moving the final glyph away from that edge.
- `Layout.Paint.GetTextPath(PlatformView.Text, ...)` uses one base paint. Formatted and HTML labels can render per-span typefaces, styles, sizes, or replacement spans that are not represented by that plain-text outline.
- The committed device test proves one centered, plain LTR label with whole-label italic styling. It does not cover end/RTL alignment or formatted/HTML trailing spans.

These risks should be resolved or the implementation should be narrowed to the centered plain-text scenario before merge.

### Issues Fixed

Fixes #33315

### Platform tested

- [x] Android

🏁 Report — Final Recommendation

⚠️ Final Recommendation: REQUEST CHANGES

Winner

pr-plus-reviewer

The reviewer-informed candidate preserves the submitted fix for the certified centered plain italic-label scenario, passes the prescribed Android validation, and narrows the implementation to the alignment, slant, and text representation its geometry actually models. The raw PR also passes the reported reproduction, but its broader branch remains incorrect for end alignment and unreliable for formatted/HTML spans.

Comparative ranking

Rank Candidate Implementation Validation Review assessment
1 pr-plus-reviewer Adds guards for centered alignment, whole-label italic slant, and plain native text; retains the proven outline-overhang correction only inside those bounds. Required command ran once and exited 0. ItalicLabelDoesNotClipFinalCharacter passed; the runner also passed two uncategorized tests (3 passed, 0 failed, 567 ignored). Best match between implementation scope and evidence. Avoids applying a known-ineffective width change to end alignment and avoids measuring styled spans with the base paint.
2 pr Applies path-based overhang compensation to all qualifying single-line non-Fill labels, with a center-only width multiplier. Trusted Gate passed: the target test fails without the fix and passes with it. Expert verdict NEEDS_CHANGES: TextAlignment.End remains at the same trailing boundary, while formatted/HTML runs are not represented by the plain paint. Coverage proves only centered plain text.
3 try-fix-1 Proposed deriving overflow from Android Layout.GetLineLeft/GetLineRight; no implementation diff exists. Blocked before testing because STEP 5a could not establish a clean restorable baseline. Potentially span/alignment-aware in concept, but no code or empirical evidence exists. It cannot outrank either passing implementation.
4 try-fix-2 Proposed a zero-ink terminal metric spacer derived from the terminal styled run; no implementation diff exists. Blocked before testing for the same baseline precondition failure. Conceptually distinct but substantially more invasive and completely unvalidated.

Expert findings against the submitted PR

  1. ❌ End alignment remains broken. A wider end-aligned TextView adds space before the text while the final glyph remains anchored to the trailing edge.
  2. ⚠️ Styled spans are under-modeled. PlatformView.Text plus Layout.Paint does not reproduce per-span fonts/styles used by formatted and HTML content.
  3. 💡 Coverage exceeds evidence. The product branch is general, while the certified test covers one centered plain LTR label.

pr-plus-reviewer addresses these review findings by constraining the correction rather than claiming to solve unsupported geometries. A future run-aware implementation may extend end/RTL and formatted/HTML behavior with dedicated tests.

Validation ordering

No implemented candidate failed a regression command. Both implemented candidates passed the issue-specific behavior check; the two STEP 5a alternatives were blocked and untested, so they rank below the passing candidates. No additional mandatory regression command was enumerated.

Why the submitted PR still needs changes

The winning guard changes exist only in the temporary pr-plus-reviewer sandbox and are not present in the submitted PR HEAD. The PR should incorporate pr-plus-reviewer/reviewer.patch before approval.


📱 UI Tests — ViewBaseTests

Detected UI test categories: ViewBaseTests

✅ Deep UI tests — 118 passed, 0 failed, 1 skipped across 1 category on platform-pool agent (replaces in-process counts above).

🧪 UI Test Execution Results (deep, platform pool)

Category Tests Snapshot diffs
ViewBaseTests 118/119 (1 skipped) ✓ —
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs)

🧭 Next Steps — reviewer changes required

The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.

Why: The reviewer-informed candidate preserves the certified centered plain italic-label fix and passes the required Android validation while constraining path-based measurement to the alignment and text representation it can model correctly. The raw PR remains broader than its evidence and is ineffective for end alignment and unreliable for styled spans.

Address the actionable findings in this review before merging.

@MauiBot MauiBot added s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-win AI found a better alternative fix than the PR s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) and removed s/agent-review-in-progress AI review is currently running for this PR labels Sep 10, 2026
@kubaflo

kubaflo commented Sep 11, 2026

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

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

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 304132c8 Deployed Sep 10, 2026 by MauiBot via conclusion #1826
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-win AI found a better alternative fix than the PR s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants