Detect wedged AVD display/input in avd_setup.sh

Add a detect-and-retry health check in `avd_setup.sh` so emulators that
boot into an offscreen-`DefaultTaskDisplayArea` / no-input-focus state
fail setup (`exit 1`) and are automatically restarted by
`AndroidVirtualDeviceApi.start()`'s existing 3-attempt retry loop.

Note: this is a detect-and-retry mitigation, not a root-cause fix for
the upstream emulator snapshot mismatch or Android WindowManager /
SurfaceFlinger race described below.

Root cause & evidence:

* Trigger + exact detach mechanism (proven via Perfetto Winscope
  `android.surfaceflinger.transactions` trace on `android_36_google_apis_x64`,
  corroborated against live CI bot repro
  https://ci.chromium.org/b/8664274452676453745):
  1. The AVD snapshots were recorded under `swiftshader_indirect` and
     resumed under `swangle_indirect`. On every boot, `wm density 400`
     triggers `SIGABRT` (`drawRenderNode called on a context with no
     surface!`) in `com.android.systemui` and `NexusLauncher`, forcing
     both to restart.
  2. When `NexusLauncher` recreates its activity, `TaskFragmentComponent`
     enqueues a transition using `InstantRemoteTransition`
     (`TaskFragmentComponent.kt`). When Launcher is concurrently
     becoming visible, WM promotes `DefaultTaskDisplayArea` and `Task=1`
     into that transition (`startTransaction` reparents
     `DefaultTaskDisplayArea` onto `Transition Root:
     DefaultTaskDisplayArea`; `finishTransaction` and
     `cleanupTransaction` reparent it back to `AppZoomOut:2:14` and
     remove the `Transition Root`).
  3. `RemoteTransitionHandler` delegates `startTransaction` to Launcher,
     where `InstantRemoteTransition.startAnimation()` calls async
     `startT.apply()` and immediately invokes
     `finishCB.onTransitionFinished()` (~3 ms later). SystemUI then
     calls `finishTransaction.apply()` and `system_server` calls
     `cleanupTransaction.apply()` in the same 16.6 ms VSync frame,
     across three different processes' default `applyToken` queues (with
     no shared `applyToken` or `TransactionBarrier`).
  4. SurfaceFlinger's `TransactionHandler::flushPendingTransactionQueues`
     iterates `mPendingTransactionQueues` (`std::unordered_map` keyed by
     `applyToken`) in hash order rather than `post_time` order. When
     SystemUI's `finishTransaction` executes before Launcher's earlier
     `startTransaction`, `finishTransaction` removes `Transition Root`
     and `startTransaction` then reparents `DefaultTaskDisplayArea` onto
     that already-removed root, permanently orphaning
     `DefaultTaskDisplayArea` (and all launcher and app tasks) under
     SurfaceFlinger's `Offscreen Hierarchy`.
  5. Because `Wallpaper`, `StatusBar`, and `Taskbar` are siblings
     outside `DefaultTaskDisplayArea`, the home screen stays non-black
     and `KeyguardStateMonitor` reports `mIsShowing=false` (so neither a
     home-screen `screencap` check nor a keyguard check detects it).
     Because `SurfaceFlinger` does not forward offscreen layers to
     `InputDispatcher`, live `dumpsys input` reports
     `FocusedWindows: <none>` (`result='NO_WINDOW'`), even while WM's
     Java `mCurrentFocus` still reports the launcher/app as focused.
     Immersive Flutter tests hide the system bars and render `0 Layers`
     (Skia Gold digest `5ba6df7acef516f7dab78587cf30ce20`) until the
     first `rotateToLandscape()` transition reparents
     `DefaultTaskDisplayArea` back onto Display 0.

* CI timing corroboration (~890 prod + 297 try builds):
  - When `InputDispatcher` has no focused window during setup, the
    second `input keyevent 82` in `avd_setup.sh` hits two 5s timeouts
    (+10.0s), pushing `avd_setup.sh` from ~10-14s to 19.9-26.4s.
  - All 6 confirmed solid-black (`5ba6df7a`) CI builds across all 3
    `android_engine_*_tests` shards hit 19.9-26.4s:
      * Vulkan try: https://ci.chromium.org/b/8664295659415895361 (20.8s)
                    https://ci.chromium.org/b/8664306896219693489 (20.8s)
      * OpenGLES prod: https://ci.chromium.org/b/8664325833093913329 (19.9s)
                       https://ci.chromium.org/b/8664923504954633793 (20.0s)
      * HCPP prod: https://ci.chromium.org/b/8665198771094913953 (26.4s)
                   https://ci.chromium.org/b/8664847067461433681 (20.8s)
  - Zero clean builds reached >= 18s (and 0/422 clean GCE `led` boots
    exceeded 14.0s).

Changes:

