diff --git a/.github/workflows/collection-native-tests.yml b/.github/workflows/collection-native-tests.yml index 82bfb97e..7c78f4aa 100644 --- a/.github/workflows/collection-native-tests.yml +++ b/.github/workflows/collection-native-tests.yml @@ -4,20 +4,78 @@ on: inputs: candidate_run_id: description: GitHub Actions run containing a candidate APK built from this exact SHA - required: true + required: false artifact_name: description: Artifact containing one standalone APK with localhost HTTP enabled for the fixture API - required: true + required: false permissions: contents: read actions: read +defaults: + run: + shell: bash jobs: + validate: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Test native input and state assertion guards + run: python3 -m unittest discover -s apps/collection/test/native -p '*_test.py' + - env: + RUN_ID: ${{ inputs.candidate_run_id }} + ARTIFACT: ${{ inputs.artifact_name }} + run: | + if [[ -n "$RUN_ID" || -n "$ARTIFACT" ]]; then + [[ "$RUN_ID" =~ ^[0-9]+$ ]] && test -n "$ARTIFACT" + fi + build: + needs: validate + if: inputs.candidate_run_id == '' && inputs.artifact_name == '' + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 24.6.0 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - run: npm ci + working-directory: apps/collection + - name: Build standalone synthetic candidate from a fresh native project + env: + LOVAT_DISPOSABLE_BUILD: "1" + run: | + mkdir -p apps/collection/.maestro/results + bash apps/collection/scripts/build-native-candidate.sh 2>&1 | tee apps/collection/.maestro/results/build-full.log + - uses: actions/upload-artifact@v4 + with: + name: collection-native-candidate-${{ github.sha }} + path: apps/collection/candidate/ + if-no-files-found: error + retention-days: 14 + - uses: actions/upload-artifact@v4 + if: always() + with: + name: collection-native-build-logs-${{ github.sha }} + path: apps/collection/.maestro/results/ + retention-days: 14 android: + needs: [validate, build] + if: ${{ always() && needs.validate.result == 'success' && (needs.build.result == 'success' || (needs.build.result == 'skipped' && inputs.candidate_run_id != '' && inputs.artifact_name != '')) }} runs-on: ubuntu-24.04 timeout-minutes: 30 steps: - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + if: inputs.candidate_run_id == '' + with: + name: collection-native-candidate-${{ github.sha }} + path: candidate - name: Verify candidate source revision + if: inputs.candidate_run_id != '' env: GH_TOKEN: ${{ github.token }} CANDIDATE_RUN_ID: ${{ inputs.candidate_run_id }} @@ -26,6 +84,7 @@ jobs: candidate_sha=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$CANDIDATE_RUN_ID" --jq .head_sha) test "$candidate_sha" = "$GITHUB_SHA" - uses: actions/download-artifact@v4 + if: inputs.candidate_run_id != '' with: name: ${{ inputs.artifact_name }} run-id: ${{ inputs.candidate_run_id }} @@ -43,10 +102,24 @@ jobs: curl --fail --location https://github.com/mobile-dev-inc/maestro/releases/download/cli-2.12.1/maestro.zip -o /tmp/maestro.zip unzip -q /tmp/maestro.zip -d "$RUNNER_TEMP" echo "$RUNNER_TEMP/maestro/bin" >> "$GITHUB_PATH" + - name: Enable hardware acceleration + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + sudo udevadm settle + sudo chmod a+rw /dev/kvm + mkdir -p apps/collection/.maestro/results + stat /dev/kvm | tee apps/collection/.maestro/results/kvm.txt + test -r /dev/kvm && test -w /dev/kvm - uses: reactivecircus/android-emulator-runner@v2 with: api-level: 35 arch: x86_64 + cores: 2 + ram-size: 2048M + disable-linux-hw-accel: false + emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -no-snapshot -camera-back none -accel on script: bash apps/collection/scripts/test-native-candidate.sh candidate - uses: actions/upload-artifact@v4 if: always() diff --git a/apps/collection/.gitignore b/apps/collection/.gitignore index 1dcf5730..3e498c3d 100644 --- a/apps/collection/.gitignore +++ b/apps/collection/.gitignore @@ -39,3 +39,8 @@ dependency-audit.json test-report/ .maestro/results/ + +/candidate/ + +# Native test helper bytecode +__pycache__/ diff --git a/apps/collection/.maestro/end-match.yaml b/apps/collection/.maestro/end-match.yaml new file mode 100644 index 00000000..50c36b9d --- /dev/null +++ b/apps/collection/.maestro/end-match.yaml @@ -0,0 +1,4 @@ +appId: com.frc8033.lovatcollection +--- +- tapOn: "End match" +- tapOn: "End match" diff --git a/apps/collection/.maestro/enter-game.yaml b/apps/collection/.maestro/enter-game.yaml new file mode 100644 index 00000000..20c0d59d --- /dev/null +++ b/apps/collection/.maestro/enter-game.yaml @@ -0,0 +1,8 @@ +appId: com.frc8033.lovatcollection +--- +- tapOn: "Scout this match" +- extendedWaitUntil: + visible: "Start position Hub" + timeout: 20000 +- waitForAnimationToEnd: + timeout: 5000 diff --git a/apps/collection/.maestro/offline-restart.yaml b/apps/collection/.maestro/offline-restart.yaml index fac41322..29cc574c 100644 --- a/apps/collection/.maestro/offline-restart.yaml +++ b/apps/collection/.maestro/offline-restart.yaml @@ -1,14 +1,5 @@ appId: com.frc8033.lovatcollection --- -- tapOn: "Scout this match" -- extendedWaitUntil: - visible: "Start position Hub" - timeout: 20000 -- tapOn: "Start position Hub" -- tapOn: "Start match" -- tapOn: "Undo" -- tapOn: "End match" -- tapOn: "End match" - scrollUntilVisible: element: text: "Submit" diff --git a/apps/collection/.maestro/reconnect.yaml b/apps/collection/.maestro/reconnect.yaml index e87c4177..1fd41ccb 100644 --- a/apps/collection/.maestro/reconnect.yaml +++ b/apps/collection/.maestro/reconnect.yaml @@ -12,8 +12,8 @@ appId: com.frc8033.lovatcollection - tapOn: text: ".*1234.*" - assertNotVisible: "Upload" -- back -- back +- tapOn: "Back" +- tapOn: "Back" - tapOn: "settings" - assertVisible: "Settings" - openLink: "lovat-collection://history" diff --git a/apps/collection/.maestro/record-match.yaml b/apps/collection/.maestro/record-match.yaml new file mode 100644 index 00000000..35b3af17 --- /dev/null +++ b/apps/collection/.maestro/record-match.yaml @@ -0,0 +1,31 @@ +appId: com.frc8033.lovatcollection +--- +# Shared installed-app flow; Android dismisses its system hint before this flow. +- tapOn: "Start position Hub" +- assertVisible: + text: "Start position Hub" + selected: true +- assertVisible: + text: "Start match" + enabled: true +- tapOn: + text: "Start match" + enabled: true +- assertNotVisible: "Start position Hub" +- assertVisible: + text: "Undo" + enabled: false +- tapOn: "Open outpost actions" +- tapOn: "Intake from outpost" +- assertVisible: + text: "Undo" + enabled: true +- tapOn: "Undo" +- assertVisible: + text: "Undo" + enabled: false +- tapOn: "Open outpost actions" +- tapOn: "Intake from outpost" +- assertVisible: + text: "Undo" + enabled: true diff --git a/apps/collection/README.md b/apps/collection/README.md index d1146cde..1d9ef9da 100644 --- a/apps/collection/README.md +++ b/apps/collection/README.md @@ -106,6 +106,12 @@ Tests execute real Zustand stores, AsyncStorage persistence, report serializatio `.maestro/` provides installed-app onboarding/deep-link, offline recording, process restart, reconnect/History retry and Settings checks. `scripts/test-native-android.sh` starts a synthetic fixture API, disables airplane connectivity and stops the API so an ADB tunnel cannot hide offline failures, then restarts the app without clearing storage. It verifies that the retried lifecycle preserves one UUID and produces one successful submission. Run it against an installed standalone APK with localhost HTTP permitted for the fixture; it never changes the production app network policy or auth behavior. Install Maestro CLI `cli-2.12.1` and Android platform tools first. -The manual **Collection native candidate tests** workflow accepts an APK artifact run/name and requires that artifact's source SHA to match the selected workflow revision. A failed native flow fails the workflow and retains JUnit/logs. It is a candidate/release check, not a required PR test until Android build stability is proven (LVT-217). No cloud builds or releases are started by the test workflow. Use the existing `native-smoke-ios` EAS simulator profile for iOS candidates; run the same flows with a reachable local fixture, omitting Android airplane/ADB commands. iOS has no simulator airplane mode. +The manual **Collection native candidate tests** workflow can build a fresh standalone synthetic Android APK when both inputs +are empty, or accepts an APK artifact run/name and requires that artifact's source SHA to match the selected workflow revision. A failed native flow fails the workflow and retains JUnit/logs. It is a candidate/release check, not a required PR test until Android build stability is proven (LVT-217). The test build runs locally on GitHub with template test signing and loopback-only +fixture networking; it does not start cloud builds or publish releases. Use the existing `native-smoke-ios` EAS simulator profile for iOS candidates; run the same flows with a reachable local fixture, omitting Android airplane/ADB commands. iOS has no simulator airplane mode. Before a release, the release owner must run the candidate checks and record the build SHA/version, then manually verify camera permission grant/deny, physical-device multi-code QR transfer, background/restart persistence, and the iOS system/browser permission prompts. Unit/component tests do not claim to validate native camera, signing, installation or permissions. Native flows require a candidate device/build and are documented separately from the automated Pages suite. Related: LVT-259/260/261/262 and LVT-273. + +The owner-assigned acceptance matrix and candidate evidence template are in +[manual release checks](docs/manual-release-checks.md). Unexecuted physical-device +and iOS simulator checks remain pending. diff --git a/apps/collection/app/home.tsx b/apps/collection/app/home.tsx index bcea4971..206139db 100644 --- a/apps/collection/app/home.tsx +++ b/apps/collection/app/home.tsx @@ -184,6 +184,10 @@ export default function Home() { > diff --git a/apps/collection/docs/manual-release-checks.md b/apps/collection/docs/manual-release-checks.md new file mode 100644 index 00000000..dc09ae5f --- /dev/null +++ b/apps/collection/docs/manual-release-checks.md @@ -0,0 +1,91 @@ +# Collection manual release checks + +Related: LVT-217 and LVT-262. Status: **prepared; device acceptance pending**. +Jack Shim (Collection issue assignee) owns the acceptance record. Name the release +operator and reviewer for each candidate. Run on a disposable Android device and +an iOS 27 device with a sandbox team; use only fictional scouting information. +An unexecuted/blocked check is pending and prevents mobile release approval. + +## Evidence record + +Copy into LVT-262 for each candidate: + +- Operator / reviewer / UTC date: **pending** +- Source SHA / build workflow or EAS run URL: **pending** +- Version / Android versionCode or iOS buildNumber: **pending** +- Signed candidate artifact URL / SHA-256 (`shasum -a 256 `): **pending** +- Device model / OS / previous installed version: **pending** +- Sandbox API origin / synthetic team code (no credentials): **pending** +- Native Android run URL / iOS simulator evidence: **pending** +- Each row's result, redacted evidence and linked defect: **pending** +- Release decision / owner sign-off: **pending** + +The CI APK is a test-only x86_64 standalone release-mode build with generated +loopback network access. It uses the template's test signing and is not a store +candidate. Its hash and source revision are retained with test results. Testing +that APK does not certify the signed mobile artifact distributed to users. + +## Device acceptance matrix + +Record pass/fail separately for Android and iOS; do not combine them into one +unchecked statement. + +| Check | Expected result | Android / iOS evidence | +| --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ---------------------- | +| Clean install from normal signed distribution channel | Correct version/build launches and onboarding works; iOS 27 does not crash on launch | Pending / Pending | +| Upgrade from previous supported version with one saved old report | Settings and report remain readable; migration preserves report identity and data | Pending / Pending | +| Set sandbox API with `lovat-collection://set-url?u=`; enroll synthetic team | Correct sandbox origin/team/scouter/event are shown | Pending / Pending | +| Record a complete report while airplane mode is enabled | Save succeeds locally; upload failure is visible and recoverable | Pending / Pending | +| Background, force-terminate and relaunch without clearing app storage | Saved report remains in History with the same UUID and event data | Pending / Pending | +| Reconnect and retry from History, then reopen/retry again | Exactly one successful server report; UUID is unchanged; no duplicate successful submission | Pending / Pending | +| Open Settings, change event/scouter/server, then relaunch | Expected selections persist and saved reports stay associated with their original data | Pending / Pending | +| Display a multi-part synthetic report QR and scan with Dashboard on a second physical device | Dashboard reconstructs one identical report; partial/repeated chunks recover safely | Pending / Pending | +| Dashboard scanner camera denied, retried, then granted via system settings | Permission denial is recoverable and transfer succeeds after grant | Pending / Pending | +| Scan unrelated/invalid QR with Dashboard | Clear error; existing report data is preserved | Pending / Pending | +| Phone lock/background during QR display, then reopen | QR remains readable and represents the same saved report | Pending / Pending | + +Collection displays QR codes; camera permission belongs to the receiving +Dashboard scanner. Do not invent a Collection camera-permission pass. Record the +receiving Dashboard version/build and OS alongside each transfer result. Keep +Auth0 login checks in Dashboard's LVT-265/266 acceptance record. + +## Automated candidate run and iOS handoff + +Dispatch **Collection native candidate tests** at the exact candidate SHA with +both inputs empty to generate and test a fresh standalone Android APK. Or provide +both the build run ID and artifact name for an externally built standalone APK; +the workflow rejects a different source revision. Never provide only one input. +The Android runner verifies airplane/offline, real process restart, saved History, +reconnect/retry and one preserved UUID. Failures remain failures, with diagnostics. +Do not use a personal device: bootstrap intentionally clears app storage. + +For iOS, build the existing `native-smoke-ios` EAS simulator profile with Xcode 27 +from that same source SHA, record the run URL, version and artifact hash, install +on a disposable simulator, and run `.maestro/bootstrap.yaml`, +`.maestro/enter-game.yaml`, `.maestro/record-match.yaml`, `.maestro/end-match.yaml`, +`.maestro/offline-restart.yaml` and `.maestro/reconnect.yaml` in that order, +each in a separate Maestro invocation against the synthetic fixture +(`node test/native/fixture-api.mjs`). Stop the fixture before `enter-game.yaml` +and restart it before reconnect; iOS simulators have no airplane-mode API. +Retain Maestro JUnit/screenshots and the fixture submission ledger. This iOS +procedure is a pending operator check until its actual build/run evidence is +attached; a build profile alone is not a passed native test. Physical-device +rows above still apply after a simulator pass. + +On Android CI, `scripts/prepare-native-android.py` runs before the shared +`record-match.yaml` and `end-match.yaml` Maestro flows. It acknowledges only +Android's known first-use full-screen hint, identified by its Android package and +specific title/button resource IDs, then reads the active window again. It +retains the hint snapshot and rejects disabled or ambiguous confirmations. +Preparation requires the field to be enabled and Start to remain disabled. + +Android's `uiautomator dump` CLI waits for global idle and cannot reliably capture +the running match timer. It is used only during static pre-match preparation; +Maestro performs every timed recording, Undo, end-menu, offline and reconnect +assertion. Outpost intake exists in every phase, so the flow does not race the +real Auto timer. Failed idle capture cannot reuse an old snapshot. Each stage +retains its JUnit result and diagnostics. + +If CI cannot boot/install, attach its failure and run the same journey on a +physical test device. Record that separate result explicitly. Attach redacted +synthetic screenshots only; never publish real notes, strategy or login tokens. diff --git a/apps/collection/lib/collection/ui/GameAction.tsx b/apps/collection/lib/collection/ui/GameAction.tsx index c11b7ed3..f62a01df 100644 --- a/apps/collection/lib/collection/ui/GameAction.tsx +++ b/apps/collection/lib/collection/ui/GameAction.tsx @@ -6,6 +6,7 @@ import { useFieldRelativeDimensions } from "../useFieldRelativeDimensions"; export const GameAction = ({ onPress, + label, children, icon, color, @@ -16,6 +17,7 @@ export const GameAction = ({ iconSize, }: { onPress: () => void; + label?: string; children?: React.ReactNode; backgroundViewReplacement?: React.ReactNode; color: string; @@ -35,6 +37,8 @@ export const GameAction = ({ return ( { Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); onPress(); diff --git a/apps/collection/lib/collection/ui/GameViewTemplate.tsx b/apps/collection/lib/collection/ui/GameViewTemplate.tsx index 038988ac..dacf03e8 100644 --- a/apps/collection/lib/collection/ui/GameViewTemplate.tsx +++ b/apps/collection/lib/collection/ui/GameViewTemplate.tsx @@ -192,13 +192,15 @@ function GameViewOverlay({ overlay: boolean; setOverlay: (value: boolean) => void; }) { + // Remove the modal's native touch targets while it is closed. Opacity only + // changes painting; hidden controls should not remain over the playing field. + if (!overlay) return null; + return ( reportState.addEvent({ type: MatchEventType.Intake, @@ -45,6 +46,7 @@ export function NeutralZoneAutoIntakeAction() { })} > reportState.addEvent({ type: MatchEventType.Intake, diff --git a/apps/collection/lib/collection/ui/actions/OutpostAction.tsx b/apps/collection/lib/collection/ui/actions/OutpostAction.tsx index 0396786f..1b7da1c3 100644 --- a/apps/collection/lib/collection/ui/actions/OutpostAction.tsx +++ b/apps/collection/lib/collection/ui/actions/OutpostAction.tsx @@ -17,6 +17,7 @@ export function OutpostAction({ })} > setOverlay(true)} color="#C1C337" icon="flag" diff --git a/apps/collection/lib/lovatAPI/checkMatchExists.ts b/apps/collection/lib/lovatAPI/checkMatchExists.ts index ba13f16a..025a6ccc 100644 --- a/apps/collection/lib/lovatAPI/checkMatchExists.ts +++ b/apps/collection/lib/lovatAPI/checkMatchExists.ts @@ -67,7 +67,9 @@ export async function checkMatchExists( } catch (error) { if ( error instanceof TypeError || - (error instanceof Error && error.name === "AbortError") + (error instanceof Error && + (error.name === "AbortError" || + /^fetch failed(?::|$)/i.test(error.message))) ) { return { status: "offline" }; } diff --git a/apps/collection/scripts/build-native-candidate.sh b/apps/collection/scripts/build-native-candidate.sh new file mode 100755 index 00000000..cb560b05 --- /dev/null +++ b/apps/collection/scripts/build-native-candidate.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +# This creates generated native projects; use a fresh disposable checkout only. +test "${LOVAT_DISPOSABLE_BUILD:-}" = 1 +test ! -e android +export CI=1 EXPO_NO_DOTENV=1 EXPO_PUBLIC_API_URL=http://127.0.0.1:9877 +mkdir -p .maestro/results candidate +npx expo prebuild --platform android --no-install +# Test-only loopback access, applied to generated files, never app.json or EAS. +python3 - <<'PY' +from pathlib import Path +import xml.etree.ElementTree as ET +ns = 'http://schemas.android.com/apk/res/android' +ET.register_namespace('android', ns) +p = Path('android/app/src/main/AndroidManifest.xml') +tree = ET.parse(p) +app = tree.getroot().find('application') +app.set(f'{{{ns}}}networkSecurityConfig', '@xml/native_test_network_security') +app.set(f'{{{ns}}}usesCleartextTraffic', 'false') +tree.write(p, encoding='utf-8', xml_declaration=True) +p = Path('android/app/src/main/res/xml/native_test_network_security.xml') +p.parent.mkdir(parents=True, exist_ok=True) +p.write_text(''' + + + 127.0.0.1 + localhost + + +''') +PY +(cd android && ./gradlew :app:assembleRelease -PreactNativeArchitectures=x86_64 --no-daemon --stacktrace) 2>&1 | tee .maestro/results/build.log +cp android/app/build/outputs/apk/release/app-release.apk candidate/collection-native-test.apk +# A standalone bundle is required: a Metro-dependent development client cannot pass. +unzip -l candidate/collection-native-test.apk | grep 'assets/index.android.bundle' +git rev-parse HEAD > candidate/source-sha.txt +node -p 'JSON.stringify(require("./app.json").expo)' > candidate/app-config.json +sha256sum candidate/collection-native-test.apk > candidate/apk.sha256 diff --git a/apps/collection/scripts/prepare-native-android.py b/apps/collection/scripts/prepare-native-android.py new file mode 100644 index 00000000..5e3a75ae --- /dev/null +++ b/apps/collection/scripts/prepare-native-android.py @@ -0,0 +1,124 @@ +"""Prepare Android full-screen state before the real match timer starts. + +Android's first-use immersive hint can cover app controls. Resolve the active +window and acknowledge only that known hint before requiring app assertions. +""" + +from pathlib import Path +import re +import subprocess +import time +import xml.etree.ElementTree as ET + +APP_ID = "com.frc8033.lovatcollection" + + +def node_for(data, label, attribute): + nodes = [ + n for n in ET.fromstring(data).iter("node") + if n.get("package") == APP_ID and n.get(attribute) == label + ] + if len(nodes) != 1: + raise ValueError("Expected exactly one " + label + " " + attribute) + return nodes[0] + + +def point_for(node): + if node.get("enabled") != "true": + raise ValueError("Expected enabled control") + match = re.fullmatch( + r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", node.get("bounds", "") + ) + if match is None: + raise ValueError("Invalid control bounds") + x1, y1, x2, y2 = map(int, match.groups()) + if x2 <= x1 or y2 <= y1: + raise ValueError("Control has no visible area") + return ((x1 + x2) // 2, (y1 + y2) // 2) + + +def immersive_confirmation_point(data): + nodes = list(ET.fromstring(data).iter("node")) + titles = [n for n in nodes if n.get("package") == "android" + and n.get("resource-id") == "android:id/immersive_cling_title"] + if not titles: + return None + buttons = [n for n in nodes if n.get("package") == "android" + and n.get("resource-id") == "android:id/ok"] + if len(titles) != 1 or len(buttons) != 1: + raise ValueError("Ambiguous Android immersive confirmation") + return point_for(buttons[0]) + + +def assert_state(data, label, expected): + node = node_for(data, label, "content-desc") + for key, value in expected.items(): + if node.get(key) != value: + raise AssertionError(label + " expected " + key + "=" + value) + + +def run(): + out = Path(".maestro/results") + out.mkdir(parents=True, exist_ok=True) + suite = ET.Element("testsuite", name="Android pre-match preparation", failures="0") + # UI Automator's CLI requires global idle. Use it only before Start; Maestro + # owns all recording assertions once the real timer updates every second. + steps = [ + ("field-available", "Start position Hub", {"enabled": "true"}), + ("match-not-started", "Start match", {"enabled": "false"}), + ] + try: + for name, label, expected in steps: + case = ET.SubElement(suite, "testcase", name=name) + try: + deadline = time.monotonic() + 30 + while True: + # Never reuse an earlier dump when Android reports that it + # could not reach idle but still exits with status zero. + subprocess.run( + ["adb", "shell", "rm", "-f", "/sdcard/collection-menu.xml"], + check=True, timeout=10, + ) + subprocess.run( + ["adb", "shell", "uiautomator", "dump", "/sdcard/collection-menu.xml"], + check=True, timeout=20, + ) + data = subprocess.check_output( + ["adb", "exec-out", "cat", "/sdcard/collection-menu.xml"], + timeout=10, + ) + (out / (name + ".xml")).write_bytes(data) + confirmation = immersive_confirmation_point(data) + if confirmation is not None: + (out / "immersive-confirmation.xml").write_bytes(data) + if time.monotonic() >= deadline: + raise AssertionError("Android immersive hint did not dismiss") + print("Dismissing Android immersive education", flush=True) + subprocess.run( + ["adb", "shell", "input", "tap", *map(str, confirmation)], + check=True, timeout=10, + ) + # Read the active window again; never use the app's + # behind-dialog bounds as evidence that it is tappable. + continue + try: + assert_state(data, label, expected) + break + except (ValueError, AssertionError): + if time.monotonic() >= deadline: + raise + time.sleep(0.25) + print(name, "state assertion passed", flush=True) + except Exception as error: + suite.set("failures", "1") + ET.SubElement(case, "failure", message=str(error)).text = repr(error) + raise + finally: + suite.set("tests", str(len(suite.findall("testcase")))) + ET.ElementTree(suite).write( + out / "prepare-landscape.xml", encoding="utf-8", xml_declaration=True + ) + + +if __name__ == "__main__": + run() diff --git a/apps/collection/scripts/test-native-android.sh b/apps/collection/scripts/test-native-android.sh index a06d6652..623fa7cd 100644 --- a/apps/collection/scripts/test-native-android.sh +++ b/apps/collection/scripts/test-native-android.sh @@ -2,10 +2,45 @@ set -euo pipefail cd "$(dirname "$0")/.." mkdir -p .maestro/results +: > .maestro/results/ledger.jsonl fixture_pid="" cleanup() { + result=$? + trap - EXIT + printf '%s\n' "$result" > .maestro/results/exit-code.txt + adb logcat -d > .maestro/results/logcat.txt 2>&1 || true + adb shell getprop > .maestro/results/device.txt 2>&1 || true + adb exec-out screencap -p > .maestro/results/screenshot.png 2>/dev/null || true + if [[ "$result" -ne 0 ]]; then + # Preserve the failure above, then compare Android's own input path with + # Maestro's tap. This diagnostic never changes the original test result. + python3 - <<'PY' > .maestro/results/input-diagnostic.txt 2>&1 || true +from pathlib import Path +import re +import subprocess +import time +import xml.etree.ElementTree as ET +out = Path('.maestro/results') +def hierarchy(name): + subprocess.run(['adb', 'shell', 'uiautomator', 'dump', '/sdcard/collection-diagnostic.xml'], check=True, timeout=20) + data = subprocess.check_output(['adb', 'exec-out', 'cat', '/sdcard/collection-diagnostic.xml'], timeout=10) + (out / name).write_bytes(data) + return ET.fromstring(data) +tree = hierarchy('input-before.xml') +hub = next((n for n in tree.iter('node') if n.get('content-desc') == 'Start position Hub'), None) +if hub is not None and hub.get('selected') == 'false': + x1, y1, x2, y2 = map(int, re.findall(r'\d+', hub.get('bounds'))) + point = [str((x1 + x2) // 2), str((y1 + y2) // 2)] + print('Diagnostic Android input tap at', point, flush=True) + subprocess.run(['adb', 'shell', 'input', 'tap', *point], check=True, timeout=10) + time.sleep(1) + hierarchy('input-after.xml') + (out / 'input-after.png').write_bytes(subprocess.check_output(['adb', 'exec-out', 'screencap', '-p'], timeout=10)) +PY + fi adb shell cmd connectivity airplane-mode disable || true if [[ -n "$fixture_pid" ]]; then kill "$fixture_pid" 2>/dev/null || true; fi + exit "$result" } trap cleanup EXIT start_fixture() { @@ -20,19 +55,26 @@ start_fixture() { adb wait-for-device adb reverse tcp:9877 tcp:9877 start_fixture -maestro test --format junit --output .maestro/results/bootstrap.xml .maestro/bootstrap.yaml +maestro test --debug-output .maestro/results/bootstrap-debug --test-output-dir .maestro/results/bootstrap-debug --format junit --output .maestro/results/bootstrap.xml .maestro/bootstrap.yaml # Stop the fixture as well: an ADB reverse tunnel can survive airplane mode. kill "$fixture_pid" wait "$fixture_pid" || true fixture_pid="" adb shell cmd connectivity airplane-mode enable -maestro test --format junit --output .maestro/results/offline.xml .maestro/offline-restart.yaml +# Start a fresh driver session after each orientation transition, preserving +# the app process and report state. Keep selection/start assertions in the +# landscape session rather than relying on a successful input command. +maestro test --debug-output .maestro/results/enter-game-debug --test-output-dir .maestro/results/enter-game-debug --format junit --output .maestro/results/enter-game.xml .maestro/enter-game.yaml +python3 scripts/prepare-native-android.py +maestro test --debug-output .maestro/results/record-match-debug --test-output-dir .maestro/results/record-match-debug --format junit --output .maestro/results/record-match.xml .maestro/record-match.yaml +maestro test --debug-output .maestro/results/end-match-debug --test-output-dir .maestro/results/end-match-debug --format junit --output .maestro/results/end-match.xml .maestro/end-match.yaml +maestro test --debug-output .maestro/results/offline-debug --test-output-dir .maestro/results/offline-debug --format junit --output .maestro/results/offline.xml .maestro/offline-restart.yaml adb shell cmd connectivity airplane-mode disable start_fixture -maestro test --format junit --output .maestro/results/reconnect.xml .maestro/reconnect.yaml +maestro test --debug-output .maestro/results/reconnect-debug --test-output-dir .maestro/results/reconnect-debug --format junit --output .maestro/results/reconnect.xml .maestro/reconnect.yaml node --input-type=module - <<'JS' import {readFileSync} from 'node:fs'; -const entries=readFileSync('.maestro/results/ledger.jsonl','utf8').trim().split('\n').map(JSON.parse); +const entries=readFileSync('.maestro/results/ledger.jsonl','utf8').trim().split('\n').filter(Boolean).map(JSON.parse); const submitted=entries.filter(e=>e.path==='/collection/submit'||e.path==='/collection/scoutreports'); if(submitted.length!==1)throw new Error('Expected one successful synthetic report submission'); if(!entries.every(e=>e.uuid===submitted[0].uuid))throw new Error('Lifecycle/retry changed the report UUID'); diff --git a/apps/collection/scripts/test-native-candidate.sh b/apps/collection/scripts/test-native-candidate.sh index d1bddb56..443de030 100644 --- a/apps/collection/scripts/test-native-candidate.sh +++ b/apps/collection/scripts/test-native-candidate.sh @@ -3,5 +3,8 @@ set -euo pipefail candidate=$(find "${1:?Candidate artifact directory required}" -name '*.apk' -type f) test -n "$candidate" test "$(printf '%s\n' "$candidate" | wc -l)" -eq 1 +mkdir -p "$(dirname "$0")/../.maestro/results" +shasum -a 256 "$candidate" > "$(dirname "$0")/../.maestro/results/test-apk.sha256" +git rev-parse HEAD > "$(dirname "$0")/../.maestro/results/source-sha.txt" adb install "$candidate" bash "$(dirname "$0")/test-native-android.sh" diff --git a/apps/collection/test/jest/game-overlay-ui.test.tsx b/apps/collection/test/jest/game-overlay-ui.test.tsx new file mode 100644 index 00000000..cdfb1fa0 --- /dev/null +++ b/apps/collection/test/jest/game-overlay-ui.test.tsx @@ -0,0 +1,56 @@ +import React from "react"; +import { render, screen, userEvent } from "@testing-library/react-native"; +import { expect, jest, test } from "@jest/globals"; +import { GameViewTemplate } from "../../lib/collection/ui/GameViewTemplate"; +import { PreMatchActions } from "../../lib/collection/ui/actions/PreMatchActions"; +import { useReportStateStore } from "../../lib/collection/reportStateStore"; +import { useTeamStore } from "../../lib/storage/userStores"; +import { meta } from "./fixtures"; +import { MatchEventType } from "../../lib/collection/MatchEventType"; +import { MatchEventPosition } from "../../lib/collection/MatchEventPosition"; + +jest.mock("@react-native-menu/menu", () => ({ MenuView: () => null })); +jest.mock("../../lib/training/TrainingReadyButton", () => ({ + TrainingReadyButton: () => null, +})); + +test("closed outpost actions leave no hidden touch controls over the field", async () => { + useTeamStore.setState({ number: null, code: "" }); + useReportStateStore.getState().scoutMatch(meta); + const setOverlay = jest.fn<(value: boolean) => void>(); + const props = { + field: , + gamePhaseMessage: "Pre-Match", + setOverlay, + onEnd: jest.fn(), + onRestart: jest.fn(), + }; + const view = await render(); + expect( + screen.queryByLabelText("Close Overlay", { includeHiddenElements: true }), + ).toBeNull(); + await userEvent + .setup() + .press(screen.getByRole("button", { name: "Start position Hub" })); + expect( + screen.getByRole("button", { name: "Start position Hub" }), + ).toBeSelected(); + await view.rerender(); + await userEvent.setup().press(screen.getByLabelText("Close Overlay")); + expect(setOverlay).toHaveBeenCalledWith(false); + setOverlay.mockClear(); + await userEvent + .setup() + .press(screen.getByRole("button", { name: "Intake from outpost" })); + expect(useReportStateStore.getState().events).toEqual([ + expect.objectContaining({ + type: MatchEventType.Intake, + position: MatchEventPosition.Outpost, + }), + ]); + expect(setOverlay).toHaveBeenCalledWith(false); + await view.rerender(); + expect( + screen.queryByLabelText("Close Overlay", { includeHiddenElements: true }), + ).toBeNull(); +}); diff --git a/apps/collection/test/jest/pre-match-ui.test.tsx b/apps/collection/test/jest/pre-match-ui.test.tsx new file mode 100644 index 00000000..1ad2d3da --- /dev/null +++ b/apps/collection/test/jest/pre-match-ui.test.tsx @@ -0,0 +1,60 @@ +import React from "react"; +import { act, render, screen, userEvent } from "@testing-library/react-native"; +import { beforeEach, expect, test } from "@jest/globals"; +import { PreMatchActions } from "../../lib/collection/ui/actions/PreMatchActions"; +import { useReportStateStore } from "../../lib/collection/reportStateStore"; +import { MatchEventPosition } from "../../lib/collection/MatchEventPosition"; +import { useTeamStore } from "../../lib/storage/userStores"; +import { useTrainingSessionStore } from "../../lib/training/trainingStore"; +import { meta } from "./fixtures"; + +beforeEach(() => { + useTeamStore.setState({ number: null, code: "" }); + useReportStateStore.getState().reset(); + useTrainingSessionStore.getState().clear(); +}); + +test("a live-match starting-position press updates the report and selected button", async () => { + useReportStateStore.getState().scoutMatch(meta); + await render(); + const user = userEvent.setup(); + await user.press(screen.getByRole("button", { name: "Start position Hub" })); + expect(useReportStateStore.getState().startPosition).toBe( + MatchEventPosition.Hub, + ); + expect( + screen.getByRole("button", { name: "Start position Hub" }), + ).toBeSelected(); + await user.press( + screen.getByRole("button", { name: "Start position LeftTrench" }), + ); + expect(useReportStateStore.getState().startPosition).toBe( + MatchEventPosition.LeftTrench, + ); + expect( + screen.getByRole("button", { name: "Start position Hub" }), + ).not.toBeSelected(); +}); + +test("a disconnected paired session prevents starting-position changes", async () => { + useReportStateStore.setState({ + meta: { + ...meta, + collection: { + sourceTeamNumber: 9999, + trainingAttemptUuid: "33333333-3333-4333-8333-333333333333", + }, + }, + }); + await render(); + const user = userEvent.setup(); + await user.press(screen.getByRole("button", { name: "Start position Hub" })); + expect(useReportStateStore.getState().startPosition).toBeUndefined(); + await act(async () => { + useReportStateStore.getState().scoutMatch(meta); + }); + await user.press(screen.getByRole("button", { name: "Start position Hub" })); + expect(useReportStateStore.getState().startPosition).toBe( + MatchEventPosition.Hub, + ); +}); diff --git a/apps/collection/test/matchValidation.test.cjs b/apps/collection/test/matchValidation.test.cjs index 33526b47..e8505e5b 100644 --- a/apps/collection/test/matchValidation.test.cjs +++ b/apps/collection/test/matchValidation.test.cjs @@ -85,6 +85,21 @@ test("disconnection allows starting even without a cached schedule", async () => }; assert.deepEqual(await checkMatchExists(meta), { status: "offline" }); }); +test("native fetch transport errors allow offline scouting", async () => { + request = async () => { + throw new Error( + "fetch failed: java.io.IOException: unexpected end of stream", + ); + }; + assert.deepEqual(await checkMatchExists(meta), { status: "offline" }); + request = async () => { + throw new Error("Could not read local device headers"); + }; + await assert.rejects( + checkMatchExists(meta), + /Could not read local device headers/, + ); +}); test("an unresponsive connection times out instead of preventing offline scouting", async (t) => { t.mock.timers.enable({ apis: ["setTimeout"] }); request = (_url, { signal }) => diff --git a/apps/collection/test/native/android_input_test.py b/apps/collection/test/native/android_input_test.py new file mode 100644 index 00000000..50c2283b --- /dev/null +++ b/apps/collection/test/native/android_input_test.py @@ -0,0 +1,102 @@ +import importlib.util +from pathlib import Path +import unittest +import xml.etree.ElementTree as ET +from tempfile import TemporaryDirectory +from unittest.mock import patch +import subprocess + +spec = importlib.util.spec_from_file_location("menu_input", Path(__file__).resolve().parents[2] / "scripts/prepare-native-android.py") +menu = importlib.util.module_from_spec(spec) +spec.loader.exec_module(menu) + + +class NativePreparationTest(unittest.TestCase): + def node(self, **overrides): + import xml.etree.ElementTree as ET + attrs = {"package": menu.APP_ID, "content-desc": "End match", "enabled": "true", "bounds": "[572,7][622,53]"} + attrs.update(overrides) + return ET.tostring(ET.Element("node", attrs)) + + def test_uses_current_control_bounds(self): + self.assertEqual(menu.point_for(ET.fromstring(self.node())), (597, 30)) + self.assertEqual(menu.point_for(ET.fromstring(self.node(bounds="[350,60][620,110]"))), (485, 85)) + + def test_rejects_disabled_or_invalid_control_bounds(self): + for data in [self.node(enabled="false"), self.node(bounds="[1,2][1,2]"), self.node(bounds="bad")]: + with self.subTest(data=data), self.assertRaises(ValueError): + menu.point_for(ET.fromstring(data)) + + def test_app_state_rejects_missing_wrong_app_or_ambiguous_nodes(self): + for data in [b"", self.node(package="other.app"), b"" + self.node() + self.node() + b""]: + with self.subTest(data=data), self.assertRaises(ValueError): + menu.assert_state(data, "End match", {"enabled": "true"}) + + def test_state_assertions_reject_wrong_or_absent_state(self): + menu.assert_state(self.node(selected="true"), "End match", {"selected": "true"}) + menu.assert_state(self.node(enabled="false"), "End match", {"enabled": "false"}) + with self.assertRaises(AssertionError): + menu.assert_state(self.node(selected="false"), "End match", {"selected": "true"}) + with self.assertRaises(ValueError): + menu.assert_state(b"", "End match", {"enabled": "false"}) + + def test_recognizes_captured_android_immersive_confirmation(self): + data = (Path(__file__).parent / "fixtures/immersive-confirmation.xml").read_bytes() + self.assertEqual(menu.immersive_confirmation_point(data), (510, 190)) + # An app button or another system OK dialog must never be acknowledged. + self.assertIsNone(menu.immersive_confirmation_point(self.node(text="Got it"))) + self.assertIsNone(menu.immersive_confirmation_point( + b'' + )) + + def test_immersive_confirmation_rejects_disabled_or_ambiguous_button(self): + import xml.etree.ElementTree as ET + data = (Path(__file__).parent / "fixtures/immersive-confirmation.xml").read_bytes() + for mode in ["disabled", "duplicate", "wrong-package"]: + root = ET.fromstring(data) + button = next(n for n in root.iter("node") if n.get("resource-id") == "android:id/ok") + if mode == "disabled": + button.set("enabled", "false") + elif mode == "wrong-package": + button.set("package", "other.app") + else: + root.append(ET.fromstring(ET.tostring(button))) + with self.subTest(mode=mode), self.assertRaises(ValueError): + menu.immersive_confirmation_point(ET.tostring(root)) + + def test_failed_idle_capture_cannot_pass_using_a_stale_dump(self): + # The real CLI prints an idle error but exits zero and leaves its old + # XML behind. That stale XML would satisfy both preparation assertions. + stale = b'' + self.node(**{ + "content-desc": "Start position Hub" + }) + self.node(**{ + "content-desc": "Start match", "enabled": "false" + }) + b'' + with TemporaryDirectory() as directory: + root = Path(directory) + remote = root / "device-ui.xml" + remote.write_bytes(stale) + + def run_command(args, **kwargs): + if args[1:4] == ["shell", "rm", "-f"]: + remote.unlink(missing_ok=True) + # A failed dump intentionally produces no new file. + return subprocess.CompletedProcess(args, 0) + + def read_command(args, **kwargs): + if not remote.exists(): + raise subprocess.CalledProcessError(1, args) + return remote.read_bytes() + + with patch.object(menu, "Path", side_effect=lambda p: root / p), \ + patch.object(menu.subprocess, "run", side_effect=run_command), \ + patch.object(menu.subprocess, "check_output", side_effect=read_command), \ + self.assertRaises(subprocess.CalledProcessError): + menu.run() + report = ET.parse(root / ".maestro/results/prepare-landscape.xml") + self.assertEqual(report.getroot().get("failures"), "1") + self.assertIsNotNone(report.find("testcase/failure")) + + +if __name__ == "__main__": + unittest.main() diff --git a/apps/collection/test/native/fixtures/immersive-confirmation.xml b/apps/collection/test/native/fixtures/immersive-confirmation.xml new file mode 100644 index 00000000..889cad34 --- /dev/null +++ b/apps/collection/test/native/fixtures/immersive-confirmation.xml @@ -0,0 +1 @@ + \ No newline at end of file