Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat: Implement automated testing framework with debug hooks and mock server

Durganshu Mishra7c2dc3fc4f5f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 67708d7..5410960 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -5,6 +5,8 @@ on:
branches: [master, development, development, rishabh-development]
pull_request:
workflow_dispatch:
+ schedule:
+ - cron: "0 2 * * *"
concurrency:
group: ci-${{ github.ref }}
@@ -46,3 +48,78 @@ jobs:
app/build/reports/
app/build/test-results/testDebugUnitTest/
retention-days: 14
+
+ instrumented-smoke:
+ if: github.event_name != 'schedule'
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Enable KVM
+ 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
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - uses: gradle/actions/setup-gradle@v4
+
+ - name: Run smoke instrumented tests (API 34, GMD)
+ run: |
+ ./gradlew :app:smokeGroupDebugAndroidTest --stacktrace \
+ -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect
+
+ - name: Upload instrumented test reports
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: instrumented-smoke-reports
+ path: |
+ app/build/reports/androidTests/
+ app/build/outputs/androidTest-results/
+ retention-days: 14
+
+ instrumented-full:
+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
+ runs-on: ubuntu-latest
+ timeout-minutes: 120
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Enable KVM
+ 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
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: "17"
+
+ - uses: gradle/actions/setup-gradle@v4
+
+ - name: Run full instrumented test matrix (API 27/30/33/34, GMD)
+ run: |
+ ./gradlew :app:fullGroupDebugAndroidTest --stacktrace \
+ -Pandroid.testoptions.manageddevices.emulator.gpu=swiftshader_indirect \
+ -Dorg.gradle.workers.max=2 \
+ -Pandroid.experimental.testOptions.managedDevices.maxConcurrentDevices=1 \
+ -Pandroid.experimental.testOptions.managedDevices.setupTimeoutMinutes=20
+
+ - name: Upload instrumented test reports
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: instrumented-full-reports
+ path: |
+ app/build/reports/androidTests/
+ app/build/outputs/androidTest-results/
+ retention-days: 14
diff --git a/.maestro/config.yaml b/.maestro/config.yaml
new file mode 100644
index 0000000..730ff2a
--- /dev/null
+++ b/.maestro/config.yaml
@@ -0,0 +1 @@
+appId: com.gotcha
diff --git a/.maestro/flows/01-launch.yaml b/.maestro/flows/01-launch.yaml
new file mode 100644
index 0000000..3bda918
--- /dev/null
+++ b/.maestro/flows/01-launch.yaml
@@ -0,0 +1,7 @@
+appId: com.gotcha
+---
+# Requires scripts/maestro_run.sh to have seeded settings first (configured route).
+- launchApp
+- assertVisible: "Gotcha"
+- assertVisible:
+ text: "Let's Go"
diff --git a/.maestro/flows/02-settings-toggle.yaml b/.maestro/flows/02-settings-toggle.yaml
new file mode 100644
index 0000000..3cdc879
--- /dev/null
+++ b/.maestro/flows/02-settings-toggle.yaml
@@ -0,0 +1,11 @@
+appId: com.gotcha
+---
+- launchApp
+- tapOn: "Open menu"
+- tapOn: "Settings"
+- tapOn: "Light"
+- assertVisible: "Light"
+- tapOn: "Dark"
+- assertVisible: "Dark"
+- tapOn: "AI Configuration"
+- assertVisible: "Base URL (OpenAI-compatible)"
diff --git a/.maestro/flows/03-chat-roundtrip.yaml b/.maestro/flows/03-chat-roundtrip.yaml
new file mode 100644
index 0000000..72baf27
--- /dev/null
+++ b/.maestro/flows/03-chat-roundtrip.yaml
@@ -0,0 +1,11 @@
+appId: com.gotcha
+---
+# Requires scripts/maestro_run.sh: mock_llm_server.py reachable via `adb reverse tcp:8080 tcp:8080`.
+- launchApp
+- tapOn:
+ text: "Let's Go"
+- inputText: "hello"
+- tapOn: "Send"
+- extendedWaitUntil:
+ visible: "MOCK_REPLY_OK"
+ timeout: 15000
diff --git a/.maestro/flows/04-assistive-ball.yaml b/.maestro/flows/04-assistive-ball.yaml
new file mode 100644
index 0000000..25ce7bb
--- /dev/null
+++ b/.maestro/flows/04-assistive-ball.yaml
@@ -0,0 +1,13 @@
+appId: com.gotcha
+---
+# Requires scripts/maestro_run.sh to have granted the SYSTEM_ALERT_WINDOW appop first
+# (Maestro cannot send shell/appops commands itself).
+- launchApp
+- tapOn: "Turn on assistive ball"
+- pressKey: Home
+- assertVisible: "Gotcha assistive ball"
+- tapOn: "Gotcha assistive ball"
+- assertVisible: "Open App"
+- tapOn: "Open App"
+- assertVisible:
+ text: "Let's Go"
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 6c09e6d..3936475 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -83,6 +83,84 @@ android {
htmlReport = true
sarifReport = true
}
+
+ testOptions {
+ animationsDisabled = true
+ managedDevices {
+ localDevices {
+ create("api27") {
+ device = "Pixel 2"
+ apiLevel = 27
+ systemImageSource = "aosp"
+ }
+ // Android 10 — no ATD image at this API level; falls back to full aosp.
+ create("api29") {
+ device = "Pixel 2"
+ apiLevel = 29
+ systemImageSource = "aosp"
+ }
+ // Android 11
+ create("api30") {
+ device = "Pixel 2"
+ apiLevel = 30
+ systemImageSource = "aosp-atd"
+ }
+ // Android 12
+ create("api31") {
+ device = "Pixel 4"
+ apiLevel = 31
+ systemImageSource = "aosp-atd"
+ }
+ // Android 13
+ create("api33") {
+ device = "Pixel 6"
+ apiLevel = 33
+ systemImageSource = "aosp-atd"
+ }
+ // Android 14
+ create("api34") {
+ device = "Pixel 6"
+ apiLevel = 34
+ systemImageSource = "aosp-atd"
+ }
+ // Android 15
+ create("api35") {
+ device = "Pixel 8"
+ apiLevel = 35
+ systemImageSource = "aosp-atd"
+ }
+ // Android 16 — no ATD image published for this API level yet;
+ // Gradle's own error suggested "google" as the available source.
+ create("api36") {
+ device = "Pixel 8"
+ apiLevel = 36
+ systemImageSource = "google"
+ }
+ }
+ groups {
+ create("smoke") {
+ targetDevices.add(allDevices["api34"])
+ }
+ create("full") {
+ targetDevices.add(allDevices["api27"])
+ targetDevices.add(allDevices["api30"])
+ targetDevices.add(allDevices["api33"])
+ targetDevices.add(allDevices["api34"])
+ }
+ // Android 10 through Android 16 — the range requested for manual
+ // multi-version verification. Excludes api27 (Android 8.1, minSdk-only).
+ create("android10to16") {
+ targetDevices.add(allDevices["api29"])
+ targetDevices.add(allDevices["api30"])
+ targetDevices.add(allDevices["api31"])
+ targetDevices.add(allDevices["api33"])
+ targetDevices.add(allDevices["api34"])
+ targetDevices.add(allDevices["api35"])
+ targetDevices.add(allDevices["api36"])
+ }
+ }
+ }
+ }
}
detekt {
@@ -159,4 +237,15 @@ dependencies {
testImplementation("junit:junit:4.13.2")
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
+
+ // Instrumented tests
+ androidTestImplementation(composeBom)
+ androidTestImplementation("androidx.test:core-ktx:1.6.1")
+ androidTestImplementation("androidx.test:runner:1.6.2")
+ androidTestImplementation("androidx.test:rules:1.6.1")
+ androidTestImplementation("androidx.test.ext:junit-ktx:1.2.1")
+ androidTestImplementation("androidx.test.espresso:espresso-core:3.6.1")
+ androidTestImplementation("androidx.compose.ui:ui-test-junit4")
+ androidTestImplementation("androidx.test.uiautomator:uiautomator:2.3.0")
+ androidTestImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
}
diff --git a/app/src/androidTest/java/com/gotcha/AccessibilityServiceTest.kt b/app/src/androidTest/java/com/gotcha/AccessibilityServiceTest.kt
new file mode 100644
index 0000000..7fc5ff3
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/AccessibilityServiceTest.kt
@@ -0,0 +1,74 @@
+package com.gotcha
+
+import android.app.UiAutomation
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import com.gotcha.service.GotchaAccessibilityService
+import com.gotcha.testutil.ShellPermissions
+import com.gotcha.testutil.TestSeed
+import org.junit.After
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Separate class from other UiAutomator tests: UiAutomation suppresses other
+ * accessibility services by default, so FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES
+ * must be requested before the first UiDevice/UiAutomation acquisition in the
+ * process — mixing that with plain UiAutomator tests in one class risks whichever
+ * runs first winning the flag for the whole class.
+ *
+ * Known limitation (confirmed on API 33 emulator, 2026-07-19): binding reliably
+ * fails when the app is under active self-instrumentation, even with the app
+ * process already warm and un-stopped (`dumpsys package` showed stopped=false)
+ * and after waiting 45s. The identical sequence — enable the secure setting after
+ * launching the app once — binds in ~0-5s via plain `adb shell` outside
+ * instrumentation. AccessibilityManagerService appears to treat the instrumented
+ * process differently for new service binds; this is a known rough edge in the
+ * Android testing ecosystem, not a bug in GotchaAccessibilityService itself
+ * (`instance` is confirmed non-null immediately when bound normally). Left in the
+ * suite as a best-effort check rather than removed — worth revisiting with the
+ * `android:process` isolation approach or Test Orchestrator if it needs to be
+ * made reliable.
+ */
+@RunWith(AndroidJUnit4::class)
+class AccessibilityServiceTest {
+
+ @Before
+ fun setUp() {
+ InstrumentationRegistry.getInstrumentation()
+ .getUiAutomation(UiAutomation.FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES)
+ }
+
+ @After
+ fun tearDown() {
+ ShellPermissions.disableAccessibilityService()
+ }
+
+ @Test
+ fun enablingViaSecureSettings_connectsService() {
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedUnconfigured(context)
+ val scenario = ActivityScenario.launch(MainActivity::class.java)
+
+ ShellPermissions.enableAccessibilityService()
+ val connected = pollUntil(timeoutMs = 10_000) {
+ GotchaAccessibilityService.instance != null
+ }
+
+ scenario.close()
+ assertTrue("GotchaAccessibilityService did not connect", connected)
+ }
+
+ private fun pollUntil(timeoutMs: Long, intervalMs: Long = 200, condition: () -> Boolean): Boolean {
+ val deadline = System.currentTimeMillis() + timeoutMs
+ while (System.currentTimeMillis() < deadline) {
+ if (condition()) return true
+ Thread.sleep(intervalMs)
+ }
+ return condition()
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/AssistiveBallTest.kt b/app/src/androidTest/java/com/gotcha/AssistiveBallTest.kt
new file mode 100644
index 0000000..23d83bd
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/AssistiveBallTest.kt
@@ -0,0 +1,101 @@
+package com.gotcha
+
+import androidx.compose.ui.test.hasContentDescription
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.performClick
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import androidx.test.uiautomator.By
+import androidx.test.uiautomator.UiDevice
+import androidx.test.uiautomator.Until
+import com.gotcha.service.AssistiveBallService
+import com.gotcha.testutil.MockLlm
+import com.gotcha.testutil.ShellPermissions
+import com.gotcha.testutil.TestSeed
+import com.gotcha.ui.ASSISTIVE_BALL_CONTENT_DESCRIPTION
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/**
+ * Exercises the assistive-ball overlay, which Espresso/Compose test cannot see
+ * (SYSTEM_ALERT_WINDOW is a separate window) — UiAutomator walks the full window
+ * hierarchy instead.
+ */
+@RunWith(AndroidJUnit4::class)
+class AssistiveBallTest {
+
+ @get:Rule
+ val composeRule = createEmptyComposeRule()
+
+ private var scenario: ActivityScenario<MainActivity>? = null
+ private val mockLlm = MockLlm()
+ private lateinit var device: UiDevice
+
+ @After
+ fun tearDown() {
+ InstrumentationRegistry.getInstrumentation().targetContext
+ .startService(AssistiveBallService.stopIntent(InstrumentationRegistry.getInstrumentation().targetContext))
+ // device.pressHome() + relaunching via the ball's "Open App" (a new task, outside
+ // ActivityScenario's control) leaves ActivityScenario's tracked lifecycle stale;
+ // close() then throws a spurious NPE (androidx.test does not support external
+ // navigation interleaved with an owned ActivityScenario). Tear-down should not
+ // fail the test over that.
+ runCatching { scenario?.close() }
+ mockLlm.shutdown()
+ ShellPermissions.revokeOverlay()
+ }
+
+ @Test
+ fun enablingBall_showsOverlay_survivesHome_andOpensApp() {
+ device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
+ ShellPermissions.grantOverlay()
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl)
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("chat_input").assertExists()
+ composeRule.onNode(hasContentDescription("Turn on assistive ball")).performClick()
+ composeRule.waitForIdle()
+
+ assertTrue(
+ "Ball overlay did not appear",
+ device.wait(Until.hasObject(By.desc(ASSISTIVE_BALL_CONTENT_DESCRIPTION)), 5_000)
+ )
+
+ device.pressHome()
+ assertTrue(
+ "Ball did not survive returning home",
+ device.wait(Until.hasObject(By.desc(ASSISTIVE_BALL_CONTENT_DESCRIPTION)), 5_000)
+ )
+
+ // The ball auto-docks to the screen edge (mostly off-screen, only a thin
+ // peek sliver visible) ~2.5s after appearing, racing against how long the
+ // waits above took. Re-locate + retry the tap a few times rather than
+ // depend on winning that race on the first attempt.
+ var menuOpened = false
+ repeat(3) {
+ if (!menuOpened) {
+ device.findObject(By.desc(ASSISTIVE_BALL_CONTENT_DESCRIPTION))?.click()
+ menuOpened = device.wait(Until.hasObject(By.textContains("Open App")), 2_000)
+ }
+ }
+ assertTrue("Ball menu did not open", menuOpened)
+ device.findObject(By.textContains("Open App")).click()
+
+ assertTrue(
+ "MainActivity did not foreground after tapping Open App",
+ device.wait(Until.hasObject(By.pkg("com.gotcha").depth(0)), 5_000)
+ )
+ assertEquals(true, AssistiveBallService.isRunning.value)
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt b/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt
new file mode 100644
index 0000000..9d7889a
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/ChatRoundTripTest.kt
@@ -0,0 +1,56 @@
+package com.gotcha
+
+import androidx.compose.ui.test.hasText
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performTextInput
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.gotcha.testutil.MOCK_REPLY_OK
+import com.gotcha.testutil.MockLlm
+import com.gotcha.testutil.TestSeed
+import org.junit.After
+import org.junit.Assert.assertTrue
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class ChatRoundTripTest {
+
+ @get:Rule
+ val composeRule = createEmptyComposeRule()
+
+ private var scenario: ActivityScenario<MainActivity>? = null
+ private val mockLlm = MockLlm()
+
+ @After
+ fun tearDown() {
+ scenario?.close()
+ mockLlm.shutdown()
+ }
+
+ @Test
+ fun sendingPrompt_showsMockReply() {
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl, model = "test-model")
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("chat_input").performTextInput("hello")
+ composeRule.onNodeWithTag("send_button").performClick()
+
+ composeRule.waitUntil(timeoutMillis = 15_000) {
+ composeRule.onAllNodes(hasText(MOCK_REPLY_OK, substring = true))
+ .fetchSemanticsNodes().isNotEmpty()
+ }
+
+ val request = mockLlm.server.takeRequest()
+ assertTrue(request.path?.endsWith("/chat/completions") == true)
+ assertTrue(request.body.readUtf8().contains("test-model"))
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/SettingsFlowTest.kt b/app/src/androidTest/java/com/gotcha/SettingsFlowTest.kt
new file mode 100644
index 0000000..d2273c2
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/SettingsFlowTest.kt
@@ -0,0 +1,64 @@
+package com.gotcha
+
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.compose.ui.test.performClick
+import androidx.compose.ui.test.performScrollTo
+import androidx.compose.ui.test.performTextReplacement
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.gotcha.data.SettingsRepository
+import com.gotcha.testutil.TestSeed
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class SettingsFlowTest {
+
+ @get:Rule
+ val composeRule = createEmptyComposeRule()
+
+ private var scenario: ActivityScenario<MainActivity>? = null
+ private val testBaseUrl = "http://localhost:8080/v1/"
+ private val testModel = "flow-test-model"
+
+ @After
+ fun tearDown() {
+ scenario?.close()
+ }
+
+ @Test
+ fun enteredSettings_persistAcrossRelaunch() {
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedUnconfigured(context)
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("settings_ai_config_header").performClick()
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("settings_base_url").performTextReplacement(testBaseUrl)
+ composeRule.onNodeWithTag("settings_model").performTextReplacement(testModel)
+ // The Save button sits below the fold in the scrollable Settings column;
+ // performClick() dispatches at the node's laid-out coordinates without
+ // scrolling it into view first, so an off-screen click silently no-ops.
+ composeRule.onNodeWithTag("settings_save").performScrollTo().performClick()
+ composeRule.waitForIdle()
+
+ scenario?.close()
+
+ val persisted = SettingsRepository(context).load()
+ assertEquals(testBaseUrl, persisted.baseUrl)
+ assertEquals(testModel, persisted.model)
+
+ // Relaunch and confirm the configured route is reached with the saved settings intact.
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+ composeRule.onNodeWithTag("chat_input").assertExists()
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/SmokeLaunchTest.kt b/app/src/androidTest/java/com/gotcha/SmokeLaunchTest.kt
new file mode 100644
index 0000000..d6c478c
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/SmokeLaunchTest.kt
@@ -0,0 +1,52 @@
+package com.gotcha
+
+import androidx.compose.ui.test.junit4.createEmptyComposeRule
+import androidx.compose.ui.test.onNodeWithTag
+import androidx.test.core.app.ActivityScenario
+import androidx.test.core.app.ApplicationProvider
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import com.gotcha.testutil.MockLlm
+import com.gotcha.testutil.TestSeed
+import org.junit.After
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+class SmokeLaunchTest {
+
+ @get:Rule
+ val composeRule = createEmptyComposeRule()
+
+ private var scenario: ActivityScenario<MainActivity>? = null
+ private val mockLlm = MockLlm()
+
+ @After
+ fun tearDown() {
+ scenario?.close()
+ mockLlm.shutdown()
+ }
+
+ @Test
+ fun configuredInstall_landsOnChatRoute() {
+ mockLlm.start()
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedConfigured(context, baseUrl = mockLlm.baseUrl)
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("chat_input").assertExists()
+ }
+
+ @Test
+ fun unconfiguredInstall_landsOnSettingsRoute() {
+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()
+ TestSeed.seedUnconfigured(context)
+
+ scenario = ActivityScenario.launch(MainActivity::class.java)
+ composeRule.waitForIdle()
+
+ composeRule.onNodeWithTag("settings_ai_config_header").assertExists()
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/testutil/MockLlm.kt b/app/src/androidTest/java/com/gotcha/testutil/MockLlm.kt
new file mode 100644
index 0000000..07fd66b
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/testutil/MockLlm.kt
@@ -0,0 +1,47 @@
+package com.gotcha.testutil
+
+import okhttp3.mockwebserver.Dispatcher
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import okhttp3.mockwebserver.RecordedRequest
+
+/** Canned reply asserted by [com.gotcha.ChatRoundTripTest]; mirrors scripts/mock_llm_server.py. */
+const val MOCK_REPLY_OK = "MOCK_REPLY_OK"
+
+/**
+ * In-process MockWebServer standing in for an OpenAI-compatible backend during
+ * androidTest runs. Serves the same two routes the Kotlin unit tests
+ * (app/src/test/java/com/gotcha/llm/LLMClientTest.kt) and the standalone
+ * scripts/mock_llm_server.py (used by Maestro) exercise.
+ */
+class MockLlm {
+
+ val server = MockWebServer()
+
+ /** Base URL to seed into settings — trailing slash, matches LLMClient's expectations. */
+ val baseUrl: String
+ get() = server.url("/v1/").toString()
+
+ fun start() {
+ server.dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest): MockResponse {
+ return when {
+ request.path?.endsWith("/chat/completions") == true -> MockResponse()
+ .setHeader("Content-Type", "application/json")
+ .setBody(
+ """{"choices":[{"message":{"role":"assistant","content":"$MOCK_REPLY_OK"}}]}"""
+ )
+ request.path?.endsWith("/models") == true -> MockResponse()
+ .setHeader("Content-Type", "application/json")
+ .setBody("""{"data":[{"id":"test-model","object":"model"}]}""")
+ else -> MockResponse().setResponseCode(404)
+ }
+ }
+ }
+ server.start()
+ }
+
+ fun shutdown() {
+ server.shutdown()
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/testutil/ShellPermissions.kt b/app/src/androidTest/java/com/gotcha/testutil/ShellPermissions.kt
new file mode 100644
index 0000000..8d6da23
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/testutil/ShellPermissions.kt
@@ -0,0 +1,36 @@
+package com.gotcha.testutil
+
+import androidx.test.platform.app.InstrumentationRegistry
+
+/**
+ * Grants/revokes permissions that `pm grant` cannot reach, via
+ * `UiAutomation.executeShellCommand` (adb-shell-equivalent privilege).
+ */
+object ShellPermissions {
+
+ private const val PACKAGE_NAME = "com.gotcha"
+
+ private fun shell(command: String) {
+ InstrumentationRegistry.getInstrumentation().uiAutomation
+ .executeShellCommand(command)
+ .close()
+ }
+
+ /** SYSTEM_ALERT_WINDOW is an appop, not a runtime permission — `pm grant` does not work. */
+ fun grantOverlay() = shell("appops set $PACKAGE_NAME SYSTEM_ALERT_WINDOW allow")
+
+ fun revokeOverlay() = shell("appops set $PACKAGE_NAME SYSTEM_ALERT_WINDOW deny")
+
+ fun enableAccessibilityService() {
+ shell(
+ "settings put secure enabled_accessibility_services " +
+ "$PACKAGE_NAME/com.gotcha.service.GotchaAccessibilityService"
+ )
+ shell("settings put secure accessibility_enabled 1")
+ }
+
+ fun disableAccessibilityService() {
+ shell("settings put secure enabled_accessibility_services \"\"")
+ shell("settings put secure accessibility_enabled 0")
+ }
+}
diff --git a/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt
new file mode 100644
index 0000000..242d298
--- /dev/null
+++ b/app/src/androidTest/java/com/gotcha/testutil/TestSeed.kt
@@ -0,0 +1,46 @@
+package com.gotcha.testutil
+
+import android.content.Context
+import com.gotcha.MainActivity
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.debug.seedTestSettings
+
+/**
+ * Seeds [com.gotcha.data.SettingsRepository] in-process before the activity under
+ * test launches. Instrumentation runs in the target app's process, so it shares the
+ * same AndroidKeystore-backed EncryptedSharedPreferences — this must happen
+ * *before* `ActivityScenario.launch()`, not via `ActivityScenarioRule`, since the
+ * activity reads settings synchronously in `onCreate`.
+ */
+object TestSeed {
+
+ fun seedConfigured(
+ context: Context,
+ baseUrl: String,
+ apiKey: String = "test",
+ model: String = "test-model",
+ assistiveBallEnabled: Boolean = false
+ ) {
+ seedTestSettings(
+ context = context,
+ baseUrl = baseUrl,
+ apiKey = apiKey,
+ model = model,
+ assistiveBallEnabled = assistiveBallEnabled
+ )
+ }
+
+ /** Blank base URL — `Settings.isConfigured` is false, routing MainActivity to Settings. */
+ fun seedUnconfigured(context: Context) {
+ val repository = SettingsRepository(context)
+ repository.save(
+ Settings(provider = LlmProvider.OPENAI_COMPATIBLE, baseUrl = "", apiKey = "")
+ )
+ repository.prefs.edit()
+ .putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true)
+ .putBoolean(MainActivity.KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, true)
+ .apply()
+ }
+}
diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml
new file mode 100644
index 0000000..52f594a
--- /dev/null
+++ b/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ package="com.gotcha">
+
+ <application>
+ <!-- Test-only hook to seed settings via adb broadcast; absent from release. -->
+ <receiver
+ android:name=".debug.TestHooksReceiver"
+ android:exported="true"
+ tools:ignore="ExportedReceiver">
+ <intent-filter>
+ <action android:name="com.gotcha.debug.SEED_SETTINGS" />
+ </intent-filter>
+ </receiver>
+ </application>
+
+</manifest>
diff --git a/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt b/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt
new file mode 100644
index 0000000..d9c493a
--- /dev/null
+++ b/app/src/debug/java/com/gotcha/debug/TestHooksReceiver.kt
@@ -0,0 +1,80 @@
+package com.gotcha.debug
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import com.gotcha.MainActivity
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+
+/**
+ * Debug-only broadcast receiver that seeds app settings for automated testing.
+ * Absent from release builds. Bypasses the UI entirely so instrumented tests and
+ * Maestro flows can configure the app before launch without touching
+ * EncryptedSharedPreferences directly (seeding must happen in-process, since the
+ * prefs file is encrypted with an AndroidKeystore-backed key).
+ *
+ * Invoke with an explicit component to bypass API-26+ implicit-broadcast limits:
+ * adb shell am broadcast -n com.gotcha/com.gotcha.debug.TestHooksReceiver \
+ * -a com.gotcha.debug.SEED_SETTINGS \
+ * --es base_url "http://localhost:8080/v1/" --es api_key test --es model test-model
+ */
+class TestHooksReceiver : BroadcastReceiver() {
+
+ override fun onReceive(context: Context, intent: Intent) {
+ if (intent.action != ACTION_SEED_SETTINGS) return
+
+ val repository = SettingsRepository(context)
+ val current = repository.load()
+ repository.save(
+ current.copy(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ baseUrl = intent.getStringExtra(EXTRA_BASE_URL) ?: current.baseUrl,
+ apiKey = intent.getStringExtra(EXTRA_API_KEY) ?: current.apiKey,
+ model = intent.getStringExtra(EXTRA_MODEL) ?: current.model,
+ assistiveBallEnabled = intent.getBooleanExtra(
+ EXTRA_ASSISTIVE_BALL,
+ current.assistiveBallEnabled
+ )
+ )
+ )
+
+ repository.prefs.edit()
+ .putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true)
+ .putBoolean(MainActivity.KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, true)
+ .apply()
+ }
+
+ companion object {
+ const val ACTION_SEED_SETTINGS = "com.gotcha.debug.SEED_SETTINGS"
+ const val EXTRA_BASE_URL = "base_url"
+ const val EXTRA_API_KEY = "api_key"
+ const val EXTRA_MODEL = "model"
+ const val EXTRA_ASSISTIVE_BALL = "assistive_ball"
+ }
+}
+
+/** Convenience for in-process callers (androidTest) that want the same seeding logic. */
+fun seedTestSettings(
+ context: Context,
+ baseUrl: String,
+ apiKey: String = "test",
+ model: String = "test-model",
+ assistiveBallEnabled: Boolean = false
+) {
+ val repository = SettingsRepository(context)
+ repository.save(
+ Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ baseUrl = baseUrl,
+ apiKey = apiKey,
+ model = model,
+ assistiveBallEnabled = assistiveBallEnabled
+ )
+ )
+ repository.prefs.edit()
+ .putBoolean(MainActivity.KEY_FIRST_LAUNCH_DONE, true)
+ .putBoolean(MainActivity.KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, true)
+ .apply()
+}
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 6ab5009..929d116 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -136,7 +136,9 @@ class MainActivity : ComponentActivity() {
}
// Request MediaProjection consent for screenshot capture
// Always request if not granted in this process session (cleared on process kill)
- if (ScreenPerception.mediaProjectionResultData == null) {
+ if (ScreenPerception.mediaProjectionResultData == null &&
+ !prefs.getBoolean(KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT, false)
+ ) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val mpManager = getSystemService(
Context.MEDIA_PROJECTION_SERVICE
@@ -513,6 +515,9 @@ class MainActivity : ComponentActivity() {
/** SharedPreferences key to track first-launch permission setup. */
const val KEY_FIRST_LAUNCH_DONE = "first_launch_setup_done"
+ /** SharedPreferences key: when true, skip the MediaProjection consent prompt (test-only). */
+ const val KEY_SUPPRESS_MEDIA_PROJECTION_PROMPT = "suppress_media_projection_prompt"
+
/** Lifecycle owner for CameraX binding. Set in onCreate, valid while activity lives. */
@Volatile
var lifecycleOwner: androidx.lifecycle.LifecycleOwner? = null
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index e173535..30a097e 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -33,6 +33,9 @@ import com.gotcha.data.ThemeMode
import kotlin.math.abs
import kotlin.math.hypot
+/** Accessibility label for the ball root view — used by UiAutomator to find the overlay. */
+const val ASSISTIVE_BALL_CONTENT_DESCRIPTION = "Gotcha assistive ball"
+
/**
* The floating "assistive ball" drawn over other apps via SYSTEM_ALERT_WINDOW,
* reworked into a Messenger-Bubbles-style call head:
@@ -339,6 +342,7 @@ class AssistiveBallOverlay(context: Context) {
@SuppressLint("ClickableViewAccessibility")
private fun buildBall(): View {
return ImageView(appContext).apply {
+ contentDescription = ASSISTIVE_BALL_CONTENT_DESCRIPTION
setImageResource(R.mipmap.ic_launcher_round)
scaleType = ImageView.ScaleType.CENTER_CROP
// Clip the square launcher icon into a circular "ball".
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index 84ad951..31c334f 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -59,6 +59,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
@@ -214,7 +215,7 @@ fun ChatScreen(
} else {
LazyColumn(
state = listState,
- modifier = Modifier.weight(1f).fillMaxWidth()
+ modifier = Modifier.weight(1f).fillMaxWidth().testTag("message_list")
) {
items(state.messages, key = { it.id }) { message ->
MessageBubble(message = message, onSpeak = onSpeak)
@@ -348,7 +349,7 @@ fun ChatScreen(
OutlinedTextField(
value = input,
onValueChange = { input = it },
- modifier = Modifier.weight(1f),
+ modifier = Modifier.weight(1f).testTag("chat_input"),
shape = RoundedCornerShape(24.dp),
placeholder = {
Text(if (otherChatRunning) "Finish the running chat first…" else "Let's Go")
@@ -419,7 +420,7 @@ fun ChatScreen(
pendingImageUri = null
pendingImageBase64 = null
},
- modifier = Modifier.size(40.dp),
+ modifier = Modifier.size(40.dp).testTag("send_button"),
enabled = state.isConfigured && !otherChatRunning &&
(input.isNotBlank() || pendingImageBase64 != null)
) {
diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
index 083cd1e..40972ae 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt
@@ -36,6 +36,7 @@ import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
@@ -222,7 +223,8 @@ fun SettingsScreen(
SectionHeader(
title = "AI Configuration",
expanded = aiConfigExpanded,
- onToggle = { aiConfigExpanded = !aiConfigExpanded }
+ onToggle = { aiConfigExpanded = !aiConfigExpanded },
+ modifier = Modifier.testTag("settings_ai_config_header")
)
AnimatedVisibility(visible = aiConfigExpanded) {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
@@ -308,14 +310,14 @@ fun SettingsScreen(
Text(if (showKey) "Hide" else "Show")
}
},
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth().testTag("settings_api_key")
)
OutlinedTextField(
value = baseUrl,
onValueChange = { baseUrl = it },
label = { Text("Base URL (OpenAI-compatible)") },
singleLine = true,
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth().testTag("settings_base_url")
)
}
ExposedDropdownMenuBox(
@@ -332,7 +334,7 @@ fun SettingsScreen(
label = { Text("Main model") },
placeholder = { Text("(select model)") },
trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = modelExpanded) },
- modifier = Modifier.fillMaxWidth().menuAnchor()
+ modifier = Modifier.fillMaxWidth().menuAnchor().testTag("settings_model")
)
ExposedDropdownMenu(
expanded = modelExpanded,
@@ -512,7 +514,7 @@ fun SettingsScreen(
LlmProvider.SAMOSA_AI -> samosaToken.isNotBlank() && model.isNotBlank()
LlmProvider.OPENAI_COMPATIBLE -> baseUrl.isNotBlank() && model.isNotBlank()
},
- modifier = Modifier.fillMaxWidth()
+ modifier = Modifier.fillMaxWidth().testTag("settings_save")
) { Text("Save") }
OutlinedButton(
onClick = {
@@ -859,10 +861,11 @@ private fun SamosaAuthSection(
private fun SectionHeader(
title: String,
expanded: Boolean,
- onToggle: () -> Unit
+ onToggle: () -> Unit,
+ modifier: Modifier = Modifier
) {
Row(
- modifier = Modifier
+ modifier = modifier
.fillMaxWidth()
.clickable(onClick = onToggle)
.padding(vertical = 8.dp),
diff --git a/scripts/maestro_run.sh b/scripts/maestro_run.sh
new file mode 100644
index 0000000..3ace638
--- /dev/null
+++ b/scripts/maestro_run.sh
@@ -0,0 +1,49 @@
+#!/usr/bin/env bash
+# Wrapper around `maestro test` that does the setup Maestro itself cannot do:
+# start the mock LLM server, reverse its port to the device, install the debug
+# APK, grant the overlay appop, and seed settings via the debug broadcast hook.
+#
+# Usage: scripts/maestro_run.sh [maestro test args...]
+# Defaults to running every flow in .maestro/flows.
+set -euo pipefail
+
+ANDROID_HOME="${ANDROID_HOME:-${LOCALAPPDATA:-}/Android/Sdk}"
+ADB="$ANDROID_HOME/platform-tools/adb"
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+DEBUG_APK="$REPO_ROOT/app/build/outputs/apk/debug/app-debug.apk"
+PACKAGE_NAME="com.gotcha"
+MOCK_PORT=8080
+
+if [[ ! -f "$DEBUG_APK" ]]; then
+ echo "Debug APK not found at $DEBUG_APK — run ./gradlew :app:assembleDebug first." >&2
+ exit 1
+fi
+
+echo "Starting mock LLM server on :$MOCK_PORT…"
+python3 "$REPO_ROOT/scripts/mock_llm_server.py" "$MOCK_PORT" &
+MOCK_SERVER_PID=$!
+trap 'kill "$MOCK_SERVER_PID" 2>/dev/null || true' EXIT
+
+sleep 1
+
+echo "Reversing device port $MOCK_PORT to host…"
+"$ADB" reverse "tcp:$MOCK_PORT" "tcp:$MOCK_PORT"
+
+echo "Installing debug APK…"
+"$ADB" install -g "$DEBUG_APK"
+
+echo "Granting overlay appop…"
+"$ADB" shell appops set "$PACKAGE_NAME" SYSTEM_ALERT_WINDOW allow
+
+echo "Seeding settings…"
+"$ADB" shell am broadcast -n "$PACKAGE_NAME/com.gotcha.debug.TestHooksReceiver" \
+ -a com.gotcha.debug.SEED_SETTINGS \
+ --es base_url "http://localhost:$MOCK_PORT/v1/" --es api_key test --es model test-model
+
+echo "Running Maestro flows…"
+if [[ $# -gt 0 ]]; then
+ maestro test "$@"
+else
+ maestro test "$REPO_ROOT/.maestro/flows"
+fi
diff --git a/scripts/mock_llm_server.py b/scripts/mock_llm_server.py
new file mode 100644
index 0000000..d8f309b
--- /dev/null
+++ b/scripts/mock_llm_server.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Dependency-free OpenAI-compatible mock server for manual/Maestro test runs.
+
+Serves canned responses on the same routes app/src/test/java/com/gotcha/llm/LLMClientTest.kt
+exercises, so androidTest (MockWebServer, in-process) and Maestro (this server,
+reached via `adb reverse tcp:8080 tcp:8080`) assert against the same reply text.
+
+Usage:
+ python3 scripts/mock_llm_server.py [port]
+"""
+import json
+import sys
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+MOCK_REPLY_OK = "MOCK_REPLY_OK"
+DEFAULT_PORT = 8080
+
+
+class MockLlmHandler(BaseHTTPRequestHandler):
+ def _send_json(self, status, payload):
+ body = json.dumps(payload).encode("utf-8")
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_POST(self):
+ if self.path.rstrip("/").endswith("/chat/completions"):
+ length = int(self.headers.get("Content-Length", 0))
+ self.rfile.read(length) # drain the request body; content is unused
+ self._send_json(
+ 200,
+ {
+ "choices": [
+ {
+ "message": {"role": "assistant", "content": MOCK_REPLY_OK},
+ "finish_reason": "stop",
+ }
+ ]
+ },
+ )
+ else:
+ self._send_json(404, {"error": "not found"})
+
+ def do_GET(self):
+ if self.path.rstrip("/").endswith("/models"):
+ self._send_json(
+ 200,
+ {"data": [{"id": "test-model", "object": "model"}]},
+ )
+ else:
+ self._send_json(404, {"error": "not found"})
+
+ def log_message(self, format, *args): # noqa: A002 - matches BaseHTTPRequestHandler signature
+ sys.stderr.write("[mock_llm_server] %s\n" % (format % args))
+
+
+def main():
+ port = int(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_PORT
+ server = HTTPServer(("0.0.0.0", port), MockLlmHandler)
+ print(f"[mock_llm_server] listening on :{port}")
+ try:
+ server.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_matrix.sh b/scripts/test_matrix.sh
new file mode 100644
index 0000000..c0e964e
--- /dev/null
+++ b/scripts/test_matrix.sh
@@ -0,0 +1,165 @@
+#!/usr/bin/env bash
+# Serial multi-AVD instrumented test runner. Boots each AVD headless, installs the
+# debug APK, seeds settings via the debug test-hook broadcast, runs
+# connectedDebugAndroidTest and/or Maestro against it, then tears the AVD down
+# before moving to the next one. This is the project's only API 26 (minSdk)
+# coverage path — Gradle Managed Devices (Phase 3) supports API 27+ only.
+#
+# Usage:
+# scripts/test_matrix.sh [--connected] [--maestro] [avd-name ...]
+#
+# With no AVD names, every AVD returned by `emulator -list-avds` is run.
+set -uo pipefail
+
+ANDROID_HOME="${ANDROID_HOME:-${LOCALAPPDATA:-}/Android/Sdk}"
+EMULATOR="$ANDROID_HOME/emulator/emulator"
+ADB="$ANDROID_HOME/platform-tools/adb"
+
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+RESULTS_ROOT="$REPO_ROOT/build/matrix-results"
+DEBUG_APK="$REPO_ROOT/app/build/outputs/apk/debug/app-debug.apk"
+
+BOOT_TIMEOUT_S=300
+PACKAGE_NAME="com.gotcha"
+
+run_connected=false
+run_maestro=false
+avd_names=()
+
+for arg in "$@"; do
+ case "$arg" in
+ --connected) run_connected=true ;;
+ --maestro) run_maestro=true ;;
+ *) avd_names+=("$arg") ;;
+ esac
+done
+
+if [[ "$run_connected" == false && "$run_maestro" == false ]]; then
+ run_connected=true
+fi
+
+if [[ ${#avd_names[@]} -eq 0 ]]; then
+ mapfile -t avd_names < <("$EMULATOR" -list-avds)
+fi
+
+if [[ ${#avd_names[@]} -eq 0 ]]; then
+ echo "No AVDs found (and none given on the command line)." >&2
+ exit 1
+fi
+
+mkdir -p "$RESULTS_ROOT"
+
+declare -a summary_avd
+declare -a summary_status
+declare -a summary_duration
+
+boot_avd() {
+ local avd="$1"
+ local extra_flags="$2"
+ echo "[$avd] booting headless…"
+ # shellcheck disable=SC2086
+ "$EMULATOR" -avd "$avd" -no-snapshot -no-audio -no-boot-anim -no-window $extra_flags \
+ > "$RESULTS_ROOT/$avd/emulator.log" 2>&1 &
+ EMULATOR_PID=$!
+
+ "$ADB" -s "emulator-$EMU_PORT" wait-for-device 2>/dev/null || true
+
+ local waited=0
+ while (( waited < BOOT_TIMEOUT_S )); do
+ local booted
+ booted="$("$ADB" -s "emulator-$EMU_PORT" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')"
+ if [[ "$booted" == "1" ]]; then
+ echo "[$avd] booted after ${waited}s"
+ return 0
+ fi
+ sleep 5
+ waited=$((waited + 5))
+ done
+ echo "[$avd] boot timed out after ${BOOT_TIMEOUT_S}s" >&2
+ return 1
+}
+
+run_one_avd() {
+ local avd="$1"
+ local avd_dir="$RESULTS_ROOT/$avd"
+ mkdir -p "$avd_dir"
+ local start_ts
+ start_ts=$(date +%s)
+ local status="pass"
+
+ # Allocate a deterministic-ish port per run so ANDROID_SERIAL is known.
+ EMU_PORT=5554
+ local serial="emulator-$EMU_PORT"
+
+ local extra_flags=""
+ if [[ "$avd" == *"26"* ]]; then
+ extra_flags="-no-snapshot-load"
+ fi
+
+ if ! boot_avd "$avd" "$extra_flags"; then
+ status="fail-boot"
+ else
+ export ANDROID_SERIAL="$serial"
+
+ echo "[$avd] installing debug APK…"
+ if ! "$ADB" -s "$serial" install -g "$DEBUG_APK" > "$avd_dir/install.log" 2>&1; then
+ status="fail-install"
+ fi
+
+ if [[ "$status" == "pass" ]]; then
+ echo "[$avd] granting overlay appop…"
+ "$ADB" -s "$serial" shell appops set "$PACKAGE_NAME" SYSTEM_ALERT_WINDOW allow
+
+ echo "[$avd] seeding settings…"
+ "$ADB" -s "$serial" shell am broadcast -n \
+ "$PACKAGE_NAME/com.gotcha.debug.TestHooksReceiver" \
+ -a com.gotcha.debug.SEED_SETTINGS \
+ --es base_url "http://localhost:8080/v1/" --es api_key test --es model test-model \
+ > "$avd_dir/seed.log" 2>&1
+
+ if [[ "$run_connected" == true ]]; then
+ echo "[$avd] running connectedDebugAndroidTest…"
+ if ! (cd "$REPO_ROOT" && ./gradlew :app:connectedDebugAndroidTest --stacktrace \
+ > "$avd_dir/connected-test.log" 2>&1); then
+ status="fail-connected"
+ fi
+ cp -r "$REPO_ROOT/app/build/reports/androidTests" "$avd_dir/" 2>/dev/null || true
+ cp -r "$REPO_ROOT/app/build/outputs/androidTest-results" "$avd_dir/" 2>/dev/null || true
+ fi
+
+ if [[ "$run_maestro" == true && "$status" == "pass" ]]; then
+ echo "[$avd] running Maestro flows…"
+ if ! "$REPO_ROOT/scripts/maestro_run.sh" > "$avd_dir/maestro.log" 2>&1; then
+ status="fail-maestro"
+ fi
+ fi
+ fi
+
+ "$ADB" -s "$serial" logcat -d > "$avd_dir/logcat.txt" 2>/dev/null || true
+ "$ADB" -s "$serial" emu kill 2>/dev/null || true
+ wait "$EMULATOR_PID" 2>/dev/null || true
+ fi
+
+ local end_ts
+ end_ts=$(date +%s)
+ summary_avd+=("$avd")
+ summary_status+=("$status")
+ summary_duration+=("$((end_ts - start_ts))s")
+}
+
+overall_exit=0
+for avd in "${avd_names[@]}"; do
+ run_one_avd "$avd"
+ if [[ "${summary_status[-1]}" != "pass" ]]; then
+ overall_exit=1
+ fi
+done
+
+echo
+echo "==== Matrix summary ===="
+printf "%-24s %-16s %s\n" "AVD" "Status" "Duration"
+for i in "${!summary_avd[@]}"; do
+ printf "%-24s %-16s %s\n" "${summary_avd[$i]}" "${summary_status[$i]}" "${summary_duration[$i]}"
+done
+
+exit $overall_exit