Skip to content

[draft] Android XML Views reference implementation + shared E2E matrix#286

Draft
Alex Freas (akfreas) wants to merge 68 commits into
mainfrom
android-xml-views-reference-impl
Draft

[draft] Android XML Views reference implementation + shared E2E matrix#286
Alex Freas (akfreas) wants to merge 68 commits into
mainfrom
android-xml-views-reference-impl

Conversation

@akfreas
Copy link
Copy Markdown
Collaborator

@akfreas Alex Freas (akfreas) commented May 25, 2026

Adds a legacy XML Views reference implementation for the Android SDK and re-runs the existing UI Automator suite against both the Compose impl and the new Views impl in parallel, mirroring the iOS swiftui/uikit + matrix CI pattern.

What's in this PR

  • com.contentful.optimization.views SDK adapterOptimizationManager, OptimizedEntryView, ScreenTracker, TrackingRecyclerView. Thin wrapper around the existing core API; no personalization or tracking logic lives here.
  • implementations/android-sdk/shared — new com.android.library module hosting AppConfig, ContentfulFetcher, EventStore, MockPreviewContentfulClient, RichText. Both :compose and :views depend on it.
  • implementations/android-sdk/compose — renamed from :app. Pure rename, no behavior change.
  • implementations/android-sdk/views — new com.android.application module with applicationId com.contentful.optimization.app.views. Mirrors every Compose screen/component with XML layouts and a per-View setTestTag helper that exposes the same kebab-case test ids to UI Automator.
  • Shared UI Automator suite parameterized by APP_PACKAGEAppLauncher reads the target package from InstrumentationRegistry.getArguments(); defaults to the Compose app so IDE runs keep working.
  • CI matrix — split the e2e-android-sdk job into a build-once stage (compose, views, uitests APKs) and a matrix-fanout stage that boots one emulator per app and runs the same uitests against each.

Test-id contract for XML Views

UI Automator's By.res("identify-button") matches AccessibilityNodeInfo.viewIdResourceName. Compose's testTagsAsResourceId = true writes the test tag verbatim there; XML android:id can't contain hyphens. The Views path uses an AccessibilityDelegateCompat that overrides viewIdResourceName to the kebab tag — and clears view.id to View.NO_ID first, because View.onInitializeAccessibilityNodeInfoInternal re-populates the field from Resources.getResourceName(mID) and clobbers the override on the CI x86_64 emulator. The helper also mirrors the test tag onto contentDescription so the shared TestHelpers.findElement By.res → By.desc fallback resolves the same selector.

Status

  • Compose leg: 56/58 passing in CI. The two failures (testScenario5ResettingSingleVariantOverrideRestoresVariant and testScenario3ResettingAudienceOverrideRestoresVariant in PreviewPanelOverridesTests) are pre-existing flakes that also fail on the final-mobile-sdk-fixes branch this PR builds on — not caused by anything in this PR.
  • Views leg: 56/58 passing in CI. Failures: testScenario3... (same pre-existing flake as Compose) plus testTracksEntryViewEventsForVisibleEntries in AnalyticsTests — the first entry's view-tracking component event isn't surfacing on CI's slow x86_64 headless emulator even though events for other entries do; passes locally on arm64. Worth a follow-up investigation.

Pre-existing CI gaps this PR also fixes

The Android CI job has been red on final-mobile-sdk-fixes for unrelated reasons that were masked by commit 6a596527 (the silent-pass guard). Bringing CI back to green required:

  • Drop set -o pipefail from the emulator-runner script — the action invokes the script via /usr/bin/sh -c, which errors with Illegal option -o pipefail and terminates the script before any test runs.
  • Drop the manual adb shell settings put global window_animation_scale 0 lines — the action's disable-animations: true already does this and the redundant adb commands exit non-zero on the freshly-booted API 35 image under the action's bash -e wrapper.
  • Use a workspace-relative android-apks/ directory for the build→matrix artifact handoff so actions/upload-artifact@v7 keys the in-zip paths off the LCA correctly.

🤖 Generated with Claude Code