* Keep the display awake (`svc power stayon true`), send
  `input keyevent KEYCODE_WAKEUP`, and run `wm dismiss-keyguard || true`.
* Poll up to 5 times (3s apart) inside `verify_display_and_input_ready`
  (with `set +x` in a subshell to keep healthy setup logs compact):
  - `check_dtda_offscreen`: flags only when an exact
    `DefaultTaskDisplayArea#<id>` node appears under `Offscreen
    Hierarchy` and no `DefaultTaskDisplayArea#<id>` node is attached
    under `Layer Hierarchy` (ignores non-DTDA offscreen leashes and
    stale offscreen DTDAs when a live DTDA is attached).
  - `check_input_focus_missing`: parses only the live
    `Input Dispatcher State:` block (stopping before any subsequent
    column-0 header such as `Input Dispatcher State at time of last
    ANR:`) and checks for `FocusedWindows: <none>`.
  - Fails open with a one-line skip notice if an expected header is
    absent (e.g., API 31's legacy `Offscreen Layers:` format).
* If still unhealthy across all 5 polls, print concise SurfaceFlinger,
  InputDispatcher, and Keyguard diagnostics and `exit 1` so `api.py`
  retries with a fresh emulator start.

Test:
* `./recipes.py test run --filter android_virtual_device` (12/12 pass).
* 62/62 shell unit tests (`gawk` and `mawk`, `LC_ALL=C` and `C.UTF-8`)
  against captured wedged/healthy dumps, stale offscreen DTDA with live
  DTDA attached, `Surface(name=DefaultTaskDisplayArea)` leash names,
  stale ANR focus blocks, CRLF, and fail-open skip logging.
* Live `led` validation on `luci.flutter.try` using this exact patch:
  - End-to-end retry test (forced attempt-1 `exit 1` -> `api.py` kill &
    restart -> attempt-2 pass on poll 1/5):
    https://ci.chromium.org/b/8664241072124189921
  - All 4 CI AVD configs across `flutter/flutter` and `flutter/packages`
    (all passed on poll 1/5):
    * API 31: https://ci.chromium.org/b/8664241071424110881 (visible SF
      skip log; InputDispatcher check active)
    * API 35: https://ci.chromium.org/b/8664241070783629761
    * API 36: https://ci.chromium.org/b/8664241070007678561
    * API 37: https://ci.chromium.org/b/8664241069363698865

Related: https://github.com/flutter/flutter/issues/185070
Related: https://github.com/flutter/flutter/pull/197263
Change-Id: Ia57fc69afef70bbb2b90486b8f606c6ee61ab1c4
Reviewed-on: https://flutter-review.googlesource.com/c/recipes/+/87682
Commit-Queue: Jenn Magder <magder@google.com>
Reviewed-by: Jenn Magder <magder@google.com>
Commit-Queue: Gray Mackall <mackall@google.com>
diff --git a/recipe_modules/android_virtual_device/resources/avd_setup.sh b/recipe_modules/android_virtual_device/resources/avd_setup.sh
index 38ce408..759cfde 100644
--- a/recipe_modules/android_virtual_device/resources/avd_setup.sh
+++ b/recipe_modules/android_virtual_device/resources/avd_setup.sh
@@ -81,6 +81,118 @@
     echo "Emulator is now available"
 }
 
