Modern Apps git

← Modern-Apps.git

build: host Rust libs for JVM tests, shared Robolectric/Compose test harness, merged coverage

Commit
b59c8b40decef7d248700930ebf5b639adf8f820
Author
Vayun Mathur <[email protected]>
When
2026-11-06 16:31 UTC (29 days ago)
Parents
db69519
- rustNativeLib registers a lazy cargoBuildHost_<crate> task; every unit Test task builds
  and appends build/rustHostLibs of the module and its project deps to java.library.path,
  so JNI-backed code runs in JVM tests (fixes OfficeSharingE2ETest, CoordinateTransformsTest).
- App and library conventions add Robolectric, androidx.test, compose ui-test-junit4 and
  coroutines-test (unit and androidTest); default Robolectric SDK 34.
- createMergedCoverageReport per module: unit .exec plus pulled emulator .ec, analyzed from
  uninstrumented compile output with generated-code excludes (Room, serializers, Compose
  singletons, R/BuildConfig, protobuf, AIDL).
- ./test runs the merged report, defaults instrumented runs to the Medium_Phone emulator
  (never a physical device without --device), and serializes emulator use across
  concurrent runs.

Diff

build-logic/shared-test-resources/robolectric.properties
diff --git a/build-logic/shared-test-resources/robolectric.properties b/build-logic/shared-test-resources/robolectric.propertiesnew file mode 100644index 0000000000..26242f8706--- /dev/null+++ b/build-logic/shared-test-resources/robolectric.properties@@ -0,0 +1,10 @@+# Repo-wide Robolectric default SDK (applied by common-conventions-app/library, which add+# this directory to every module's unit-test resources).+#+# The existing Robolectric tests pin `@Config(sdk = [34])` explicitly. This file sets that+# same SDK as the default for every test class WITHOUT an explicit `@Config(sdk = ...)`+# (mechanism, verified against robolectric-4.17: Robolectric merges the classpath-root+# robolectric.properties via Config$Implementation.fromProperties as the base config for+# every test, still overridable per test class with @Config). Keeps new tests on the same+# validated sandbox instead of whatever the module's targetSdk resolves to.+sdk=34
build-logic/src/main/kotlin/RustNative.kt
diff --git a/build-logic/src/main/kotlin/RustNative.kt b/build-logic/src/main/kotlin/RustNative.ktindex 62c40db9bf..803a86fe86 100644--- a/build-logic/src/main/kotlin/RustNative.kt+++ b/build-logic/src/main/kotlin/RustNative.kt@@ -1,6 +1,7 @@ import org.gradle.api.DefaultTask import org.gradle.api.GradleException import org.gradle.api.Project+import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.provider.ListProperty@@ -15,8 +16,10 @@ import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction+import org.gradle.api.tasks.testing.Test import org.gradle.internal.os.OperatingSystem import org.gradle.kotlin.dsl.register+import org.gradle.kotlin.dsl.withType import org.gradle.process.ExecOperations import java.io.File import java.util.Properties@@ -120,6 +123,33 @@ private val KNOWN_RUST_ABIS = listOf(     RustAbi(ABI_X86_64, "x86_64-linux-android", "x86_64-linux-android"), ) +/**+ * Host target triple for JVM unit tests that load Rust cdylibs via+ * `System.loadLibrary`. Mirrors the pattern in+ * `:library:everysync-core` (which predates this helper): GNU triple on+ * Windows (MinGW — matches the installed toolchain; MSVC would need VS Build+ * Tools), Apple triples on macOS, GNU triples on Linux. Resolved with plain+ * JVM system properties at configuration time so the configuration cache is+ * unaffected (a String, never a task or Project, crosses into task actions).+ */+fun hostRustTriple(): String {+    val os = System.getProperty("os.name").lowercase()+    val arch = System.getProperty("os.arch").lowercase()+    val isArm = arch.contains("aarch64") || arch.startsWith("arm")+    return when {+        os.contains("win") -> if (isArm) "aarch64-pc-windows-gnullvm" else "x86_64-pc-windows-gnu"+        os.contains("mac") -> if (isArm) "aarch64-apple-darwin" else "x86_64-apple-darwin"+        else -> if (isArm) "aarch64-unknown-linux-gnu" else "x86_64-unknown-linux-gnu"+    }+}++/** `lib<crate>.dylib` / `.so` / `<crate>.dll` for [hostRustTriple]. */+fun hostRustLibFileName(crate: String): String = when {+    System.getProperty("os.name").lowercase().contains("win") -> "$crate.dll"+    System.getProperty("os.name").lowercase().contains("mac") -> "lib$crate.dylib"+    else -> "lib$crate.so"+}+ /**  * A `path = "..."` or workspace-inherited reference found in one manifest's  * dependency tables.@@ -313,6 +343,13 @@ private fun Project.findRustPathDepDirs(crateDir: File): List<File> {  *                   means the crate has no Vulkan shaders. Only supported with the  *                   default [srcDir], since crates locate `build/spirv` relative to it.  * @param glslcArgs  Extra glslc flags, e.g. `--target-env=vulkan1.1`, `-O`.+ * @param hostTests  Also build this crate for the host (`cargoBuildHost_<crate>`,+ *                   see below) so JVM unit tests can `System.loadLibrary` it.+ *                   Set to false for crates that cannot compile for host+ *                   (Android-only deps like `ndk`/`oboe`, Vulkan/GLES paths+ *                   with no host fallback): no host task is registered and+ *                   [wireRustHostLibsForUnitTests] skips the crate cleanly+ *                   instead of breaking unit tests that never load it.  */ fun Project.rustNativeLib(     crate: String,@@ -322,6 +359,7 @@ fun Project.rustNativeLib(     srcDir: String = "src/main/rust",     shaders: List<String> = emptyList(),     glslcArgs: List<String> = emptyList(),+    hostTests: Boolean = true, ) {     // Serialize cargoBuild across all Rust modules to avoid concurrent rustup installs.     val rustLock = gradle.sharedServices.registerIfAbsent(@@ -594,6 +632,150 @@ fun Project.rustNativeLib(             dependsOn(cargoNdkBuild)         }     }+    // Host cdylib for JVM unit tests (testDevUnitTest / testDevUnitTest):+    // `cargo build --locked --target <hostTriple>` with the same profile,+    // features, env (RUSTC pin, PATH, RUSTFLAGS remap, CARGO_INCREMENTAL=0),+    // toolchain lock, inputs/outputs, and caching as the per-ABI tasks above —+    // but WITHOUT any Android linker/NDK env (no CC/CXX/AR/SYSROOT, no+    // per-target LINKER/RUSTFLAGS, no 16 KB page-size link arg: that flag+    // would break the host link). The output (`lib<crate>.dylib/.so/.dll`)+    // is installed into `build/rustHostLibs`, which nothing packages — APK/AAB+    // assembly reads only `build/rustJniLibs`, so Android outputs are+    // unchanged. Lazy by construction: nothing depends on this task except+    // unit Test tasks (see wireRustHostLibsForUnitTests), so assemble/install+    // never build it. With hostTests = false nothing is registered and+    // dependents' tests never notice the crate.+    val hostTriple: String = hostRustTriple()+    val hostTaskName = "cargoBuildHost_$crate"+    if (hostTests) {+        val cargoBuildHost = tasks.register<Exec>(hostTaskName) {+            usesService(rustLock)+            description = "Builds lib$crate for the host (JVM unit tests)."+            workingDir = file(srcDir)++            val isWindowsHost = OperatingSystem.current().isWindows+            val exeExt = if (isWindowsHost) ".exe" else ""+            val hostLibName = hostRustLibFileName(crate)+            // Per-crate target (may exist from older isolated builds) and workspace root target+            // (current scheme since Cargo.toml workspace unified to root).+            val perCrateHostOut = file("$srcDir/target/$hostTriple/$profile/$hostLibName")+            val workspaceHostOut = rootProject.file("target/$hostTriple/$profile/$hostLibName")+            val destHostLib = layout.buildDirectory.file("rustHostLibs/$hostLibName").get().asFile++            // Same cacheable + relocatable shape as the per-ABI tasks: every+            // input is RELATIVE-sensitive with a distinct (host-prefixed)+            // property name, and host-toolchain facts the env doesn't cover+            // are explicit input properties.+            outputs.cacheIf("Rust cdylib host build is hermetic given the declared inputs") { true }++            inputs.dir("$srcDir/src").withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostCrateSrc")+            inputs.file("$srcDir/Cargo.toml").withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostCrateManifest")+            file("$srcDir/build.rs").takeIf { it.isFile }?.let {+                inputs.file("$srcDir/build.rs").withPathSensitivity(PathSensitivity.RELATIVE)+                    .withPropertyName("hostBuildRs")+            }+            // Same SPIR-V staleness hazard as the ABI tasks: the crate+            // include_bytes!s build/spirv, so a shader edit must re-run cargo.+            compileShaders?.let {+                inputs.files(it).withPathSensitivity(PathSensitivity.RELATIVE)+                    .withPropertyName("hostSpirv")+            }+            // Same flatc-bindings staleness hazard as the ABI tasks (see above).+            file("$srcDir/schema").takeIf { it.isDirectory }?.let {+                inputs.dir("$srcDir/schema").withPathSensitivity(PathSensitivity.RELATIVE)+                    .withPropertyName("hostSchema")+            }+            inputs.files(fileTree(srcDir) { exclude("target/**") })+                .withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostRustCrateTree")+            for (depDir in pathDepDirs) {+                val relDep = depDir.relativeTo(rootProject.projectDir)+                inputs.files(rootProject.fileTree(relDep) { exclude("target/**") })+                    .withPathSensitivity(PathSensitivity.RELATIVE)+                    .withPropertyName("host_" + pathDepPropertyName(rootProject.projectDir, depDir))+            }+            // Root workspace unified (Cargo.toml + Cargo.lock + rust-toolchain.toml)+            inputs.file(rootProject.file("Cargo.toml")).withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostWorkspaceManifest")+            inputs.file(rootProject.file("Cargo.lock")).withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostWorkspaceLock")+            inputs.file(rootProject.file("rust-toolchain.toml")).withPathSensitivity(PathSensitivity.RELATIVE)+                .withPropertyName("hostRustToolchain")+            // Only rust third_party crates – avoid pulling third_party:nanojson java outputs (was implicit dep failure).+            // jni is a crates.io dependency now, so Cargo.lock above covers it.+            inputs.dir(rootProject.file("third_party/om-file-format-sys/src"))+                .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiSrc")+            inputs.file(rootProject.file("third_party/om-file-format-sys/Cargo.toml"))+                .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiManifest")+            inputs.file(rootProject.file("third_party/om-file-format-sys/build.rs"))+                .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiBuildRs")+            inputs.dir(rootProject.file("third_party/om-file-format-sys/c"))+                .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostOmFfiC")+            // BetoCore vendored crates (Apache-2.0) — incremental builds track these like om-file-format-sys.+            inputs.dir(rootProject.file("third_party/betocore"))+                .withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("hostBetocore")+            // Host-toolchain facts that shape the lib bytes but live in env/workingDir+            // (both @Internal on Exec), so they need an explicit input property.+            // Deliberately NOT the NDK props: the host link must not see them.+            inputs.property("hostTriple", hostTriple)+            outputs.file(destHostLib)++            val cargoHome = System.getenv("CARGO_HOME") ?: "${System.getProperty("user.home")}/.cargo"+            val rustSrc = file(srcDir).absolutePath++            val pathSep = if (isWindowsHost) ";" else ":"+            environment("PATH", "$cargoBin$pathSep${System.getenv("PATH")}")+            // Same non-rustup-rustc hazard as the ABI tasks: pin the shim.+            environment("RUSTC", "$cargoBin/rustc$exeExt")+            // Reproducible builds: same $HOME remap as the ABI tasks.+            environment(+                "RUSTFLAGS",+                "--remap-path-prefix=$cargoHome=/cargo --remap-path-prefix=$rustSrc=/$remapLabel",+            )+            environment("CARGO_INCREMENTAL", "0")++            commandLine(+                "$cargoBin/cargo$exeExt",+                "build",+                "--locked",+                "--profile",+                profile,+                "--target",+                hostTriple,+                *cargoFeatureArgs.toTypedArray(),+            )++            doLast {+                destHostLib.parentFile.mkdirs()+                val src = when {+                    perCrateHostOut.exists() -> perCrateHostOut+                    workspaceHostOut.exists() -> workspaceHostOut+                    else -> error("Neither per-crate ${perCrateHostOut.path} nor workspace ${workspaceHostOut.path} exists for $crate")+                }+                src.copyTo(destHostLib, overwrite = true)+            }+        }+        // Same historic-aggregate convenience as cargoNdkBuild for the default+        // crate dir (`./gradlew :mod:cargoBuildHost`); per-crate task names stay+        // unique for multi-crate modules (communicate's rust-mls second crate).+        if (srcDir == "src/main/rust") {+            tasks.register("cargoBuildHost") {+                description = "Builds lib$crate for the host (JVM unit tests)."+                dependsOn(cargoBuildHost)+            }+        }+        // Recorded for wireRustHostLibsForUnitTests: plain strings only, so the+        // configuration cache never sees a Project.+        rustHostLibRefs().getOrPut(path) { mutableListOf() } += RustHostLibRef(+            projectPath = path,+            taskName = hostTaskName,+            libDir = layout.buildDirectory.dir("rustHostLibs").get().asFile.absolutePath,+        )+    } else {+        logger.warn("rustNativeLib($crate): hostTests = false — JVM unit tests cannot load this crate.")+    }     // Rust file-length gate: fails the build on any *.rs over     // RUST_FILE_LENGTH_LIMIT lines, like the Kotlin FileLength rule (which     // cannot see Rust). Configuration-cache compatible: plain path strings@@ -631,3 +813,85 @@ fun Project.rustNativeLib(         dependsOn(rustFileLength)     } }++/**+ * One host-testable crate registered by [rustNativeLib]: the owning project's+ * path, the host build task name, and the `build/rustHostLibs` dir. Plain+ * strings only, so the configuration cache never sees a Project.+ */+data class RustHostLibRef(+    val projectPath: String,+    val taskName: String,+    val libDir: String,+)++/** Shared `projectPath -> host crates` registry (see [RustHostLibRef]). */+private fun Project.rustHostLibRefs(): MutableMap<String, MutableList<RustHostLibRef>> {+    val extra = rootProject.extensions.extraProperties+    @Suppress("UNCHECKED_CAST")+    return if (extra.has("rustHostLibRefs")) {+        extra.get("rustHostLibRefs") as MutableMap<String, MutableList<RustHostLibRef>>+    } else {+        mutableMapOf<String, MutableList<RustHostLibRef>>().also { extra.set("rustHostLibRefs", it) }+    }+}++/**+ * Wires every unit [Test] task (testDevUnitTest, testDebugUnitTest, ...) so+ * `System.loadLibrary` finds Rust cdylibs on the host JVM: each Test task+ * depends on the host build tasks of this module and of every project it+ * transitively depends on that registered one via [rustNativeLib]+ * (e.g. `:office` also picks up `:library:e2ee-p2p`'s `e2ee_pqc`), and+ * `java.library.path` gains each of their `build/rustHostLibs` dirs.+ *+ * The existing value is appended to, never clobbered: AGP's own+ * `src/test/jniLibs` dirs (which AGP merges into the same property) survive+ * regardless of ordering, because both sides merge. Crates opted out with+ * `hostTests = false` register no task and are skipped cleanly.+ *+ * Laziness: the host tasks are reachable only through these `dependsOn`+ * edges, so assemble/install never build them. Configuration-cache safe:+ * `evaluationDependsOn` pulls transitive deps through evaluation before any+ * state is read, and only plain strings (task paths, dir paths) cross into+ * task configuration — never a Project.+ */+fun Project.wireRustHostLibsForUnitTests() {+    // Deferred to afterEvaluate: the module's own `dependencies {}` block runs+    // after the convention plugin, so the project-dep graph is only complete+    // then. Task wiring uses configureEach, which covers Test tasks whether+    // AGP already created them or creates them later.+    afterEvaluate {+        val self = this@wireRustHostLibsForUnitTests+        val ordered = mutableListOf<String>()+        val seen = HashSet<String>()+        seen += self.path+        val queue = ArrayDeque<String>()+        fun enqueueDepsOf(p: Project) {+            p.configurations.forEach { cfg ->+                cfg.dependencies.filterIsInstance<ProjectDependency>().forEach { dep ->+                    val depPath = dep.path+                    if (seen.add(depPath)) {+                        queue += depPath+                        ordered += depPath+                    }+                }+            }+        }+        enqueueDepsOf(self)+        while (queue.isNotEmpty()) {+            val depPath = queue.removeFirst()+            self.evaluationDependsOn(depPath)+            enqueueDepsOf(self.project(depPath))+        }+        val refs = (listOf(self.path) + ordered).flatMap { rustHostLibRefs()[it].orEmpty() }+        if (refs.isEmpty()) return@afterEvaluate+        self.tasks.withType<Test>().configureEach {+            refs.forEach { ref -> dependsOn("${ref.projectPath}:${ref.taskName}") }+            val sep = File.pathSeparator+            val existing = (systemProperties["java.library.path"] as? String)+                ?.split(sep).orEmpty()+            val merged = (existing + refs.map { it.libDir }).distinct()+            systemProperty("java.library.path", merged.joinToString(sep))+        }+    }+}
build-logic/src/main/kotlin/TestCoverage.kt
diff --git a/build-logic/src/main/kotlin/TestCoverage.kt b/build-logic/src/main/kotlin/TestCoverage.ktnew file mode 100644index 0000000000..39723c249f--- /dev/null+++ b/build-logic/src/main/kotlin/TestCoverage.kt@@ -0,0 +1,101 @@+/**+ * Shared test-coverage infrastructure for `common-conventions-app` and+ * `common-conventions-library`, kept here so the two convention plugins cannot drift:+ * - [MERGED_COVERAGE_EXCLUDES]: class-file patterns stripped from every merged coverage+ *   report. AGP's own `createDevUnitTestCoverageReport` / `createDebugUnitTestCoverageReport`+ *   tasks are AGP-internal `JacocoReportTask`s with **no excludes support** (verified against+ *   AGP 9.5.0-alpha09: the task exposes the class file collection as-is), so the conventions+ *   register their own Gradle `JacocoReport` task ([MERGED_COVERAGE_TASK]) which does.+ * - [ROBOLECTRIC_DEFAULT_SDK]: documented next to the properties file that carries it.+ * - [mergedCoverageClassDirs]: the class files the merged report analyzes.+ */++/** Task name of the per-module merged (unit + instrumented) JaCoCo report. */+const val MERGED_COVERAGE_TASK = "createMergedCoverageReport"++/**+ * Unit-test variant each convention's merged report is built from: apps test `dev`+ * (`testDevUnitTest`, AGP `testBuildType = "dev"`), libraries test `debug`+ * (`testDebugUnitTest`).+ */+const val APP_UNIT_TEST_VARIANT = "dev"+const val LIBRARY_UNIT_TEST_VARIANT = "debug"++/** Stable output location of the merged report, relative to the module build directory. */+const val MERGED_COVERAGE_XML_PATH = "reports/coverage/merged/report.xml"+const val MERGED_COVERAGE_HTML_PATH = "reports/coverage/merged/html"++/**+ * JaCoCo version used to *render* merged reports. Must read the .exec/.ec execution data+ * written by AGP 9.5's coverage agent (JaCoCo 0.8.14); report rendering within the same+ * 0.8.x family is compatible.+ */+const val MERGED_COVERAGE_JACOCO_VERSION = "0.8.14"++/**+ * Robolectric default SDK, mirrored in `build-logic/shared-test-resources/robolectric.properties`+ * (which is the mechanism that actually applies it; this constant only documents the intent+ * next to the coverage/task wiring).+ */+const val ROBOLECTRIC_DEFAULT_SDK = 34++/**+ * Class-file excludes applied to every merged coverage report.+ *+ * JaCoCo file-tree excludes are purely name-based, which settles two of the requested cases:+ * - `*$Companion` is **not** excluded: companion objects hold real code (e.g. factory methods+ *   and default noop implementations), and there is no way to exclude "only empty" companions+ *   with a name pattern. They count as normal code.+ * - `*Preview*` composables are **not** excluded by annotation: JaCoCo cannot filter by+ *   annotation. This is moot in practice — screenshot previews live in the `screenshotTest`+ *   source set, which never enters the report's class directories. Keep `@Preview`+ *   functions out of `src/main` and they stay out of coverage.+ */+val MERGED_COVERAGE_EXCLUDES = listOf(+    // Generated Android code: R, BuildConfig, Manifest.+    "**/R.class",+    "**/R\$*.class",+    "**/BuildConfig.class",+    "**/BuildConfig\$*.class",+    "**/Manifest.class",+    "**/Manifest\$*.class",+    // View/Data Binding (Compose-first repo, but harmless where present).+    "**/databinding/**",+    "**/*Binding.class",+    "**/*Binding\$*.class",+    "**/DataBinderMapperImpl.class",+    // Room/KSP generated implementations.+    "**/*_Impl.class",+    "**/*_Impl\$*.class",+    // kotlinx.serialization generated serializers.+    "**/*\$\$serializer.class",+    "**/*\$\$serializer\$*.class",+    // Compose compiler singletons (remember/composable caches, no coverable logic).+    "**/ComposableSingletons\$*.class",+    // Hilt/Dagger generated code (no Hilt/Dagger in the repo today; future-proofing).+    "**/Hilt_*.class",+    "**/*_Hilt*.class",+    "**/Dagger*.class",+    "**/*_Factory.class",+    "**/*_MembersInjector.class",+    // protobuf-lite generated outer classes.+    "**/*OuterClass*.class",+    // AIDL-generated stubs.+    "**/*\$Stub*.class",+)++/**+ * This module's own compiled classes for [variant], before AGP's offline JaCoCo+ * instrumentation (JaCoCo can only render from original classes), minus+ * [MERGED_COVERAGE_EXCLUDES]. Covers Kotlin and javac output; dependency classes never+ * appear here, so no package filter is needed.+ */+fun org.gradle.api.Project.mergedCoverageClassDirs(variant: String): org.gradle.api.file.FileTree {+    val cap = variant.replaceFirstChar { it.uppercase() }+    return files(+        layout.buildDirectory.dir("intermediates/built_in_kotlinc/$variant/compile${cap}Kotlin/classes"),+        layout.buildDirectory.dir("intermediates/javac/$variant/compile${cap}JavaWithJavac/classes"),+    ).builtBy("compile${cap}Kotlin", "compile${cap}JavaWithJavac").asFileTree.matching {+        MERGED_COVERAGE_EXCLUDES.forEach { exclude(it) }+    }+}
build-logic/src/main/kotlin/common-conventions-app.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts b/build-logic/src/main/kotlin/common-conventions-app.gradle.ktsindex 75ffba8ede..8359eb0bc7 100644--- a/build-logic/src/main/kotlin/common-conventions-app.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-app.gradle.kts@@ -1,4 +1,5 @@ import org.gradle.api.tasks.bundling.AbstractArchiveTask+import org.gradle.testing.jacoco.tasks.JacocoReport  plugins {     id("com.android.application")@@ -17,6 +18,11 @@ detekt {  val libs = the<org.gradle.accessors.dm.LibrariesForLibs>() +// JVM unit tests load Rust cdylibs from build/rustHostLibs (see RustNative.kt):+// every Test task builds + links the host libs of this module and each project+// dep that registers one. Lazy — assemble/install never build them.+wireRustHostLibsForUnitTests()+ /**  * version.txt is read once per build (not once per module): the first  * convention plugin evaluated stashes the (code, name) pair on the Gradle@@ -142,6 +148,17 @@ configure<com.android.build.api.dsl.ApplicationExtension> {         generateLocaleConfig = true     } +    testOptions {+        unitTests.isIncludeAndroidResources = true+    }++    // Repo-wide Robolectric default SDK: build-logic/shared-test-resources holds a+    // robolectric.properties with `sdk=<ROBOLECTRIC_DEFAULT_SDK>` (see TestCoverage.kt),+    // merged by Robolectric as the base config for every test class without an explicit+    // `@Config(sdk = ...)`. Per-module `testOptions.unitTests.isReturnDefaultValues`+    // settings are untouched — that flag is never set here (it hides bugs).+    sourceSets.getByName("test").resources.srcDir(File(rootDir, "build-logic/shared-test-resources"))+     lint {         checkDependencies = true         // `abortOnError` is the only switch that lets lint fail anything. AGP's@@ -389,17 +406,89 @@ dependencies {     testImplementation(libs.kotlin.test)     testImplementation(libs.kotlin.test.junit) +    // JVM unit-test harness shared by every app (plain JUnit, Robolectric including+    // Compose-under-Robolectric via createComposeRule, coroutines-test). The compose+    // test artifact version comes from the BOM, like the main-source Compose deps.+    testImplementation(libs.robolectric)+    testImplementation(libs.androidx.test.core)+    testImplementation(libs.androidx.test.ext.junit)+    testImplementation(libs.kotlinx.coroutines.test)+    testImplementation(platform(libs.androidx.compose.bom))+    testImplementation(libs.androidx.compose.ui.test.junit4)+    // Bare ComponentActivity for Robolectric Compose tests (createComposeRule needs the+    // manifest entry; the artifact ships only a manifest, no code). Scoped to `dev`,+    // the variant unit tests run against (testBuildType = "dev"). `devImplementation`+    // has no static Kotlin-DSL accessor (the `dev` build type is repo-custom, unlike the+    // standard `debug`/`release`), so this uses add() like any custom configuration.+    add("devImplementation", libs.androidx.compose.ui.test.manifest)+     // Launch-no-crash tests (src/androidTest, run on-device via assemble +     // `am instrument`). Wired once here so no app build file needs its own     // block; modules without an androidTest source set compile nothing extra.-    // Deliberately no compose ui-test: its Espresso idle-sync reflects on-    // hidden InputManager APIs that no longer exist on current releases, so-    // every compose-rule test dies before its first line. UiDevice polling-    // covers Compose and non-Compose screens alike with no Espresso involved.+    // NOTE on compose ui-test below: its Espresso idle-sync reflects on hidden+    // InputManager APIs that no longer exist on current releases, so an on-device+    // compose-rule test still dies before its first line. The artifact is present so+    // androidTest sources resolve (and UiDevice polling, which covers Compose and+    // non-Compose screens alike with no Espresso involved, needs no rule at all);+    // prefer UiDevice polling on-device and createComposeRule only under Robolectric.     androidTestImplementation(libs.androidx.test.runner)     androidTestImplementation(libs.androidx.test.core)     androidTestImplementation(libs.androidx.test.ext.junit)     androidTestImplementation(libs.androidx.test.uiautomator)+    androidTestImplementation(libs.kotlinx.coroutines.test)+    androidTestImplementation(platform(libs.androidx.compose.bom))+    androidTestImplementation(libs.androidx.compose.ui.test.junit4)+    androidTestImplementation(libs.androidx.compose.ui.test.manifest)+}++// Merged coverage: a Gradle JacocoReport combining the unit-test .exec (Robolectric+// included) with the on-device .ec files ./test pulls to build/outputs/coverage-manual.+// AGP's own createDevUnitTestCoverageReport cannot take excludes (AGP-internal task+// type), so this task applies MERGED_COVERAGE_EXCLUDES (see TestCoverage.kt) and writes+// XML+HTML to build/reports/coverage/merged/. It depends on testDevUnitTest, so invoking+// it runs the unit tests first; whichever of .exec/.ec exist are merged (fileTrees are+// lenient about missing inputs). Skipped only when there is no execution data at all.+// Configuration-cache safe: all inputs are lazy file collections, no Project capture.+//+// NOTE: this intentionally does NOT apply the Gradle `jacoco` plugin. AGP wires its own+// JaCoCo agent onto unit-test tasks when enableUnitTestCoverage is on, and expects the+// Test tasks to carry no Gradle JacocoTaskExtension (`testDevUnitTest` fails to even+// materialize when one is present). The report below reuses AGP's own `jacocoAnt`+// configuration instead of adding another one — looked up lazily at task-registration+// time (AGP creates it when its JacocoPlugin applies, which can be after this script+// runs), pinned by AGP to the same version family as its own coverage agent so+// .exec/.ec files read cleanly.+val jacocoAntClasspath: FileCollection = objects.fileCollection().from(+    provider { configurations.getByName("jacocoAnt") },+)++tasks.register<JacocoReport>(MERGED_COVERAGE_TASK) {+    group = "verification"+    description = "Merged JaCoCo report for the dev variant: unit-test .exec plus " ++        "androidTest .ec files (whichever exist), with generated-code excludes."+    dependsOn("testDevUnitTest")+    setJacocoClasspath(jacocoAntClasspath)+    classDirectories.from(mergedCoverageClassDirs(APP_UNIT_TEST_VARIANT))+    executionData.from(+        files(layout.buildDirectory.dir("outputs/unit_test_code_coverage/devUnitTest"))+            .asFileTree.matching { include("*.exec") },+        files(layout.buildDirectory.dir("outputs/coverage-manual"))+            .asFileTree.matching { include("*.ec") },+    )+    sourceDirectories.from(+        files(layout.projectDirectory.dir("src/main/java")),+        files(layout.projectDirectory.dir("src/main/kotlin")),+    )+    reports {+        xml.required.set(true)+        xml.outputLocation.set(layout.buildDirectory.file(MERGED_COVERAGE_XML_PATH))+        html.required.set(true)+        html.outputLocation.set(layout.buildDirectory.dir(MERGED_COVERAGE_HTML_PATH))+        csv.required.set(false)+    }+    onlyIf("there is unit or instrumented execution data to report on") {+        executionData.files.isNotEmpty()+    } }  fun DependencyHandlerScope.justSoItShowsAsUsedSomewhere() {
build-logic/src/main/kotlin/common-conventions-library.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts b/build-logic/src/main/kotlin/common-conventions-library.gradle.ktsindex 32e75b81b1..666e76ac96 100644--- a/build-logic/src/main/kotlin/common-conventions-library.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-library.gradle.kts@@ -1,4 +1,5 @@ import org.gradle.api.tasks.bundling.AbstractArchiveTask+import org.gradle.testing.jacoco.tasks.JacocoReport  plugins {     id("com.android.library")@@ -16,6 +17,11 @@ detekt {  val libs = the<org.gradle.accessors.dm.LibrariesForLibs>() +// JVM unit tests load Rust cdylibs from build/rustHostLibs (see RustNative.kt):+// every Test task builds + links the host libs of this module and each project+// dep that registers one. Lazy — assemble/install never build them.+wireRustHostLibsForUnitTests()+ configure<com.android.build.api.dsl.LibraryExtension> {     buildFeatures {         compose = true@@ -95,6 +101,71 @@ dependencies {      testImplementation(libs.kotlin.test)     testImplementation(libs.kotlin.test.junit)++    // JVM unit-test harness shared by every library (plain JUnit, Robolectric including+    // Compose-under-Robolectric via createComposeRule, coroutines-test). The compose+    // test artifact version comes from the BOM, like the main-source Compose deps.+    testImplementation(libs.robolectric)+    testImplementation(libs.androidx.test.core)+    testImplementation(libs.androidx.test.ext.junit)+    testImplementation(libs.kotlinx.coroutines.test)+    testImplementation(platform(libs.androidx.compose.bom))+    testImplementation(libs.androidx.compose.ui.test.junit4)+    // Bare ComponentActivity for Robolectric Compose tests (createComposeRule needs the+    // manifest entry; the artifact ships only a manifest, no code). Scoped to `debug`,+    // the variant unit tests run against.+    debugImplementation(libs.androidx.compose.ui.test.manifest)++    // On-device test harness (src/androidTest; e.g. :library:map's renderer harness).+    // Same Espresso caveat as the app convention: the compose test artifact is present+    // so sources resolve, but prefer UiDevice polling on-device and createComposeRule+    // only under Robolectric.+    androidTestImplementation(libs.androidx.test.runner)+    androidTestImplementation(libs.androidx.test.core)+    androidTestImplementation(libs.androidx.test.ext.junit)+    androidTestImplementation(libs.kotlinx.coroutines.test)+    androidTestImplementation(platform(libs.androidx.compose.bom))+    androidTestImplementation(libs.androidx.compose.ui.test.junit4)+    androidTestImplementation(libs.androidx.compose.ui.test.manifest)+}++// Merged coverage: same shape as the app convention's task (see TestCoverage.kt), but for+// the `debug` variant libraries test (testDebugUnitTest). Writes XML+HTML to+// build/reports/coverage/merged/ with the shared generated-code excludes. Like the app+// side, this deliberately avoids the Gradle `jacoco` plugin (AGP owns the Test-task+// agent wiring) and reuses AGP's own `jacocoAnt` configuration for the report runtime,+// looked up lazily (AGP creates it when its JacocoPlugin applies).+val jacocoAntClasspath: FileCollection = objects.fileCollection().from(+    provider { configurations.getByName("jacocoAnt") },+)++tasks.register<JacocoReport>(MERGED_COVERAGE_TASK) {+    group = "verification"+    description = "Merged JaCoCo report for the debug variant: unit-test .exec plus " ++        "androidTest .ec files (whichever exist), with generated-code excludes."+    dependsOn("testDebugUnitTest")+    setJacocoClasspath(jacocoAntClasspath)+    classDirectories.from(mergedCoverageClassDirs(LIBRARY_UNIT_TEST_VARIANT))+    executionData.from(+        files(layout.buildDirectory.dir("outputs/unit_test_code_coverage/debugUnitTest"))+            .asFileTree.matching { include("*.exec") },+        files(layout.buildDirectory.dir("outputs/coverage-manual"))+            .asFileTree.matching { include("*.ec") },+    )+    sourceDirectories.from(+        files(layout.projectDirectory.dir("src/main/java")),+        files(layout.projectDirectory.dir("src/main/kotlin")),+    )+    reports {+        xml.required.set(true)+        xml.outputLocation.set(layout.buildDirectory.file(MERGED_COVERAGE_XML_PATH))+        html.required.set(true)+        html.outputLocation.set(layout.buildDirectory.dir(MERGED_COVERAGE_HTML_PATH))+        csv.required.set(false)+    }+    onlyIf("there is unit or instrumented execution data to report on") {+        executionData.files.isNotEmpty()+    } }  tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 46e9c6872c..c1e8600bd7 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -191,6 +191,7 @@ kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutine kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" }+kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinxCoroutines" } kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" } kotlin-test-junit = { group = "org.jetbrains.kotlin", name = "kotlin-test-junit", version.ref = "kotlin" } # Stripe compiles against kotlin-parcelize but doesn't publish the runtime as a POM@@ -225,6 +226,9 @@ androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" } androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" } androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" } androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }+# Compose test rule (createComposeRule / createAndroidComposeRule). Versioned by the+# Compose BOM above: on-device (androidTest) and under Robolectric (test).+androidx-compose-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" } # Supplies @PreviewTest, which is what actually marks a @Preview as a screenshot test. screenshot-validation-api = { group = "com.android.tools.screenshot", name = "screenshot-validation-api", version.ref = "composeScreenshot" } androidx-compose-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundation" }
test
diff --git a/test b/testindex ce5a287161..498725a08d 100755--- a/test+++ b/test@@ -2,7 +2,7 @@ # Unified test runner: rust tests + unit tests + instrumented tests, with coverage. # # Usage:-#   ./test [--rust-only|--unit-only|--instrumented-only] [--no-coverage] [--device S] [--dry-run] [--help|-h] <module> [module...]+#   ./test [--rust-only|--unit-only|--instrumented-only] [--no-coverage] [--device S] [--emulator] [--dry-run] [--help|-h] <module> [module...] #   ./test all [flags]                       # every app + library convention module #   ./test games/voxels maps                 # multi-module, minimal gradlew invocations #   ./test voxels                             # shorthand -> games:voxels (same as ./check)@@ -11,7 +11,8 @@ #   ./test --instrumented-only calculator     # only the instrumented phase #   ./test --no-coverage calculator           # skip coverage, plain test tasks #   ./test --device 9 calculator              # Pixel 9 by model (8 = Pixel 8)-#   ./test --device SERIAL calculator         # explicit device serial+#   ./test --device SERIAL calculator         # explicit device serial (physical or emulator)+#   ./test --emulator calculator              # boot/use the Medium_Phone emulator (this is the default) #   ./test --dry-run calculator               # prints what would run without executing # # Module notation mirrors ./check: slash == colon, leading/trailing slashes and@@ -25,24 +26,37 @@ #     workspace crates (--workspace when 'all', else -p flags for in-scope #     crates) plus one cargo llvm-cov per standalone dir. --no-coverage runs #     plain `cargo test --locked` equivalents instead.-#   Unit: app modules -> :mod:createDevUnitTestCoverageReport, library modules-#     -> :mod:createDebugUnitTestCoverageReport (single gradlew invocation with-#     --continue; app vs library decided by grepping the module build.gradle.kts-#     for common-conventions-app, like check's all_module_dirs). --no-coverage+#   Unit: app modules -> :mod:createMergedCoverageReport (which runs+#     :mod:testDevUnitTest first), library modules -> the same merged task for the+#     debug variant (runs :mod:testDebugUnitTest first); single gradlew invocation+#     with --continue; app vs library decided by grepping the module build.gradle.kts+#     for common-conventions-app, like check's all_module_dirs. --no-coverage #     -> :mod:testDevUnitTest / :mod:testDebugUnitTest. Afterwards prints-#     per-module INSTRUCTION covered/missed from-#     build/reports/coverage/test/*/report.xml plus a TOTAL line.+#     per-module INSTRUCTION covered/missed/percent from the MERGED report+#     build/reports/coverage/merged/report.xml (falling back to the unit-only+#     build/reports/coverage/test/*/report.xml when no merged report exists) plus+#     a TOTAL line. Percentages come from the report-level counter, which is the+#     LAST <counter type="INSTRUCTION"> in JaCoCo XML. #   Instrumented: scope = in-scope modules having any *.kt under src/androidTest.-#     Per-module assemble via one gradlew invocation-#     (:mod:assembleDev :mod:assembleDevAndroidTest, --continue), then per module-#     session-install the app APK (./install logic incl. versionCodeOverride and-#     .idsig staging; never plain adb install for the app APK), plain+#     Apps assemble :mod:assembleDev :mod:assembleDevAndroidTest, libraries+#     :mod:assembleDebug :mod:assembleDebugAndroidTest (single gradlew invocation+#     with --continue), then per module: apps session-install the app APK (./install+#     logic incl. versionCodeOverride and .idsig staging; never plain adb install+#     for the app APK), libraries skip straight to the test APK; plain #     `adb install -r` for the test APK, `am instrument` the runner, and with-#     coverage pull /data/data/<pkg>/files/coverage.ec via run-as.+#     coverage pull /data/data/<pkg>/files/coverage.ec via run-as into+#     build/outputs/coverage-manual/ (consumed by the merged report on the next run). #-# Device: --device accepts a serial or 8|9 (Pixel 8 / Pixel 9 by model, mirroring-#   ./install); default is the first non-emulator device. No device connected is-#   a hard error when instrumented tests are in scope (unless --dry-run).+# Device: without --device, instrumented tests ALWAYS run on the Medium_Phone+#   emulator (SDK $ANDROID_SDK_ROOT or /Users/vayun/devmate-android-toolchain/android-sdk),+#   booted headless (-no-window -no-audio -no-boot-anim) when not already running;+#   a physical device is never used unless --device names it explicitly. --device+#   accepts a serial or 8|9 (Pixel 8 / Pixel 9 by model, mirroring ./install).+#   --emulator is accepted for explicitness and means the same as the default.+# Concurrency: the unit phase is lock-free, but emulator boot plus the whole+#   install+instrument loop run under a mkdir-based lock in $TMPDIR, so concurrent+#   `./test --instrumented-only <different modules>` runs serialize instead of+#   colliding on the single emulator. # Big-heap escalation when 'all' is expanded: same flags as install-all #   (-Dorg.gradle.jvmargs=-Xmx46144m ... --max-workers=32). set -euo pipefail@@ -89,15 +103,16 @@ module_application_id() {     "$ROOT/$(echo "$1" | tr ':' '/')/build.gradle.kts" | head -1 } -# APK built for a module; output-metadata.json names the file authoritatively-# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk).+# APK built for an app module; output-metadata.json names the file authoritatively+# (nested modules like cast:tv build tv-dev.apk, not cast-tv-dev.apk). VARIANT is+# dev (apps) or debug (libraries). built_app_apk() {-  local mod="$1" fs_path out_dir meta base_name file_name+  local mod="$1" variant="$2" fs_path out_dir meta base_name file_name   fs_path="$(echo "$mod" | tr ':' '/')"-  out_dir="$ROOT/$fs_path/build/outputs/apk/dev"+  out_dir="$ROOT/$fs_path/build/outputs/apk/$variant"   meta="$out_dir/output-metadata.json"   base_name="${mod##*:}"-  file_name="$base_name-dev.apk"+  file_name="$base_name-$variant.apk"   if [[ -f "$meta" ]]; then     local found     found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"@@ -111,12 +126,12 @@ built_app_apk() { }  built_test_apk() {-  local mod="$1" fs_path out_dir meta base_name file_name+  local mod="$1" variant="$2" fs_path out_dir meta base_name file_name   fs_path="$(echo "$mod" | tr ':' '/')"-  out_dir="$ROOT/$fs_path/build/outputs/apk/androidTest/dev"+  out_dir="$ROOT/$fs_path/build/outputs/apk/androidTest/$variant"   meta="$out_dir/output-metadata.json"   base_name="${mod##*:}"-  file_name="$base_name-dev-androidTest.apk"+  file_name="$base_name-$variant-androidTest.apk"   if [[ -f "$meta" ]]; then     local found     found="$(grep -oE '"outputFile"[[:space:]]*:[[:space:]]*"[^"]+"' "$meta" | head -1 | sed -E 's/.*\"([^\"]+)\"$/\1/')"@@ -129,6 +144,16 @@ built_test_apk() {   return 1 } +# Test-package id for a library module: the namespace is computed in+# common-conventions-library (com.vayunmathur + dotted path, dashes stripped) and the+# androidTest APK appends .test.+library_test_package() {+  local dotted+  dotted="$(echo "$1" | tr '/' '.')"+  dotted="$(echo "$dotted" | tr -d '-')"+  echo "com.vayunmathur.$dotted.test"+}+ # on-device versionCode for a package, empty when not installed. device_version_code() {   "$ADB_BIN" -s "$TARGET_SERIAL" shell pm list packages --show-versioncode "$1" 2>/dev/null \@@ -244,6 +269,8 @@ while [[ $idx -lt ${#ARGS[@]} ]]; do       idx=$((idx + 1)); continue ;;     --no-coverage)       NO_COV=1; idx=$((idx + 1)); continue ;;+    --emulator)+      USE_EMULATOR=1; idx=$((idx + 1)); continue ;;     --dry-run)       DRY_RUN=1; idx=$((idx + 1)); continue ;;     --device=*)@@ -320,17 +347,18 @@ if [[ $RUN_RUST -eq 1 ]]; then   done fi -# --- unit tasks: app -> Dev variant, library (or other) -> Debug variant ---+# --- unit tasks: merged coverage report per module (runs the unit tests first);+# app -> Dev variant, library (or other) -> Debug variant (decided inside the+# convention plugin, so both spellings are the same task name) --- UNIT_TASKS=() if [[ $RUN_UNIT -eq 1 ]]; then   for mod in "${MODS[@]}"; do     gmod="$(echo "$mod" | tr '/' ':')"-    if is_app_module "$mod"; then-      if [[ $NO_COV -eq 1 ]]; then UNIT_TASKS+=(":$gmod:testDevUnitTest");-      else UNIT_TASKS+=(":$gmod:createDevUnitTestCoverageReport"); fi+    if [[ $NO_COV -eq 1 ]]; then+      if is_app_module "$mod"; then UNIT_TASKS+=(":$gmod:testDevUnitTest");+      else UNIT_TASKS+=(":$gmod:testDebugUnitTest"); fi     else-      if [[ $NO_COV -eq 1 ]]; then UNIT_TASKS+=(":$gmod:testDebugUnitTest");-      else UNIT_TASKS+=(":$gmod:createDebugUnitTestCoverageReport"); fi+      UNIT_TASKS+=(":$gmod:createMergedCoverageReport")     fi   done fi@@ -354,7 +382,11 @@ INST_TASKS=() if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then   for mod in "${INST_MODS[@]}"; do     gmod="$(echo "$mod" | tr '/' ':')"-    INST_TASKS+=(":$gmod:assembleDev" ":$gmod:assembleDevAndroidTest")+    if is_app_module "$mod"; then+      INST_TASKS+=(":$gmod:assembleDev" ":$gmod:assembleDevAndroidTest")+    else+      INST_TASKS+=(":$gmod:assembleDebug" ":$gmod:assembleDebugAndroidTest")+    fi   done fi @@ -365,22 +397,103 @@ if [[ $NO_COV -eq 1 ]]; then echo "Coverage: off (--no-coverage)"; else echo "Co echo ""  # --- device selection (needed for the instrumented phase) ---+# Without --device, instrumented tests ALWAYS run on the Medium_Phone emulator:+# never pick a physical device implicitly. --device with a serial/8/9 still selects+# a physical device (or a specific emulator) explicitly. ADB_BIN=""+EMULATOR_BIN=""+EMULATOR_SERIAL=""+EMULATOR_AVD="${EMULATOR_AVD:-Medium_Phone}"+# SDK location: env first, then the checked-in toolchain path, then PATH lookup.+ANDROID_SDK_DIR=""+for sdk_base in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk" "$HOME/Library/Android/sdk" "/Users/vayun/devmate-android-toolchain/android-sdk"; do+  if [[ -n "$sdk_base" && -d "$sdk_base/platform-tools" ]]; then+    ANDROID_SDK_DIR="$sdk_base"+    break+  fi+done+if [[ -n "$ANDROID_SDK_DIR" && -x "$ANDROID_SDK_DIR/platform-tools/adb" ]]; then+  ADB_BIN="$ANDROID_SDK_DIR/platform-tools/adb"+elif command -v adb >/dev/null 2>&1; then+  ADB_BIN="adb"+fi+if [[ -n "$ANDROID_SDK_DIR" && -x "$ANDROID_SDK_DIR/emulator/emulator" ]]; then+  EMULATOR_BIN="$ANDROID_SDK_DIR/emulator/emulator"+elif command -v emulator >/dev/null 2>&1; then+  EMULATOR_BIN="emulator"+fi++# mkdir-based emulator lock (macOS has no flock): serializes emulator boot and the+# install+instrument loop across concurrent ./test runs. Lock-free unit phase is+# unaffected. Stale locks (owner pid dead) are broken and retried.+EMULATOR_LOCK_DIR="${TMPDIR:-/tmp}/modern-apps-test-emulator.lock"+LOCK_HELD=0+acquire_emulator_lock() {+  local owner+  while true; do+    if mkdir "$EMULATOR_LOCK_DIR" 2>/dev/null; then+      echo $$ > "$EMULATOR_LOCK_DIR/pid"+      LOCK_HELD=1+      return 0+    fi+    owner="$(cat "$EMULATOR_LOCK_DIR/pid" 2>/dev/null || echo "")"+    if [[ -n "$owner" ]] && ! kill -0 "$owner" 2>/dev/null; then+      echo "Warning: breaking stale emulator lock (owner pid $owner dead)."+      rm -rf "$EMULATOR_LOCK_DIR"+      continue+    fi+    sleep 2+  done+}+release_emulator_lock() {+  if [[ $LOCK_HELD -eq 1 ]]; then+    rm -rf "$EMULATOR_LOCK_DIR"+    LOCK_HELD=0+  fi+}++# Boot the emulator headless if no emulator is online yet; sets EMULATOR_SERIAL.+# The AVD is arm64, like the host, so no -PemulatorAbi is needed.+ensure_emulator_running() {+  [[ -n "$ADB_BIN" ]] || { echo "Error: adb not found; cannot drive the emulator." >&2; return 1; }+  local serial+  serial="$("$ADB_BIN" devices 2>/dev/null | awk '$2=="device" && $1 ~ /^emulator-/ {print $1; exit}')"+  if [[ -n "$serial" ]]; then+    EMULATOR_SERIAL="$serial"+    echo "Emulator already running: $EMULATOR_SERIAL"+    return 0+  fi+  [[ -n "$EMULATOR_BIN" ]] || { echo "Error: emulator binary not found (SDK dir: ${ANDROID_SDK_DIR:-<none>})." >&2; return 1; }+  echo "Booting emulator AVD $EMULATOR_AVD headless..."+  "$EMULATOR_BIN" -avd "$EMULATOR_AVD" -no-window -no-audio -no-boot-anim -read-only >/dev/null 2>&1 &+  local waited=0+  while [[ $waited -lt 300 ]]; do+    sleep 5+    waited=$((waited + 5))+    serial="$("$ADB_BIN" devices 2>/dev/null | awk '$2=="device" && $1 ~ /^emulator-/ {print $1; exit}')"+    [[ -z "$serial" ]] && continue+    if [[ "$("$ADB_BIN" -s "$serial" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r')" == "1" ]]; then+      EMULATOR_SERIAL="$serial"+      echo "Emulator booted: $EMULATOR_SERIAL (${waited}s)"+      return 0+    fi+  done+  echo "Error: emulator $EMULATOR_AVD did not finish booting within 300s." >&2+  return 1+}+ NEED_DEVICE=0 if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then NEED_DEVICE=1; fi if [[ $NEED_DEVICE -eq 1 ]]; then-  if command -v adb >/dev/null 2>&1; then-    ADB_BIN="adb"-  else-    for adb_base in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "$HOME/Android/Sdk" "$HOME/Library/Android/sdk"; do-      if [[ -n "$adb_base" && -x "$adb_base/platform-tools/adb" ]]; then-        ADB_BIN="$adb_base/platform-tools/adb"-        break-      fi-    done-  fi   TARGET_SERIAL=""-  if [[ -n "$ADB_BIN" ]]; then+  if [[ -n "$DEVICE_HINT" ]]; then+    # Explicit device: serial match, or 8|9 Pixel-by-model (physical or emulator,+    # mirroring ./install). Physical devices are only ever used this way.+    if [[ -z "$ADB_BIN" ]]; then+      echo "Error: adb not found; cannot select a target device." >&2+      echo "Install Android platform-tools and put adb on PATH (or set ANDROID_HOME)." >&2+      exit 1+    fi     if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then       # hint 8 = model Pixel_8; 9 = model Pixel_9* (covers Pixel_9 and Pixel_9_Pro_XL).       while read -r dev_line; do@@ -410,16 +523,6 @@ if [[ $NEED_DEVICE -eq 1 ]]; then           break         fi       done < <("$ADB_BIN" devices -l 2>/dev/null)-    else-      while read -r dev_line; do-        dev_serial="$(echo "$dev_line" | awk '{print $1}')"-        dev_state="$(echo "$dev_line" | awk '{print $2}')"-        [[ "$dev_state" == "device" ]] || continue-        case "$dev_serial" in emulator*) continue;; esac-        case "$dev_serial" in "List"*) continue;; esac-        TARGET_SERIAL="$dev_serial"-        break-      done < <("$ADB_BIN" devices -l 2>/dev/null)     fi   fi   if [[ -z "$ADB_BIN" ]]; then@@ -434,24 +537,27 @@ if [[ $NEED_DEVICE -eq 1 ]]; then     export ANDROID_SERIAL="$TARGET_SERIAL"     if [[ "$DEVICE_HINT" == "8" || "$DEVICE_HINT" == "9" ]]; then       echo "Target device: $ANDROID_SERIAL (Pixel $DEVICE_HINT)"-    elif [[ -n "$DEVICE_HINT" ]]; then-      echo "Target device: $ANDROID_SERIAL (explicit --device)"     else-      echo "Target device: $ANDROID_SERIAL (first connected device not starting with 'emulator')"+      echo "Target device: $ANDROID_SERIAL (explicit --device)"     fi-  elif [[ -n "$DEVICE_HINT" ]]; then-    echo "Error: no connected device matching '$DEVICE_HINT' found (check 'adb devices')." >&2-    exit 1   elif [[ $DRY_RUN -eq 1 ]]; then-    echo "[DRY-RUN] Warning: no non-emulator device connected; ANDROID_SERIAL not set."+    echo "[DRY-RUN] Would ensure the $EMULATOR_AVD emulator is running (boot headless if needed)."+    TARGET_SERIAL="<emulator>"   else-    echo "Error: No non-emulator device connected." >&2-    echo "Connect a physical device (check 'adb devices'); refusing to test on an emulator." >&2-    exit 1+    # Default path: emulator (never a physical device without --device). The lock+    # serializes boot + install/instrument against concurrent ./test runs; the trap+    # below releases it on exit. Lock-free unit phase already ran (or was skipped), so+    # holding the lock from here to the end of the instrumented phase is correct.+    acquire_emulator_lock+    trap release_emulator_lock EXIT+    ensure_emulator_running || exit 1+    TARGET_SERIAL="$EMULATOR_SERIAL"+    export ANDROID_SERIAL="$TARGET_SERIAL"+    echo "Target device: $ANDROID_SERIAL (emulator $EMULATOR_AVD)"   fi else   TARGET_SERIAL="${ANDROID_SERIAL:-}"-  if command -v adb >/dev/null 2>&1; then ADB_BIN="adb"; fi+  if [[ -z "$ADB_BIN" ]] && command -v adb >/dev/null 2>&1; then ADB_BIN="adb"; fi fi  # --- extra Gradle args: --continue so one broken module doesn't block the rest ---@@ -543,7 +649,7 @@ if [[ $DRY_RUN -eq 1 ]]; then   if [[ $RUN_UNIT -eq 1 ]]; then     echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${UNIT_TASKS[*]}$gradle_args_str"     for mod in "${MODS[@]}"; do-      echo "[DRY-RUN] Would summarize unit coverage from $mod/build/reports/coverage/test/*/report.xml"+      echo "[DRY-RUN] Would summarize merged coverage from $mod/build/reports/coverage/merged/report.xml (fall back to $mod/build/reports/coverage/test/*/report.xml)"     done   else     echo "[DRY-RUN] Unit phase skipped."@@ -551,18 +657,29 @@ if [[ $DRY_RUN -eq 1 ]]; then   if [[ $RUN_INST -eq 1 ]]; then     if [[ ${#INST_MODS[@]} -gt 0 ]]; then       echo "[DRY-RUN] Would execute: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"+      if [[ -z "$DEVICE_HINT" ]]; then+        echo "[DRY-RUN] Would ensure the $EMULATOR_AVD emulator is running (boot headless if needed), under the emulator lock."+      fi       for mod in "${INST_MODS[@]}"; do         colon_mod="$(echo "$mod" | tr '/' ':')"-        pkg="$(module_application_id "$colon_mod")"-        [[ -z "$pkg" ]] && pkg="<applicationId from $mod/build.gradle.kts>"         base="${mod##*/}"-        echo "[DRY-RUN] Would session-install $pkg from $mod/build/outputs/apk/dev/$base-dev.apk (or output-metadata.json outputFile)"-        echo "[DRY-RUN] Would run: adb install -r $mod/build/outputs/apk/androidTest/dev/$base-dev-androidTest.apk"+        if is_app_module "$mod"; then+          variant="dev"+          pkg="$(module_application_id "$colon_mod")"+          [[ -z "$pkg" ]] && pkg="<applicationId from $mod/build.gradle.kts>"+          echo "[DRY-RUN] Would session-install $pkg from $mod/build/outputs/apk/$variant/$base-$variant.apk (or output-metadata.json outputFile)"+          test_pkg="$pkg.test"+        else+          variant="debug"+          test_pkg="$(library_test_package "$mod")"+          echo "[DRY-RUN] Would install test APK only (library has no app APK): $mod/build/outputs/apk/androidTest/$variant/$base-$variant-androidTest.apk"+        fi+        echo "[DRY-RUN] Would run: adb install -r $mod/build/outputs/apk/androidTest/$variant/$base-$variant-androidTest.apk"         if [[ $NO_COV -eq 1 ]]; then-          echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r $pkg.test/androidx.test.runner.AndroidJUnitRunner"+          echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r $test_pkg/androidx.test.runner.AndroidJUnitRunner"         else-          echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r -e coverage true -e coverageFilePath /data/data/$pkg/files/coverage.ec $pkg.test/androidx.test.runner.AndroidJUnitRunner"-          echo "[DRY-RUN] Would pull: adb exec-out run-as $pkg cat files/coverage.ec > $mod/build/outputs/coverage-manual/$pkg.ec"+          echo "[DRY-RUN] Would run: adb -s \${ANDROID_SERIAL:-<device>} shell am instrument -w -r -e coverage true -e coverageFilePath /data/data/$test_pkg/files/coverage.ec $test_pkg/androidx.test.runner.AndroidJUnitRunner"+          echo "[DRY-RUN] Would pull: adb exec-out run-as $test_pkg cat files/coverage.ec > $mod/build/outputs/coverage-manual/$test_pkg.ec"         fi       done     else@@ -680,14 +797,19 @@ if [[ $RUN_UNIT -eq 1 ]]; then   [[ $UNIT_RC -ne 0 ]] && echo "Warning: unit test tasks reported failures (exit $UNIT_RC)."   if [[ $NO_COV -eq 0 ]]; then     echo ""-    echo "Unit coverage (INSTRUCTION counters):"+    echo "Coverage (MERGED report when present, else unit-only; INSTRUCTION counters):"     TOTAL_COV=0; TOTAL_MISS=0     for mod in "${MODS[@]}"; do-      xml=""-      while IFS= read -r f; do-        case "$f" in "" ) continue;; esac-        xml="$f"; break-      done < <(find "$ROOT/$mod/build/reports/coverage/test" -maxdepth 2 -name report.xml 2>/dev/null | sort)+      xml=""; kind=""+      if [[ -f "$ROOT/$mod/build/reports/coverage/merged/report.xml" ]]; then+        xml="$ROOT/$mod/build/reports/coverage/merged/report.xml"+        kind="merged"+      else+        while IFS= read -r f; do+          case "$f" in "" ) continue;; esac+          xml="$f"; kind="unit"; break+        done < <(find "$ROOT/$mod/build/reports/coverage/test" -maxdepth 2 -name report.xml 2>/dev/null | sort)+      fi       if [[ -z "$xml" || ! -f "$xml" ]]; then         echo "  $mod: no coverage data (no tests?)"         continue@@ -700,15 +822,23 @@ if [[ $RUN_UNIT -eq 1 ]]; then         echo "  $mod: no coverage data (no tests?)"         continue       fi-      echo "  $mod: covered=$covered missed=$missed"+      total=$((covered + missed))+      if [[ $total -gt 0 ]]; then pct="$(awk "BEGIN {printf \"%.1f\", 100*$covered/$total}")"; else pct="100.0"; fi+      echo "  $mod [$kind]: $pct% (covered=$covered missed=$missed)"       TOTAL_COV=$((TOTAL_COV + covered))       TOTAL_MISS=$((TOTAL_MISS + missed))     done-    echo "  TOTAL: covered=$TOTAL_COV missed=$TOTAL_MISS"+    grand=$((TOTAL_COV + TOTAL_MISS))+    if [[ $grand -gt 0 ]]; then total_pct="$(awk "BEGIN {printf \"%.1f\", 100*$TOTAL_COV/$grand}")"; else total_pct="100.0"; fi+    echo "  TOTAL: $total_pct% (covered=$TOTAL_COV missed=$TOTAL_MISS)"   fi fi  # --- instrumented phase: assemble, session-install, run, pull coverage ---+# Runs under the emulator lock acquired during device selection (default path), so+# concurrent ./test runs serialize their install+instrument loops. UD lock is NOT held+# when --device selected an explicit device: several agents may share one physical+# device only if they coordinate elsewhere (the lock is emulator-scoped by design). if [[ $RUN_INST -eq 1 && ${#INST_MODS[@]} -gt 0 ]]; then   echo ""   echo "Running: $SCRIPT_DIR/gradlew ${INST_TASKS[*]}$gradle_args_str"