Alex Freas (akfreas) and others added 30 commits May 22, 2026 13:19
…single @contentful/optimization-js-bridge under packages/universal that builds one shared src/index.ts into both native UMD bundles
…merged @contentful/optimization-js-bridge package
…imization-js-bridge so the JS bridge matches the iOS and Android native SDKs that already call them
… adapter on top of the existing core API so XML/Views-based Android apps can integrate the SDK without Compose dependencies
…ibrary module under com.contentful.optimization.shared so both the Compose reference impl and the upcoming XML Views impl can consume the same AppConfig, ContentfulFetcher, EventStore, MockPreviewContentfulClient, and RichText
…e and reroute every script, gradle build path, IDE run config, and CI workflow line to the new module so it sits as a sibling of the upcoming :views XML reference impl, mirroring the iOS swiftui/uikit pair
…se impl screen-for-screen, using OptimizedEntryView, ScreenTracker, and OptimizationManager from the new SDK views adapter and exposing every Compose testTag through an AccessibilityNodeInfoCompat.setViewIdResourceName helper so the shared UI Automator suite resolves the same selectors against both apps
…arguments so the same UI Automator suite can drive both the Compose reference impl and the new XML Views reference impl, defaulting to the Compose impl when no override is passed
…ws, build:apks) and teach scripts/run-e2e.sh to pick the gradle module + APK file + am instrument APP_PACKAGE arg from the APP_PACKAGE env var so the same script drives either reference impl
…ompose, views, and uitests APKs and a matrix-fanout stage that boots one emulator per app and runs the same UI Automator suite against each with APP_PACKAGE forwarded as an instrumentation argument, mirroring the iOS SwiftUI/UIKit dual-target CI pattern
…st-id contract, the APP_PACKAGE instrumentation argument, and the new com.contentful.optimization.views SDK adapter in the AGENTS.md files
…g AnalyticsTests against both apps: wait for client.isInitialized before driving consent/page so the profile state flow actually advances, memoize the OptimizedEntryView view-tracking controller on its (entry, personalization) tuple so personalization re-emissions don't reset the dwell timer, and tighten the entry content padding so the analytics block sits inside the viewport like it does in Compose; also fetch entries exactly once per Activity instead of re-rendering on every profile state change
…ity.onCreate after the reset-prefs check so cold launches with reset=true do not race against the bridge loading the persisted profile, gate the Views identify and reset button handlers behind client.isInitialized so a quick test tap before the bridge boots no longer no-ops, attach the preview-panel floating action button from the post-init coroutine to mirror OptimizationRoot's previewPanel config, derive the nested entry test tag from the resolved entry's sys.id so personalization-variant ids surface like they do on the Compose side, and force-stop both reference impls at the start of scripts/run-e2e.sh so local back-to-back runs against different apps cannot leak stale focused windows into the next instrumentation run
…nside LiveUpdatesTestActivity.loadEntry, force-close the preview panel on every entry into LiveUpdatesTestActivity so a prior testTogglePreviewPanel cannot leave shouldLive=true sticky for the next test's locked slots, and suppress the AccessibilityNodeInfoCompat ACTION_CLICK from TestTagging.setTestTag so the shared TestHelpers.tapElement helper's accessibility-then-coordinate double click does not double-fire onClick listeners on stock Android Buttons the way it would have to on Compose's debounced gesture handler
…x artifact handoff so actions/upload-artifact v7 keys the in-zip paths off the LCA correctly and the matrix leg's adb install lines find compose-debug.apk and views-debug.apk where they expect them
…rom the matrix script — the emulator-runner action already does this via disable-animations: true and the duplicate adb commands exit non-zero under the action's bash -e wrapper on the freshly-booted API 35 image, terminating the script before any apk install or instrument run
…okes it via /usr/bin/sh which errors out with 'Illegal option -o pipefail' on the first line, terminating the script before any apk install or instrument run. The grep checks on the test-output log already detect instrumentation failures regardless of pipe-status propagation
…too in setTestTag, so UiAutomator's By.desc fallback finds buttons in the CI x86_64 headless emulator config where the AccessibilityDelegate-driven viewIdResourceName override appears to not always propagate to the accessibility node tree on time
…n setTestTag right before installing the AccessibilityDelegate, so the framework's onInitializeAccessibilityNodeInfoInternal can't populate viewIdResourceName from Resources.getResourceName(mID) and clobber our delegate's setViewIdResourceName(testTag) before UiAutomator's By.res reads it on the CI x86_64 emulator. Compose's testTagsAsResourceId works because Compose nodes have no underlying XML id to conflict; this brings the Views path to the same precondition
…init renderer at declaration, mark afterEach as void, replace Object.create(null) cast with a type-predicate factory
…thResolvers in createDeferred, void the beforeEach/afterEach calls, init renderer at declaration, replace Object.create(null) cast with a type-predicate factory
…l and 0.4 ratio to named constants, destructure mock.mock.calls all the way through, init renderer at declaration, void the beforeEach/afterEach calls
… test: void the beforeEach call, extract the inner subscriber-notify forEach callback to a named arrow, capture the original destroy via Reflect.get with an explicit this-typed annotation to silence both prefer-destructuring and unbound-method
…eact-web test: add a void-this reference inside the mock destroy method to acknowledge class-methods-use-this, switch indexed array access to computed-key object destructuring
…r tests so they actually validate the mocked destroy/screen/states.eventStream shape at runtime instead of returning true unconditionally; the lint-clean type narrowing now matches what the runtime check claims
…ollView — the e2e Detox suite preview-panel-overrides.test.js was changed in 95d6afc to match the panel scroll container by that id but the SDK side of the rename never landed on final-mobile-sdk-fixes, so all 8 scenarios were failing with 'No views in hierarchy found matching: view.getTag() is preview-panel-scroll'
…eanup-order test that broke the CI Format Check; the cherry-picked lint commit was line-wrapped one way and prettier wants it the other way
Alex Freas (akfreas) and others added 30 commits May 25, 2026 21:07
…r tests so they actually validate the mocked destroy/screen/states.eventStream shape at runtime instead of returning true unconditionally; the lint-clean type narrowing now matches what the runtime check claims
…ollView — the e2e Detox suite preview-panel-overrides.test.js was changed in 95d6afc to match the panel scroll container by that id but the SDK side of the rename never landed on final-mobile-sdk-fixes, so all 8 scenarios were failing with 'No views in hierarchy found matching: view.getTag() is preview-panel-scroll'
…eanup-order test that broke the CI Format Check; the cherry-picked lint commit was line-wrapped one way and prettier wants it the other way
…view panel and update Detox scenario 6 to tap by testID
…via sdk.page in the demo app so the override interceptor can be exercised end-to-end from Detox
…and reset taps in PreviewPanelOverridesTests scenario 3, because deactivation drops the audience to the bottom of the sorted list and UiAutomator's findObject returns a stale accessibility node from the now-off-screen position whose ACTION_CLICK silently no-ops on the Compose recomposed segment — verified locally by [bridge-sync] resetAudienceOverride firing after the scroll where previously only overrideAudience fired
…CI x86_64 Compose recomposition surfaces faster than local arm64 by reading every visibleBounds inside a try-catch and falling back to display extents — the stale-handle scenario 3 hit on the previous CI run originated from el.visibleBounds in the scroll loop, not from the click itself
…iebreak in sortAudiences and the mirrored isQualified-first ordering in the RN AudienceSection) so an audience keeps its row when its override flips, removing the spurious accessibility-tree staleness that the test framework hit when a deactivation demoted the audience-toggle off-screen between two taps — buildPreviewModel.test.ts updated to assert the new alphabetical-only ordering, the iOS and Android JS bridge UMD bundles regenerated from the merged source
…verridesTests and refresh the scenario 2 singleClick comment — both were narrowly justified by sortAudiences demoting an overridden audience off-screen between two taps; the panel now sorts by name only and that demotion no longer happens
…us-Compose accessibility-cache pollution that surfaces when multiple scenarios share a single am instrument session — waitAndTap now resolves the element AFTER the 1.5s idle wait (so the captured UiObject2 is not handed across the recomposition window in which Compose invalidates the underlying node id), forceStop polls 'pidof' until the app process is actually gone instead of relying on the kernel-side teardown lagging Thread.sleep(500), and relaunchClean bookends launchApp with two waitForIdle ticks so the new activity's accessibility tree has settled before the next findObject runs
…iebreak in sortAudiences and the mirrored isQualified-first ordering in the RN AudienceSection) so an audience keeps its row when its override flips, removing the spurious accessibility-tree staleness that the test framework hit when a deactivation demoted the audience-toggle off-screen between two taps — buildPreviewModel.test.ts updated to assert the new alphabetical-only ordering, the iOS and Android JS bridge UMD bundles regenerated from the merged source
…verridesTests and refresh the scenario 2 singleClick comment — both were narrowly justified by sortAudiences demoting an overridden audience off-screen between two taps; the panel now sorts by name only and that demotion no longer happens
…us-Compose accessibility-cache pollution that surfaces when multiple scenarios share a single am instrument session — waitAndTap now resolves the element AFTER the 1.5s idle wait (so the captured UiObject2 is not handed across the recomposition window in which Compose invalidates the underlying node id), forceStop polls 'pidof' until the app process is actually gone instead of relying on the kernel-side teardown lagging Thread.sleep(500), and relaunchClean bookends launchApp with two waitForIdle ticks so the new activity's accessibility tree has settled before the next findObject runs
…Guard rules — rename the prose ZiplineContextManager to QuickJsContextManager to match the actual class, update README/AGENTS scope and architecture sections to name QuickJS via io.github.dokar3:quickjs-kt, and drop the defensive -keep class app.cash.zipline.** rule since the module has no Zipline dependency
…ct2.scroll on the inner preview-panel-list scrollable instead of raw device.swipe coordinates — a coordinate swipe past the inner scroll's limit bubbles up to the ModalBottomSheet container as a drag-to-dismiss and tears the panel out of the accessibility tree entirely, observed via diagnostic snapshots showing previewPanel=false mid-scroll, and a semantic scroll on the inner scrollable Compose node stays within it; the loop now does a stale-resilient findObject+visibleBounds (Compose recomposition staled the handle between the two reads and the previous bounds==null code treated that as 'not found' and swiped past the target), accepts partial overlap with the panel viewport instead of demanding full containment (clipped-edge rows are still tappable), and scrolls DOWN then UP if needed so we can recover when the panel entered already past the target — and TestHelpers.waitForElement now includes the selector in its timeout AssertionError so future failures point at the missing selector instead of an opaque message
…trument grind through every remaining @before for its full 20-30s waitForElement timeout — AndroidJUnitRunner has no built-in early-exit, and the CI grep on /tmp/test-output.log for FAILURES only fires after the whole suite finishes, so one root-cause failure in an early test class burned ~25 minutes of GitHub Actions runner time and hit the 45-minute job ceiling before being cancelled; the fix streams am instrument output through an awk filter that, on the first 'Error in test' or 'Process crashed' line, prints the line, runs adb shell am force-stop com.contentful.optimization.uitests to kill the instrumentation host so the remote am instrument -w exits, then exits awk with code 1 to collapse the local pipeline — applied symmetrically in .github/workflows/main-pipeline.yaml and implementations/android-sdk/scripts/run-e2e.sh (the latter gated behind FAIL_FAST=true with an env-var escape hatch for the diagnose-a-later-test case), and the post-run grep now also matches 'Error in test' so the aborted-mid-stream path where the FAILURES summary line is never written still exits non-zero
…ML line because the reactivecircus/android-emulator-runner action's parseScript() in src/script-parser.ts does rawScript.trim().split(/\r\n|\n|\r/) and then runs each non-comment, non-empty resulting line as a separate sh -c — which silently broke the previous multi-line pipeline ('adb shell am instrument ... \' on one line, '| tee ... \' on the next, '| awk ...' on the third) into three independent commands; am instrument ran standalone with its stdout going to the GHA console, the | tee and | awk lines were syntax-error no-ops, /tmp/test-output.log was never written, fail-fast never triggered, and the suite kept running through every later test class's @before timeouts; the new single-line form keeps the tee + awk pipeline intact, and the awk script body uses ;-separated statements instead of newlines so it stays one line
…boot the x86_64 Pixel 7 + api 35 image pays on every job — add an actions/cache@v4 step keyed on api-level/arch/target/profile/device-name pointing at ~/.android/avd plus ~/.android/adb*, run a snapshot-generating emulator-runner step gated on the cache-miss path (headless boot, no audio, no boot animation, -no-snapshot-save deliberately OMITTED so the snapshot gets persisted at shutdown for the cache step to pick up), then flip the actual test-run emulator-runner to force-avd-creation: false and add -no-snapshot-save to its emulator-options so the cached snapshot survives whatever dirty state the suite leaves behind
…te cold boot the x86_64 Pixel 7 + api 35 image pays on every job — add an actions/cache@v4 step keyed on api-level/arch/target/profile/device-name pointing at ~/.android/avd plus ~/.android/adb*, run a snapshot-generating emulator-runner step gated on the cache-miss path (headless boot, no audio, no boot animation, -no-snapshot-save deliberately OMITTED so the snapshot gets persisted at shutdown for the cache step to pick up), then flip the actual test-run emulator-runner to force-avd-creation: false and add -no-snapshot-save to its emulator-options so the cached snapshot survives whatever dirty state the suite leaves behind"