+# Checks whether DefaultTaskDisplayArea is orphaned under SurfaceFlinger's
+# 'Offscreen Hierarchy' with no active DefaultTaskDisplayArea attached under
+# 'Layer Hierarchy'.
+# Exit codes: 0 = wedged (offscreen only), 1 = healthy, 2 = header absent (fail-open).
+function check_dtda_offscreen() {
+    awk '
+        { sub(/\r$/, "") }
+        /^Layer Hierarchy[[:space:]]*$/ { section = "layer"; next }
+        /^Offscreen Hierarchy[[:space:]]*$/ { section = "offscreen"; saw_offscreen = 1; next }
+        section != "" && (/^[[:space:]]*$/ || /^Display /) { section = "" }
+        section != "" {
+            line = $0
+            gsub(/[^ -~]/, "", line)
+            if (line ~ /^[[:space:]|+-]*DefaultTaskDisplayArea#[0-9]+/) {
+                if (section == "layer") on_display = 1
+                if (section == "offscreen") offscreen = 1
+            }
+        }
+        END {
+            if (!saw_offscreen) exit 2
+            if (offscreen && !on_display) exit 0
+            exit 1
+        }
+    '
+}
+
+# Checks whether the live 'Input Dispatcher State:' block reports
+# 'FocusedWindows: <none>', strictly stopping before any subsequent column-0
+# header (such as 'Input Dispatcher State at time of last ANR:').
+# Exit codes: 0 = wedged (no focus), 1 = healthy, 2 = header absent (fail-open).
+function check_input_focus_missing() {
+    awk '
+        { sub(/\r$/, "") }
+        /^Input Dispatcher State:[[:space:]]*$/ { in_live = 1; saw_live = 1; next }
+        in_live && /^[^[:space:]]/ { in_live = 0 }
+        in_live && /^[[:space:]]*FocusedWindows:[[:space:]]*<none>[[:space:]]*$/ { no_focus = 1 }
+        END {
+            if (!saw_live) exit 2
+            exit(no_focus ? 0 : 1)
+        }
+    '
+}
+
+# Polls display and input health so transient post-restart states can settle,
+# failing (exit 1 -> api.py retry) only if a wedged state persists across all polls.
+function verify_display_and_input_ready() {
+    local adb=${1}
+    (
+        set +x
+        local max_polls=5
+        local poll_sleep=3
+        local sf_dump=""
+        local input_dump=""
+        local sf_rc=1
+        local input_rc=1
+        local dtda_offscreen=0
+        local focus_missing=0
+
+        for ((i=1; i<=max_polls; i++)); do
+            dtda_offscreen=0
+            focus_missing=0
+            sf_dump=$(${adb} -s emulator-5554 shell dumpsys SurfaceFlinger 2>/dev/null || true)
+            input_dump=$(${adb} -s emulator-5554 shell dumpsys input 2>/dev/null || true)
+
+            sf_rc=0
+            printf '%s\n' "${sf_dump}" | check_dtda_offscreen || sf_rc=$?
+            if [[ ${sf_rc} -eq 0 ]]; then
+                dtda_offscreen=1
+            elif [[ ${sf_rc} -eq 2 && ${i} -eq 1 ]]; then
+                echo "SurfaceFlinger health check skipped (no Offscreen Hierarchy header)."
+            fi
+
+            input_rc=0
+            printf '%s\n' "${input_dump}" | check_input_focus_missing || input_rc=$?
+            if [[ ${input_rc} -eq 0 ]]; then
+                focus_missing=1
+            elif [[ ${input_rc} -eq 2 && ${i} -eq 1 ]]; then
+                echo "InputDispatcher health check skipped (no live Input Dispatcher State header)."
+            fi
+
+            if [[ ${dtda_offscreen} -eq 0 && ${focus_missing} -eq 0 ]]; then
+                echo "Display and input health check passed (poll ${i}/${max_polls})."
+                exit 0
+            fi
+
+            echo "Display/input health check poll ${i}/${max_polls} unhealthy (dtda_offscreen=${dtda_offscreen}, focus_missing=${focus_missing})."
+            if [[ ${i} -lt ${max_polls} ]]; then
+                sleep ${poll_sleep}
+            fi
+        done
+
+        echo "ERROR: Emulator display/input remained wedged after ${max_polls} polls (dtda_offscreen=${dtda_offscreen}, focus_missing=${focus_missing})."
+        echo "--- SurfaceFlinger DefaultTaskDisplayArea / Offscreen diagnostics ---"
+        printf '%s\n' "${sf_dump}" | awk '
+            { sub(/\r$/, "") }
+            /^Offscreen Hierarchy[[:space:]]*$/ { in_off = 1; print; next }
+            in_off && (/^[[:space:]]*$/ || /^Display / || /^Layer Hierarchy/) { in_off = 0 }
+            in_off || /DefaultTaskDisplayArea/ { print }
+        ' | head -n 60 || true
+        echo "--- Live Input Dispatcher State focus diagnostics ---"
+        printf '%s\n' "${input_dump}" | awk '
+            { sub(/\r$/, "") }
+            /^Input Dispatcher State:[[:space:]]*$/ { in_live = 1; print; next }
+            in_live && /^[^[:space:]]/ { in_live = 0 }
+            in_live && /FocusedDisplayId|FocusedApplications|FocusedWindows|FocusRequests|displayId=0, name=/ { print }
+        ' | head -n 40 || true
+        echo "--- KeyguardServiceDelegate diagnostics ---"
+        ${adb} -s emulator-5554 shell dumpsys window policy 2>/dev/null | grep -E 'KeyguardServiceDelegate|KeyguardStateMonitor|showing=|mIsShowing=|mWakefulness=' | head -n 20 || true
+        exit 1
+    )
+}
+
 # path to the adb executable
 adb=${1}
 
@@ -123,6 +235,13 @@
 
 ${adb} shell input keyevent 82
 
+# Keep display awake and dismiss keyguard before handing off to tests.
+${adb} shell svc power stayon true
+${adb} shell input keyevent KEYCODE_WAKEUP
+${adb} shell wm dismiss-keyguard || true
+
+verify_display_and_input_ready "${adb}"
+
 print_device_list "${adb}"
 
 # clear exit signal for the LUCI ci.