This reverts commit d85979e.
…roid-xml-views-reference-impl

# Conflicts:
#	.github/workflows/main-pipeline.yaml
#	implementations/android-sdk/uitests/src/main/kotlin/com/contentful/optimization/uitests/tests/PreviewPanelOverridesTests.kt
… instead of launching PreviewPanelActivity as a separate Activity — the prior FAB.setOnClickListener { startActivity(PreviewPanelActivity::class.java) } left UiAutomator unable to resolve the panel's accessibility nodes while the consuming MainActivity still held window focus during the OPEN transition, so every shared UI test that called By.text("Preview Panel") after waitAndTap(preview-panel-fab) timed out at 20s even though uiautomator dump showed the TextView in the tree (15 of 16 PreviewPanelTests + PreviewPanelOverridesTests scenarios failed in views/, all green in compose/ which never launches PreviewPanelActivity at all and instead uses PreviewPanelOverlay's in-place ModalBottomSheet); the new PreviewPanelActivity.addFloatingButton adds a fullscreen ComposeView to activity.window.decorView whose content is an InActivityPreviewPanelOverlay composable hosting both the FAB and the on-click ModalBottomSheet that renders PreviewPanelContent, matching the compose-impl architecture node-for-node, and OptimizationManager.attachPreviewPanel's return type changes from ImageButton? to View? to reflect the new host (PreviewPanelActivity itself is kept for backwards compatibility with any consumer that historically launched it directly but the SDK no longer routes the FAB through it)
…eference impls when APP_PACKAGE is unset (or set to "all"/"both") so a single local invocation mirrors the CI e2e-android-sdk matrix's compose + views legs — the previous default of APP_PACKAGE=com.contentful.optimization.app meant local devs only exercised the compose impl and the views impl's UI-automator coverage drifted unnoticed; the new main() resolves apps_to_run from the env var, build_apks now runs :compose:assembleDebug :views:assembleDebug :uitests:assembleDebug in a single Gradle invocation (the extra :assembleDebug is cheap against daemon startup and removes a per-impl Gradle re-invocation for the all path), and run_for_app handles the per-iteration force_stop_other_apps + install_apks + run_tests with a per-impl TEST_LOG=test-results-${APP_MODULE}.log so a follow-on iteration doesn't clobber the previous app's log
…device.click() fallback when the accessibility ACTION_CLICK already fired — the prior accessibility-click + 100ms + device.click sequence undid the action whenever the first tap morphed the button in place at the same screen position (e.g., LiveUpdatesTests' Identify button became Reset and the coordinate click then flipped isIdentified back to false, hanging the suite on the 'identified-status = Yes' wait), and drop the now-redundant performAccessibilityAction(ACTION_CLICK) no-op override in views/setTestTag that was only there to suppress the duplicate fire (with single-tap semantics it instead returned true without doing anything, so the views fallback path skipped the coordinate click and the button never received the tap, breaking setUp on default-personalization)
…et-all AlertDialog confirm button a unique selector and waiting for the dialog to dismiss before closing the panel — the prior confirmButton was a Material3 TextButton with Text("Reset") inside, which UI Automator could only target by By.text("Reset") and non-deterministically matched the panel's per-row reset-variant-* / reset-audience-* 'Reset' labels below the dialog instead, and even when the dialog did dismiss, closePanel's pressBack raced the dialog's dismissal and consumed back on the still-attached dialog window so the bottom sheet stayed open over the activity's now-modal-blocked entries (visible entry-text-* tags: []); the confirm button is now a clickable Text with contentDescription = 'reset-all-confirm' applied to the same node that owns the onClick (matching PreviewActionButton's proven pattern — placing the contentDescription on a TextButton modifier produced a separate non-merging semantic node above the clickable that UI Automator's accessibility-click forwarded to the AlertDialog root instead of the button), and the test now polls for the dialog body text ('This will clear all manual overrides...') to disappear before pressBack so the sheet dismissal isn't racing the dialog teardown
… combines a JUnit Timeout with withLookingForStuckThread enabled and a TestWatcher that dumps the UI hierarchy and a screenshot to /sdcard/test-failures on any failure — without a per-test timeout a single hung waitForElement (e.g. a wedged JS bridge reply or a UI Automator selector that never resolves) produces no Error in test or Process crashed line, so the workflow's awk fail-fast has nothing to match and am instrument -w blocks until the 45-minute job budget runs out (observed on run 26530969618 views matrix entry); the rule is added to all 10 active test classes (skipping the @ignore'd ExtendedViewTrackingTests) and its TestTimedOutException is emitted by AndroidJUnitRunner as Error in testFoo(...): TestTimedOutException which the existing awk pattern already matches, so the suite aborts within ~60s of any wedge instead of dragging out the full job and the failure context for the wedged test is on the device for the workflow to adb pull
…ut --kill-after=30 1200 and adb pull /sdcard/test-failures plus an adb logcat -d dump to /tmp inline after the awk pipeline (preserving the pipeline's exit code via e=$?; …; exit $e) so a wedged adb or a JUnit Timeout-rule deadlock can't burn the full 45-minute job budget and so per-test failure captures (UI hierarchy XML + screenshot from PerTestRule) and the device logcat are pulled to the runner before reactivecircus/android-emulator-runner kills the emulator at script-step end — the cleanup MUST stay on the same physical YAML line as the test pipeline because the action's parseScript splits the script block on every newline and runs each line as a separate sh -c, so a follow-up cleanup line would never run when the test line exits non-zero; the failure-handler step now also tails logcat and lists /tmp/test-failures, and the artifact upload now includes /tmp/logcat.log and /tmp/test-failures/ so the artifact has enough context to debug a hang or timeout without re-running the suite
…oidJUnitRunner streams machine-parseable INSTRUMENTATION_STATUS_CODE lines as each test starts and finishes instead of buffering the entire human-readable summary (dots, Error in test lines, OK (N tests) / FAILURES!!! footer) until end-of-suite — without -r the awk fail-fast never sees per-test progress and a single hung @before produces zero output to the runner until the outer timeout 1200 SIGTERMs the pipeline (observed on run 26534799046 views matrix entry, where the test command produced no streamed output for the full 20-minute timeout window and the only 'Error in testTracksEntryViewEventsForVisibleEntries' line that appeared was am instrument's flush-on-kill artifact, not a real failure detection); awk now matches /^INSTRUMENTATION_STATUS_CODE:[[:space:]]+-[12]$/ (the -2=errored / -1=assumption-failed exit codes AndroidJUnitRunner emits after each failing test), the post-grep that fails the step on missing OK is replaced by a check for the terminal INSTRUMENTATION_CODE line (emitted only when am instrument completes — absent on SIGTERM/hang), and a per-test failure is now surfaced within ~1s of the test marking itself failed so the PerTestRule 60s timeout actually aborts the suite at the 60s mark instead of being invisible behind am instrument's end-of-suite flush
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant