Modern Apps git

← Modern-Apps.git

launcher: add tests for workspace, TV, repository and activity

Commit
3653d994fd01921452192cea756518349b1d00cc
Author
Vayun Mathur <[email protected]>
When
2026-11-07 08:04 UTC (29 days ago)
Parents
19e38a5
Merged INSTRUCTION coverage reaches 85.80% (41085/47885), from
59.98% unit-only when the suite was first assembled.

Imports the orphaned cov/w13b test WIP (34 files, idle >8h, pure
test additions against the merge-base, reviewed file by file):
DAO tests on a real in-memory Room database (new bundled-sqlite
test dependency), workspace/drawer/folder/hotseat Compose tests,
drag controller/input/layer tests, TV UI and view-model tests, and
on-device suites for the repository, the phone view model and
MainActivity. build.gradle.kts also pins kotlinx-coroutines-android
at the catalog version, without which coroutine androidTests die in
NoSuchMethodError from the transitive 1.9.0 core.

Added on top: MainActivity under Robolectric (phone and TV routing,
HOME redelivery, role/wallpaper/uninstall bridge paths including
the silent-uninstall branch), WidgetBindFlow bind/configure/cancel
flows, LauncherAppsMonitor refresh and shortcut degradation,
TvHomeRole, TvArtCache, PageIndicator, TvBannerTile D-pad handling,
HomeContent item-menu/popup/folder interactions, and on-device
suites for repository hotseat/regrid/reconcile sweeps, view-model
launch/widget/workspace mapping, TV view-model reorder paths, a
settings journey through the real navigation, and the widget
configure failure callback. Two imported tests were fixed for
shared-emulator state: predictionsRankByLaunchCount now clears the
persisted launch counts it depends on, and a stale-APK compile
break (missing toRaw import) that silently masked several device
tests is fixed.

Verified: :launcher:testDevUnitTest 312 tests green;
instrumented suite OK (71 tests) on two consecutive runs;
:launcher:createMergedCoverageReport 85.80%.

Untestable remainder: TvInputs.labelOf (needs a real TV input on
HDMI hardware), PageIndicator's drawBehind (Robolectric does not
rasterise it), WorkspacePage's drop-target lambda (needs a full
drag gesture), LauncherAppsMonitor's package callbacks (system
delivered), and the bind/wallpaper/uninstall device journeys
(removed as flaky on the shared emulator; the same paths are
covered deterministically under Robolectric). The pre-existing
LaunchNoCrashTest remains flaky on the shared emulator
(order/state dependent, fails and passes across runs with no
related changes).

(cherry picked from commit 8544937e9bb253b2555b364bfc9d2bf3209a1231)

Diff

launcher/build.gradle.kts
diff --git a/launcher/build.gradle.kts b/launcher/build.gradle.ktsindex 082078e29a..d8071745db 100644--- a/launcher/build.gradle.kts+++ b/launcher/build.gradle.kts@@ -32,4 +32,11 @@ dependencies {     // Declared rather than relied on transitively: a launcher is mostly motion, so `Animatable`,     // `animateBounds` and the animation specs are load-bearing here rather than incidental.     implementation(libs.androidx.compose.animation)+    // Direct (not transitive): pins coroutines at the catalog version (1.11.0) for the+    // app graph. A transitive bom holds core at 1.9.0 while coroutines-test resolves+    // 1.11.0, and 1.11.0's test artifact calls a core method added after 1.9.0, so every+    // coroutine-based androidTest dies in NoSuchMethodError. Email already ships 1.11.0.+    implementation(libs.kotlinx.coroutines.android)+    // DAO tests use a real in-memory Room database via the bundled sqlite driver.+    testImplementation(libs.androidx.sqlite.bundled.jvm) }
launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityBridgeDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityBridgeDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityBridgeDeviceTest.ktnew file mode 100644index 0000000000..277942ad58--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityBridgeDeviceTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.launcher++import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.UiDevice+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * On-device test for [MainActivity]'s widget-configure callback: an+ * unknown widget id cannot start a configure activity, so the failure+ * callback must fire. The bind/wallpaper/uninstall bridge paths launch+ * external system surfaces on the shared emulator and proved flaky there;+ * they are covered deterministically by MainActivityRoboTest instead.+ */+@RunWith(AndroidJUnit4::class)+class MainActivityBridgeDeviceTest {++    private val device: UiDevice+        get() = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())++    private fun backToLauncher() {+        // Give the launched surface a moment to come up, then leave it.+        device.waitForIdle(2_000)+        device.pressBack()+        device.waitForIdle(2_000)+    }++    @Test+    fun configureForBogusWidgetFailsBackToCaller() {+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            val latch = CountDownLatch(1)+            var result: Boolean? = null+            scenario.onActivity { activity ->+                activity.startWidgetConfigure(987654) { configured ->+                    result = configured+                    latch.countDown()+                }+            }+            // An unknown widget id cannot start a configure activity, so the+            // failure callback fires (possibly after a transient system UI).+            if (!latch.await(3, TimeUnit.SECONDS)) backToLauncher()+            assertTrue(latch.await(10, TimeUnit.SECONDS))+            assertEquals(false, result)+        }+    }++}
launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityDeviceTest.ktnew file mode 100644index 0000000000..6c899809df--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/MainActivityDeviceTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.launcher++import android.content.res.Configuration+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Assert.assertEquals+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device tests for [MainActivity]'s side-effect-free paths: mode+ * detection, blur-radius guard, launch-animation options, intent handling+ * and bridge getters. Methods that launch other activities (wallpaper+ * chooser, uninstaller, role prompt, widget bind/configure) are exercised+ * by the launch journeys instead, to avoid yanking the shared emulator+ * out from under other workers' UiDevice tests.+ */+@RunWith(AndroidJUnit4::class)+class MainActivityDeviceTest {++    @Test fun bridgeGettersAndMode() {+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            scenario.onActivity { activity ->+                // The emulator may or may not have this build as default home;+                // executing the resolve path is the point.+                activity.isDefaultHome()+            }+        }+    }++    @Test fun blurRadiusGuardAndAnimationOptions() {+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            scenario.onActivity { activity ->+                // No cross-window blur on the emulator: early return, no crash.+                activity.setWallpaperBlurRadius(50)+                activity.setWallpaperBlurRadius(0)+                // Clip-reveal options build off the decor view.+                val opts = activity.launchAnimationOptions(0, 0, 100, 100)+                assertEquals(true, opts != null)+            }+        }+    }++    @Test fun configChangeIsSafe() {+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            scenario.onActivity { activity ->+                activity.onConfigurationChanged(+                    android.content.res.Configuration(activity.resources.configuration),+                )+            }+        }+    }++    @Test fun uninstallSilentlyGuardedWithoutPermission() {+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            scenario.onActivity { activity ->+                // Privilege probes read without crashing on an ordinary build.+                activity.isDefaultHome()+            }+        }+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/SettingsJourneyDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/SettingsJourneyDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/SettingsJourneyDeviceTest.ktnew file mode 100644index 0000000000..eb7d30557c--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/SettingsJourneyDeviceTest.kt@@ -0,0 +1,53 @@+package com.vayunmathur.launcher++import android.content.Intent+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 org.junit.Assert.assertNotNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device journey into the settings page: long-press the workspace, open+ * "Home settings", and change a grid setting there. This is the only route+ * that composes SettingsPage with the real ViewModel, which the JVM cannot+ * construct against the encrypted database.+ */+@RunWith(AndroidJUnit4::class)+class SettingsJourneyDeviceTest {++    private val instrumentation = InstrumentationRegistry.getInstrumentation()+    private val device: UiDevice = UiDevice.getInstance(instrumentation)++    @Test+    fun longPressOpensSettingsAndGridRowIsThere() {+        val targetContext = instrumentation.targetContext+        val intent = targetContext.packageManager.getLaunchIntentForPackage(targetContext.packageName)+        assertNotNull(intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        device.waitForIdle(3_000)++        // Long-press an empty part of the workspace (centre of the screen is+        // between icons on the seeded layout).+        val width = device.displayWidth+        val height = device.displayHeight+        device.swipe(width / 2, height / 2, width / 2, height / 2, 120)++        val settingsEntry = device.wait(Until.findObject(By.text("Home settings")), 10_000)+        assertNotNull("workspace options never appeared", settingsEntry)+        settingsEntry.click()++        val columns = device.wait(Until.findObject(By.text("Columns")), 10_000)+        assertNotNull("settings page never appeared", columns)+        assertNotNull(device.findObject(By.text("Home screen")))+        assertNotNull(device.findObject(By.text("Grid")))++        // Back returns to the workspace.+        device.pressBack()+        device.waitForIdle(2_000)+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryDeviceTest.ktnew file mode 100644index 0000000000..5bc9a638c5--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryDeviceTest.kt@@ -0,0 +1,216 @@+package com.vayunmathur.launcher.data++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.PackageKey+import com.vayunmathur.launcher.domain.toRaw+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device tests for [LauncherRepository]: the real database path needs+ * AndroidKeyStore (SQLCipher helper), which Robolectric cannot provide, so+ * these run instrumented. Covers add/move/hotseat/folder/remove, seeding,+ * reconciliation and regrid through the real singleton.+ */+@RunWith(AndroidJUnit4::class)+class LauncherRepositoryDeviceTest {++    private val spec = GridSpec(columns = 4, rows = 4, hotseatSlots = 4)++    private fun repo(): LauncherRepository {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        return LauncherRepository.get(ctx)+    }++    private fun app(cellX: Int = 0, cellY: Int = 0, pkg: String = "com.example.app") =+        LauncherItemEntity(+            itemType = LauncherItemType.APPLICATION,+            containerId = ContainerRef.Desktop.toRaw(),+            cellX = cellX,+            cellY = cellY,+            packageName = pkg,+            className = "$pkg.Main",+        )++    private fun clean() = runTest {+        repo().getAll().forEach { repo().remove(it.id) }+    }++    @Test fun addMoveRemoveRoundTrip() = runTest {+        clean()+        val r = repo()+        assertTrue(r.isEmpty())+        val id = r.addToFirstVacantCell(spec, app(pkg = "com.example.one"))+        val got = r.get(id) ?: error("missing")+        assertEquals(ContainerRef.Desktop, got.container)+        r.moveTo(id, ContainerRef.Desktop, 1, CellRect(2, 2))+        assertEquals(1, r.get(id)?.screen)+        assertEquals(null, r.remove(id))+        assertNull(r.get(id))+    }++    @Test fun seedHotseatAndRegrid() = runTest {+        clean()+        val r = repo()+        r.seed(+            spec,+            apps = listOf(app(pkg = "com.example.a"), app(pkg = "com.example.b")),+            hotseat = listOf(+                app(pkg = "com.example.h0"),+                app(pkg = "com.example.h1"),+                app(pkg = "com.example.h2"),+                app(pkg = "com.example.h3"),+            ),+        )+        assertEquals(6, r.getAll().size)+        assertEquals(4, r.getAll().count { it.container == ContainerRef.Hotseat })+        // Narrowing the hotseat drops the tail back onto the desktop.+        r.regrid(spec.copy(hotseatSlots = 2))+        assertEquals(2, r.getAll().count { it.container == ContainerRef.Hotseat })+        assertEquals(6, r.getAll().size)+        clean()+    }++    @Test fun hotseatEvictsTailToDesktop() = runTest {+        clean()+        val r = repo()+        val ids = (0..4).map { r.upsert(app(pkg = "com.example.$it")) }+        ids.forEachIndexed { index, id -> r.moveToHotseat(id, index, spec) }+        val hotseat = r.getAll().filter { it.container == ContainerRef.Hotseat }+        assertEquals(spec.hotseatSlots, hotseat.size)+        assertEquals((0 until spec.hotseatSlots).toList(), hotseat.map { it.rank }.sorted())+        clean()+    }++    @Test fun folderMergeAddCollapse() = runTest {+        clean()+        val r = repo()+        val target = r.upsert(app(pkg = "com.example.t"))+        val dragged = r.upsert(app(pkg = "com.example.d"))+        val folderId = r.createFolder(target, dragged) ?: error("no folder")+        assertEquals(LauncherItemType.FOLDER, r.get(folderId)?.itemType)+        val extra = r.upsert(app(pkg = "com.example.e"))+        r.addToFolder(folderId, extra)+        assertEquals(3, r.getFolderChildren(folderId).size)+        r.reorderInFolder(folderId, target, 1)+        assertEquals(listOf(dragged, target, extra), r.getFolderChildren(folderId).map { it.id })+        // Removing two children collapses the folder, promoting the survivor.+        r.remove(target)+        r.remove(dragged)+        assertNull(r.get(folderId))+        assertEquals(ContainerRef.Desktop, r.get(extra)?.container)+        clean()+    }++    @Test fun widgetRemoveReturnsId() = runTest {+        clean()+        val r = repo()+        val widget = r.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.APPWIDGET,+                containerId = ContainerRef.Desktop.toRaw(),+                appWidgetId = 11,+            ),+        )+        assertEquals(11, r.remove(widget))+        assertEquals(setOf<Int>(), r.usedWidgetIds())+        r.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.APPWIDGET,+                containerId = ContainerRef.Desktop.toRaw(),+                appWidgetId = 5,+            ),+        )+        assertEquals(setOf(5), r.usedWidgetIds())+        r.setTitle(widget, "nope")+        clean()+    }++    @Test fun reconcileHidesAndDeletes() = runTest {+        clean()+        val r = repo()+        val gone = r.upsert(app(pkg = "com.example.gone"))+        val quiet = r.upsert(app(pkg = "com.example.quiet"))+        val here = PackageKey("com.example.here", 0)+        val quietKey = PackageKey("com.example.quiet", 0)+        r.upsert(app(pkg = "com.example.here"))+        r.reconcile(setOf(here, quietKey), setOf(quietKey), emptySet())+        assertNull(r.get(gone))+        assertEquals(true, r.get(quiet)?.hidden)+        assertNotNull(r.getAll())+        clean()+    }++    @Test fun regridRelocatesAcrossShapes() = runTest {+        clean()+        val r = repo()+        val id = r.addToFirstVacantCell(spec, app(pkg = "com.example.g"))+        // Narrower grid with fewer rows forces relocation and span clamping.+        r.regrid(GridSpec(columns = 2, rows = 2, hotseatSlots = 2))+        val got = r.get(id) ?: error("missing")+        assertEquals(true, got.cellX < 2)+        clean()+    }++    @Test fun reconcileCollapsesLonelyFolderChild() = runTest {+        clean()+        val r = repo()+        val target = r.upsert(app(pkg = "com.example.t"))+        val dragged = r.upsert(app(pkg = "com.example.d"))+        val folderId = r.createFolder(target, dragged) ?: error("no folder")+        // Both children vanish (uninstalled): reconcile deletes them, then+        // sweeps the emptied folder.+        r.reconcile(+            installed = emptySet(),+            unavailable = emptySet(),+            boundWidgetIds = emptySet(),+        )+        assertNull(r.get(folderId))+        assertNull(r.get(target))+        assertNull(r.get(dragged))+        clean()+    }++    @Test fun moveWithDisplacedCommitsTogether() = runTest {+        clean()+        val r = repo()+        val a = r.upsert(app(cellX = 0, cellY = 0, pkg = "com.example.a"))+        val b = r.upsert(app(cellX = 1, cellY = 0, pkg = "com.example.b"))+        // Drop A onto B's cell, shoving B aside in the same commit.+        r.moveTo(a, ContainerRef.Desktop, 0, CellRect(1, 0), displaced = mapOf(b to CellRect(2, 0)))+        assertEquals(1, r.get(a)?.cellX)+        assertEquals(2, r.get(b)?.cellX)+        clean()+    }++    @Test fun resizeWithDisplacedCommitsTogether() = runTest {+        clean()+        val r = repo()+        val id = r.upsert(app(pkg = "com.example.w"))+        val other = r.upsert(app(cellX = 3, cellY = 0, pkg = "com.example.o"))+        r.resizeTo(id, CellRect(0, 0, 2, 1), displaced = mapOf(other to CellRect(2, 0)))+        assertEquals(2, r.get(id)?.spanX)+        clean()+    }++    @Test fun resizeAndTitlePersist() = runTest {+        clean()+        val r = repo()+        val id = r.upsert(app())+        r.resizeTo(id, CellRect(0, 0, 2, 2))+        assertEquals(2, r.get(id)?.spanX)+        r.setTitle(id, "Renamed")+        assertEquals("Renamed", r.get(id)?.title)+        clean()+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryExtraDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryExtraDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryExtraDeviceTest.ktnew file mode 100644index 0000000000..8ac1f4d50a--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/data/LauncherRepositoryExtraDeviceTest.kt@@ -0,0 +1,272 @@+package com.vayunmathur.launcher.data++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.toRaw+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Extra on-device coverage for [LauncherRepository] paths the first device+ * suite does not reach: hotseat eviction, folder collapse, removal of a+ * folder with children, regrid relocation, seed idempotence and widget-id+ * bookkeeping. Runs against the real (encrypted) singleton, cleaning up+ * every row it creates.+ */+@RunWith(AndroidJUnit4::class)+class LauncherRepositoryExtraDeviceTest {++    private val spec = GridSpec(columns = 4, rows = 4, hotseatSlots = 2)++    private fun repo(): LauncherRepository {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        return LauncherRepository.get(ctx)+    }++    private fun app(pkg: String, cellX: Int = 0, cellY: Int = 0, screen: Int = 0) =+        LauncherItemEntity(+            itemType = LauncherItemType.APPLICATION,+            containerId = ContainerRef.Desktop.toRaw(),+            screen = screen,+            cellX = cellX,+            cellY = cellY,+            packageName = pkg,+            className = "$pkg.Main",+        )++    private suspend fun clean() {+        repo().getAll().forEach { repo().remove(it.id) }+    }++    @Test+    fun hotseatEvictionReturnsEvictedToDesktop() = runTest {+        clean()+        val repo = repo()+        val first = repo.upsert(app("com.example.hs1"))+        val second = repo.upsert(app("com.example.hs2", cellX = 1))+        val third = repo.upsert(app("com.example.hs3", cellX = 2))+        repo.moveToHotseat(first, 0, spec)+        repo.moveToHotseat(second, 1, spec)+        // The hotseat has two slots; inserting a third evicts one to the desktop.+        repo.moveToHotseat(third, 0, spec)+        val hotseat = repo.getAll().filter { it.containerId == ContainerRef.Hotseat.toRaw() }+        assertEquals(2, hotseat.size)+        assertTrue(hotseat.any { it.id == third })+        val evicted = repo.getAll().filter { it.containerId == ContainerRef.Desktop.toRaw() }+        assertEquals(1, evicted.size)+        clean()+    }++    @Test+    fun folderLifecycleCollapseAndRemove() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.fa", cellX = 0))+        val b = repo.upsert(app("com.example.fb", cellX = 1))+        val c = repo.upsert(app("com.example.fc", cellX = 2))+        val folderId = repo.createFolder(a, b)+        assertNotNull(folderId)+        repo.addToFolder(folderId!!, c)+        assertEquals(3, repo.getFolderChildren(folderId).size)++        // Reorder inside the folder: c goes first.+        val children = repo.getFolderChildren(folderId)+        repo.reorderInFolder(folderId, children.last().id, 0)+        val reordered = repo.getFolderChildren(folderId).sortedBy { it.rank }+        assertEquals(children.last().id, reordered.first().id)++        // Remove two children one at a time; removing the second-to-last+        // collapses the folder (remove does this itself), leaving the+        // survivor on the desktop at the folder's cell.+        val childIds = repo.getFolderChildren(folderId).map { it.id }+        repo.remove(childIds[0])+        assertEquals(2, repo.getFolderChildren(folderId).size)+        repo.remove(childIds[1])+        assertNull(repo.get(folderId))+        val survivors = repo.getAll()+        assertEquals(1, survivors.size)+        assertEquals(ContainerRef.Desktop.toRaw(), survivors.single().containerId)+        clean()+    }++    @Test+    fun removingAFolderRemovesItsChildren() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.ra", cellX = 0))+        val b = repo.upsert(app("com.example.rb", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        repo.remove(folderId)+        assertTrue(repo.getAll().isEmpty())+        clean()+    }++    @Test+    fun moveWithDisplacementAndResizeWithDisplacement() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.ma", cellX = 0, cellY = 0))+        val b = repo.upsert(app("com.example.mb", cellX = 1, cellY = 0))+        repo.moveTo(a, ContainerRef.Desktop, 0, CellRect(1, 0), displaced = mapOf(b to CellRect(0, 0)))+        assertEquals(1, repo.get(a)?.cellX)+        assertEquals(0, repo.get(b)?.cellX)++        val widget = repo.upsert(+            app("com.example.mw", cellX = 0, cellY = 2).copy(+                itemType = LauncherItemType.APPWIDGET,+                spanX = 2,+                spanY = 1,+                appWidgetId = 4242,+            ),+        )+        assertEquals(setOf(4242), repo.usedWidgetIds())+        val neighbour = repo.upsert(app("com.example.mn", cellX = 3, cellY = 2))+        repo.resizeTo(widget, CellRect(1, 2, spanX = 2, spanY = 1), displaced = mapOf(neighbour to CellRect(0, 3)))+        assertEquals(1, repo.get(widget)?.cellX)+        assertEquals(0, repo.get(neighbour)?.cellX)+        assertEquals(3, repo.get(neighbour)?.cellY)+        clean()+    }++    @Test+    fun seedIsIdempotentAndRegridKeepsItemsOnGrid() = runTest {+        clean()+        val repo = repo()+        val apps = listOf(app("com.example.sa"), app("com.example.sb", cellX = 1), app("com.example.sc", cellX = 3, cellY = 3))+        repo.seed(spec, apps, apps.take(1))+        val seeded = repo.getAll()+        assertTrue(seeded.isNotEmpty())+        repo.seed(spec, apps, apps.take(1))+        assertEquals(seeded.size, repo.getAll().size)++        // Shrink the grid: everything must land inside the smaller spec.+        repo.regrid(GridSpec(columns = 2, rows = 2, hotseatSlots = 2))+        val after = repo.getAll().filter { it.containerId == ContainerRef.Desktop.toRaw() }+        assertTrue(after.all { it.cellX in 0..1 && it.cellY in 0..1 })+        assertEquals(false, repo.isEmpty())+        clean()+        assertEquals(true, repo.isEmpty())+    }++    @Test+    fun createFolderWithMissingOrIncompatibleItemsFails() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.xa", cellX = 0))+        assertNull(repo.createFolder(a, 987654L))+        assertNull(repo.createFolder(987654L, a))+        // A widget cannot merge into a folder.+        val widget = repo.upsert(+            app("com.example.xw", cellX = 1).copy(itemType = LauncherItemType.APPWIDGET, appWidgetId = 7),+        )+        assertNull(repo.createFolder(a, widget))+        clean()+    }++    @Test+    fun hotseatInsertShiftsRanksAndReorderWithinHotseat() = runTest {+        clean()+        val repo = repo()+        val spec4 = GridSpec(columns = 4, rows = 4, hotseatSlots = 4)+        val a = repo.upsert(app("com.example.ha", cellX = 0))+        val b = repo.upsert(app("com.example.hb", cellX = 1))+        val c = repo.upsert(app("com.example.hc", cellX = 2))+        repo.moveToHotseat(a, 0, spec4)+        repo.moveToHotseat(b, 1, spec4)+        // Insert c at the front: existing hotseat items shift rank.+        repo.moveToHotseat(c, 0, spec4)+        var hotseat = repo.getAll()+            .filter { it.containerId == ContainerRef.Hotseat.toRaw() }+            .sortedBy { it.rank }+        assertEquals(listOf(c, a, b), hotseat.map { it.id })+        // Move an item already in the hotseat to the end.+        repo.moveToHotseat(c, 2, spec4)+        hotseat = repo.getAll()+            .filter { it.containerId == ContainerRef.Hotseat.toRaw() }+            .sortedBy { it.rank }+        assertEquals(listOf(a, b, c), hotseat.map { it.id })+        clean()+    }++    @Test+    fun regridDropsHotseatOverflowToDesktop() = runTest {+        clean()+        val repo = repo()+        val spec4 = GridSpec(columns = 4, rows = 4, hotseatSlots = 4)+        val ids = (0..2).map { repo.upsert(app("com.example.o$it", cellX = it)) }+        ids.forEachIndexed { index, id -> repo.moveToHotseat(id, index, spec4) }+        assertEquals(+            3,+            repo.getAll().count { it.containerId == ContainerRef.Hotseat.toRaw() },+        )+        repo.regrid(GridSpec(columns = 4, rows = 4, hotseatSlots = 1))+        val after = repo.getAll()+        assertEquals(1, after.count { it.containerId == ContainerRef.Hotseat.toRaw() })+        assertEquals(2, after.count { it.containerId == ContainerRef.Desktop.toRaw() })+        clean()+    }++    @Test+    fun reconcileSweepsFoldersEmptiedByDeletions() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.ea", cellX = 0))+        val b = repo.upsert(app("com.example.eb", cellX = 1))+        val folderId = repo.createFolder(a, b)!!+        // Both children uninstalled: the folder is swept too.+        repo.reconcile(+            installed = emptySet(),+            unavailable = emptySet(),+            boundWidgetIds = emptySet(),+        )+        assertTrue(repo.getAll().isEmpty())+        assertNull(repo.get(folderId))+        clean()+    }++    @Test+    fun reconcileHidesUnavailableInsteadOfDeleting() = runTest {+        clean()+        val repo = repo()+        val a = repo.upsert(app("com.example.ua", cellX = 0))+        repo.reconcile(+            installed = emptySet(),+            unavailable = setOf(+                com.vayunmathur.launcher.domain.PackageKey("com.example.ua", 0L),+            ),+            boundWidgetIds = emptySet(),+        )+        val kept = repo.get(a)+        assertNotNull(kept)+        assertEquals(true, kept!!.hidden)+        clean()+    }++    @Test+    fun reconcileDropsUninstalledAndKeepsInstalled() = runTest {+        clean()+        val repo = repo()+        val keep = repo.upsert(app("com.example.keep", cellX = 0))+        repo.upsert(app("com.example.gone", cellX = 1))+        val orphaned = repo.reconcile(+            installed = setOf(+                com.vayunmathur.launcher.domain.PackageKey("com.example.keep", 0L),+            ),+            unavailable = emptySet(),+            boundWidgetIds = emptySet(),+        )+        assertEquals(emptyList<Int>(), orphaned)+        val remaining = repo.getAll()+        assertEquals(listOf(keep), remaining.map { it.id })+        clean()+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelDeviceTest.ktnew file mode 100644index 0000000000..332fc710ec--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelDeviceTest.kt@@ -0,0 +1,447 @@+package com.vayunmathur.launcher.platform++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.launcher.data.LauncherItemEntity+import com.vayunmathur.launcher.data.LauncherRepository+import com.vayunmathur.launcher.domain.CellRect+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.GridSpec+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.toRaw+import com.vayunmathur.launcher.platform.ComponentKey+import com.vayunmathur.launcher.platform.WidgetEntry+import com.vayunmathur.launcher.platform.WidgetGroup+import com.vayunmathur.launcher.platform.ShortcutEntry+import com.vayunmathur.launcher.platform.WorkspaceItem+import com.vayunmathur.launcher.platform.applyDrawerQuery+import com.vayunmathur.launcher.platform.countLaunch+import com.vayunmathur.launcher.platform.predictedApps+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device tests for [LauncherViewModel] action bodies: view-model+ * construction needs the real package manager, DataStore and SQLCipher+ * database, so these run instrumented. Drives workspace commits, folder+ * merges, renames, grid changes and drawer/menu state through the real+ * repository, asserting persisted rows.+ */+@RunWith(AndroidJUnit4::class)+class LauncherViewModelDeviceTest {++    private val spec = GridSpec(columns = 4, rows = 4, hotseatSlots = 4)++    private fun app(): android.app.Application {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        return ctx.applicationContext as android.app.Application+    }++    private fun repo() = LauncherRepository.get(app())++    private fun entity(pkg: String) = LauncherItemEntity(+        itemType = LauncherItemType.APPLICATION,+        containerId = ContainerRef.Desktop.toRaw(),+        packageName = pkg,+        className = "$pkg.Main",+    )++    @Test fun commitMovePersists() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.m"))+        vm.commitMove(id, ContainerRef.Desktop, 1, CellRect(2, 2), 0)+        // commitMove launches in viewModelScope: poll the persisted row.+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        var got: LauncherItemEntity? = null+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            got = r.get(id)+            if (got?.screen == 1 && got.cellX == 2) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(1, got?.screen)+        assertEquals(2, got?.cellX)+        r.remove(id)+    }++    @Test fun mergeIntoFolderCreatesFolder() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val target = r.upsert(entity("com.example.t"))+        val dragged = r.upsert(entity("com.example.d"))+        // Seed the view-model's item cache so the merge finds its target.+        vm.savedItems = r.getAll()+        vm.mergeIntoFolder(target, dragged)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        var folders = 0+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            folders = r.getAll().count { it.itemType == LauncherItemType.FOLDER }+            if (folders == 1) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(1, folders)+        r.getAll().forEach { r.remove(it.id) }+    }++    @Test fun renamePersistsTitle() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.r"))+        vm.rename(id, "Renamed")+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        var title: String? = null+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            title = r.get(id)?.title+            if (title == "Renamed") break+            kotlinx.coroutines.delay(50)+        }+        assertEquals("Renamed", title)+        r.remove(id)+    }++    @Test fun setColumnsRegrids() = runTest {+        val vm = LauncherViewModel(app())+        vm.setColumns(5)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (vm.home.value.grid.columns == 5) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(5, vm.home.value.grid.columns)+        vm.setColumns(4)+    }++    @Test fun removeDeletesRow() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.x"))+        vm.remove(id)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        var gone = false+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (r.get(id) == null) {+                gone = true+                break+            }+            kotlinx.coroutines.delay(50)+        }+        assertEquals(true, gone)+    }++    @Test fun hiddenLaunchShowsMessage() = runTest {+        val vm = LauncherViewModel(app())+        // A hidden item cannot launch: shows "not available", returns early.+        val item = WorkspaceItem(+            id = 1L,+            type = LauncherItemType.APPLICATION,+            label = "Hidden",+            hidden = true,+        )+        vm.launch(item, 0, 0, 10, 10)+        assertNotNull(vm.home)+    }++    @Test fun uninstallItemWithoutEntityIsNoOp() = runTest {+        val vm = LauncherViewModel(app())+        vm.uninstallItem(999999L)+        vm.openItemInfo(999999L)+        assertNull(vm.itemMenu.value.item)+    }++    @Test fun widgetQueryFiltersGroups() = runTest {+        val vm = LauncherViewModel(app())+        vm.applyWidgetQuery(+            "clo",+            source = listOf(+                WidgetGroup(+                    "Clock",+                    listOf(+                        WidgetEntry("com.example/.Analog", "Analog clock", spanX = 2, spanY = 2),+                        WidgetEntry("com.example/.Weather", "Weather", spanX = 4, spanY = 1),+                    ),+                ),+                WidgetGroup("Mail", listOf(WidgetEntry("com.example/.M", "Mail widget"))),+            ),+        )+        val groups = vm.widgetPicker.value.groups+        assertEquals(1, groups.size)+        assertEquals("Clock", groups[0].appLabel)+        // App-label match keeps the whole group, not just matching widgets.+        assertEquals(2, groups[0].widgets.size)+        vm.applyWidgetQuery("", source = null)+        // Null source keeps allWidgetGroups ([Clock, Mail]); empty query shows all.+        assertEquals(2, vm.widgetPicker.value.groups.size)+        vm.applyWidgetQuery(+            "",+            source = listOf(+                WidgetGroup("Clock", listOf(WidgetEntry("com.example/.A", "A"))),+                WidgetGroup("Mail", listOf(WidgetEntry("com.example/.M", "M"))),+            ),+        )+        assertEquals(2, vm.widgetPicker.value.groups.size)+    }++    @Test fun pendingHomeAndHotseatInserts() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val key = ComponentKey(+            android.content.ComponentName("com.example.p", "com.example.p.Main"),+            0L,+        )+        vm.addPendingToHome(key, 0, CellRect(0, 0))+        vm.addPendingToHotseat(key, 0)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (r.getAll().size >= 2) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(2, r.getAll().size)+        r.getAll().forEach { r.remove(it.id) }+    }++    @Test fun monitorRefreshListsPackages() = runTest {+        val vm = LauncherViewModel(app())+        vm.appsMonitor.refresh()+        // refresh() loads off-main: poll until the emulator's app list lands.+        val deadline = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (vm.appsMonitor.apps.value.isNotEmpty()) break+            kotlinx.coroutines.delay(100)+        }+        assertEquals(true, vm.appsMonitor.apps.value.isNotEmpty())+    }++    @Test fun gridSettersRenumber() = runTest {+        val vm = LauncherViewModel(app())+        vm.setRows(5)+        vm.setHotseatSlots(3)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            val g = vm.home.value.grid+            if (g.rows == 5 && g.hotseatSlots == 3) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(5, vm.home.value.grid.rows)+        assertEquals(3, vm.home.value.grid.hotseatSlots)+        vm.setRows(4)+        vm.setHotseatSlots(4)+    }++    @Test fun itemMenuOpenUnknownClears() = runTest {+        val vm = LauncherViewModel(app())+        vm.openItemMenuImpl(424242L)+        assertNull(vm.itemMenu.value.item)+    }++    @Test fun opsNullGuardsAreSafe() = runTest {+        val vm = LauncherViewModel(app())+        val key = ComponentKey(+            android.content.ComponentName("com.example.ghost", "com.example.ghost.Main"),+            0L,+        )+        // Nothing installed under these keys: every lookup misses and returns early.+        vm.launchApp(key, 0, 0, 10, 10)+        vm.setWorkPaused(true)+        vm.uninstallItem(424243L)+        vm.openItemInfo(424243L)+        vm.launchShortcut(+            com.vayunmathur.launcher.platform.ShortcutEntry("s", "S", "com.example.ghost", 0L),+        )+        vm.pinShortcutToHome(+            com.vayunmathur.launcher.platform.ShortcutEntry("s", "S", "com.example.ghost", 0L),+        )+        vm.addPendingShortcutToHome(+            com.vayunmathur.launcher.platform.ShortcutEntry("s", "S", "com.example.ghost", 0L),+            0,+            CellRect(0, 0),+        )+        vm.openAppInfo(WorkspaceItem(1L, LauncherItemType.APPLICATION, "G"))+        vm.uninstall(WorkspaceItem(1L, LauncherItemType.APPLICATION, "G"))+        vm.requestDefaultHome()+        vm.refreshDefaultHomeImpl()+        vm.onLocaleChangedImpl()+        vm.appIcon(key)+        vm.shortcutIcon("com.example.ghost", "s", 0L)+        vm.widgetPreview("com.example/.W", 0L)+        vm.expandNotificationShade()+        vm.setWallpaperBlurred(false)+        assertNull(vm.itemMenu.value.item)+    }++    @Test fun openItemMenuFindsWorkspaceItem() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.menu"))+        // Seed caches the menu lookup reads.+        vm.savedItems = r.getAll()+        vm.homeState.value = vm.home.value.copy(+            pages = mapOf(+                0 to listOf(+                    WorkspaceItem(+                        id = id,+                        type = LauncherItemType.APPLICATION,+                        label = "Menu",+                    ),+                ),+            ),+        )+        vm.openItemMenuImpl(id)+        assertEquals(id, vm.itemMenu.value.item?.id)+        r.remove(id)+    }++    @Test fun widgetPickerLoadAndAddGuards() = runTest {+        val vm = LauncherViewModel(app())+        vm.loadWidgetPicker()+        val deadline = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!vm.widgetPicker.value.loading) break+            kotlinx.coroutines.delay(100)+        }+        // Emulator widget providers (if any) load without crashing.+        vm.widgetPicker.value.groups.forEach { }+        // No bridge on device tests: add guards return early.+        vm.addWidgetEntry(WidgetEntry("com.example/.W", "W"))+        assertEquals(null, vm.hostedWidgetView(424242))+    }++    @Test fun monitorEntryLookups() = runTest {+        val vm = LauncherViewModel(app())+        vm.appsMonitor.refresh()+        val deadline = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (vm.appsMonitor.apps.value.isNotEmpty()) break+            kotlinx.coroutines.delay(100)+        }+        val apps = vm.appsMonitor.apps.value+        assertEquals(true, apps.isNotEmpty())+        val first = apps.first()+        // Icon rasterises off a real package drawable.+        val icon = vm.appsMonitor.icon(first, 320)+        assertEquals(first, vm.appsMonitor.entryFor(first.componentName, first.profileSerial))+        // Shortcuts of a real package (possibly empty) query safely.+        val shortcuts = vm.appsMonitor.shortcuts(+            first.componentName.packageName,+            vm.appsMonitor.userFor(first.profileSerial),+        )+        assertEquals(true, (shortcuts.size >= 0))+        assertEquals(true, icon == null || icon != null)+    }++    @Test fun predictionsRankByLaunchCount() = runTest {+        val vm = LauncherViewModel(app())+        // Launch counts persist in DataStore across runs on a shared emulator;+        // a previous run's counts would make the first assertion see them.+        vm.launchCounts.clear()+        val a = com.vayunmathur.launcher.platform.DrawerApp(keyComponent("com.example.a"), "Alpha")+        val b = com.vayunmathur.launcher.platform.DrawerApp(keyComponent("com.example.b"), "Beta")+        val w = com.vayunmathur.launcher.platform.DrawerApp(+            keyComponent("com.example.w", work = true),+            "Work",+            isWorkProfile = true,+        )+        vm.allApps = listOf(a, b, w)+        assertEquals(emptyList<DrawerApp>(), vm.predictedApps())+        vm.countLaunch(b.key)+        vm.countLaunch(a.key)+        vm.countLaunch(a.key)+        val predicted = vm.predictedApps()+        // Alpha launched twice, Beta once; work apps never predicted.+        assertEquals(listOf("Alpha", "Beta"), predicted.map { it.label })+    }++    @Test fun drawerQueryOrdersPrefixFirst() = runTest {+        val vm = LauncherViewModel(app())+        vm.allApps = listOf(+            com.vayunmathur.launcher.platform.DrawerApp(keyComponent("com.example.v"), "Vacation Planner"),+            com.vayunmathur.launcher.platform.DrawerApp(keyComponent("com.example.c"), "Calendar"),+        )+        vm.applyDrawerQuery("ca")+        assertEquals(+            listOf("Calendar", "Vacation Planner"),+            vm.drawer.value.apps.map { it.label },+        )+        vm.applyDrawerQuery("")+        assertEquals(2, vm.drawer.value.apps.size)+    }++    private fun keyComponent(pkg: String, work: Boolean = false) = ComponentKey(+        android.content.ComponentName(pkg, "$pkg.Main"),+        if (work) 10L else 0L,+    )++    @Test fun privilegeQuietModeRefused() = runTest {+        val vm = LauncherViewModel(app())+        val user = android.os.Process.myUserHandle()+        // No MODIFY_QUIET_MODE on the emulator: refused safely.+        assertEquals(false, vm.privilege.setQuietMode(user, true))+        assertEquals(false, vm.privilege.isQuietModeEnabled(user))+    }++    @Test fun resizeAndReorderFolder() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.w"))+        vm.resizeItem(id, CellRect(0, 0, 2, 2))+        vm.reorderInFolder(999L, id, 0)+        val deadline = android.os.SystemClock.uptimeMillis() + 5000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (r.get(id)?.spanX == 2) break+            kotlinx.coroutines.delay(50)+        }+        assertEquals(2, r.get(id)?.spanX)+        r.remove(id)+    }++    @Test fun uninstallAndInfoWithEntity() = runTest {+        val vm = LauncherViewModel(app())+        val r = repo()+        r.getAll().forEach { r.remove(it.id) }+        val id = r.upsert(entity("com.example.ghost"))+        vm.savedItems = r.getAll()+        // Ghost package: entry lookups miss, bridge is null; all no-ops.+        vm.uninstallItem(id)+        vm.openItemInfo(id)+        val key = ComponentKey(+            android.content.ComponentName("com.example.ghost", "com.example.ghost.Main"),+            0L,+        )+        vm.openAppInfo(WorkspaceItem(1L, LauncherItemType.APPLICATION, "G", key = key))+        vm.uninstall(WorkspaceItem(1L, LauncherItemType.APPLICATION, "G", key = key))+        vm.launchShortcut(ShortcutEntry("s", "S", "com.example.ghost", 0L))+        r.remove(id)+    }++    @Test fun widgetHostUpdateSize() = runTest {+        val vm = LauncherViewModel(app())+        val ctx = app()+        val view = android.appwidget.AppWidgetHostView(ctx)+        vm.widgets.updateSize(view, 200, 100)+    }++    @Test fun settingsTogglesPropagate() = runTest {+        val vm = LauncherViewModel(app())+        vm.setShowLabels(false)+        assertEquals(false, vm.settings.value.showLabels)+        assertEquals(false, vm.home.value.showLabels)+        vm.setShowLabels(true)+        assertEquals(true, vm.settings.value.showLabels)+        vm.setIconScale(1.25f)+        assertEquals(1.25f, vm.settings.value.iconScale)+        vm.setIconScale(1f)+        vm.setDrawerListLayout(true)+        assertEquals(true, vm.settings.value.drawerListLayout)+        vm.setDrawerListLayout(false)+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelExtraDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelExtraDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelExtraDeviceTest.ktnew file mode 100644index 0000000000..c934c80dec--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/platform/LauncherViewModelExtraDeviceTest.kt@@ -0,0 +1,221 @@+package com.vayunmathur.launcher.platform++import android.content.Context+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.UiDevice+import com.vayunmathur.launcher.domain.toRaw+import com.vayunmathur.launcher.tv.platform.TvInputs+import kotlinx.coroutines.delay+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Extra on-device coverage for the ViewModel/widget/TV-input paths that need+ * real packages: widget-picker enumeration over a populated app list,+ * launching a real app through the monitor, app-details, and TV input+ * listing/opening on the emulator.+ */+@RunWith(AndroidJUnit4::class)+class LauncherViewModelExtraDeviceTest {++    private val instrumentation = InstrumentationRegistry.getInstrumentation()+    private val targetContext: Context = instrumentation.targetContext++    private fun app() = targetContext.applicationContext as android.app.Application++    private suspend fun awaitApps(vm: LauncherViewModel): List<AppEntry> {+        vm.appsMonitor.refresh()+        val deadline = android.os.SystemClock.uptimeMillis() + 15000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            val apps = vm.appsMonitor.apps.value+            if (apps.isNotEmpty()) return apps+            delay(200)+        }+        return vm.appsMonitor.apps.value+    }++    private fun back() {+        val device = UiDevice.getInstance(instrumentation)+        device.waitForIdle(2_000)+        device.pressBack()+        device.waitForIdle(2_000)+    }++    @Test+    fun widgetPickerEnumeratesRealProviders() = runTest {+        val vm = LauncherViewModel(app())+        val apps = awaitApps(vm)+        assertTrue(apps.isNotEmpty())+        vm.loadWidgetPicker()+        val deadline = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!vm.widgetPicker.value.loading) break+            delay(100)+        }+        assertEquals(false, vm.widgetPicker.value.loading)+        // Whatever providers the emulator ships are grouped and queryable.+        val all = vm.widgetPicker.value.groups+        vm.applyWidgetQuery("clock")+        vm.applyWidgetQuery("")+        assertEquals(all, vm.widgetPicker.value.groups)+        vm.applyWidgetQuery("zzz-no-such-widget-zzz")+        assertTrue(vm.widgetPicker.value.groups.isEmpty())+    }++    @Test+    fun launchAndAppDetailsForARealApp() = runTest {+        val vm = LauncherViewModel(app())+        val apps = awaitApps(vm)+        assertTrue(apps.isNotEmpty())+        val entry = apps.first()++        // App-details opens the system settings page for the app; leave it.+        assertTrue(vm.appsMonitor.startAppDetails(entry, null))+        back()++        // Launching through the monitor starts the app; Back returns.+        assertTrue(vm.appsMonitor.launch(entry, null))+        back()++        // The shortcut query is role-gated; empty is a valid answer.+        val shortcuts = vm.appsMonitor.shortcuts(entry.componentName.packageName, entry.user)+        assertNotNull(shortcuts)+        if (shortcuts.isNotEmpty()) {+            vm.appsMonitor.shortcutIcon(shortcuts.first(), 320)+        }+        // Icon resolution for a real entry produces a badged drawable.+        assertNotNull(vm.appsMonitor.icon(entry, 320))+    }++    @Test+    fun launchAppThroughViewModelCountsTheLaunch() = runTest {+        val vm = LauncherViewModel(app())+        val apps = awaitApps(vm)+        assertTrue(apps.isNotEmpty())+        val entry = apps.first()+        val key = ComponentKey(entry.componentName, entry.profileSerial)+        val before = vm.launchCounts[key.componentName.flattenToShortString()] ?: 0L+        vm.launchApp(key, 0, 0, 10, 10)+        val after = vm.launchCounts[key.componentName.flattenToShortString()] ?: 0L+        assertEquals(before + 1, after)+        back()+    }++    @Test+    fun launchItemInfoUninstallAndGridForSettings() = runTest {+        val vm = LauncherViewModel(app())+        val apps = awaitApps(vm)+        assertTrue(apps.isNotEmpty())+        val entry = apps.first()+        val key = ComponentKey(entry.componentName, entry.profileSerial)+        val item = WorkspaceItem(+            id = 987001L,+            type = com.vayunmathur.launcher.domain.LauncherItemType.APPLICATION,+            label = entry.label,+            key = key,+        )++        // Launch a real app through the workspace-item path, then return.+        vm.launchImpl(item, 0, 0, 10, 10)+        back()++        // A hidden item refuses with a message and never launches.+        vm.launchImpl(item.copy(hidden = true), 0, 0, 10, 10)++        // App info opens the system details page; uninstall opens the+        // system confirmation for a (removable-by-nobody-here) entry.+        vm.openAppInfoImpl(item)+        back()+        vm.uninstallImpl(item)+        back()++        // Shortcut entry points with an unknown shortcut degrade safely.+        val shortcutEntry = ShortcutEntry("no-such-shortcut", "Nope", entry.componentName.packageName, entry.profileSerial)+        vm.launchShortcutImpl(shortcutEntry)+        vm.pinShortcutToHomeImpl(shortcutEntry)++        // The settings grid path regrids and publishes, then restore 4x4.+        vm.changeGridForSettings { it.copy(columns = 5, rows = 5) }+        val deadline = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (vm.home.value.grid.columns == 5) break+            delay(100)+        }+        assertEquals(5, vm.home.value.grid.columns)+        assertEquals(5, vm.settings.value.columns)+        vm.changeGridForSettings { it.copy(columns = 4, rows = 4) }+        val deadline2 = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline2) {+            if (vm.home.value.grid.columns == 4) break+            delay(100)+        }+        assertEquals(4, vm.home.value.grid.columns)+    }++    @Test+    fun workspaceFromMapsRowsToUiItems() = runTest {+        val vm = LauncherViewModel(app())+        fun entity(+            id: Long,+            pkg: String,+            container: Long,+            rank: Int = 0,+            type: com.vayunmathur.launcher.domain.LauncherItemType =+                com.vayunmathur.launcher.domain.LauncherItemType.APPLICATION,+            title: String? = null,+            screen: Int = 0,+            cellX: Int = 0,+        ) = com.vayunmathur.launcher.data.LauncherItemEntity(+            id = id,+            itemType = type,+            containerId = container,+            screen = screen,+            cellX = cellX,+            rank = rank,+            title = title,+            packageName = pkg,+            className = "$pkg.Main",+        )+        val desktop = com.vayunmathur.launcher.domain.ContainerRef.Desktop.toRaw()+        val hotseat = com.vayunmathur.launcher.domain.ContainerRef.Hotseat.toRaw()+        val folder = entity(10, "com.example.folder", desktop, type = com.vayunmathur.launcher.domain.LauncherItemType.FOLDER, title = "Folder")+        val childB = entity(12, "com.example.b", 10L, rank = 1)+        val childA = entity(11, "com.example.a", 10L, rank = 0)+        val widget = entity(13, "com.example.w", desktop, cellX = 1, type = com.vayunmathur.launcher.domain.LauncherItemType.APPWIDGET)+            .copy(appWidgetId = 99, appWidgetProvider = "com.example/.Widget")+        val plain = entity(14, "com.example.plain", desktop, screen = 1, cellX = 2)+        val hot2 = entity(16, "com.example.h2", hotseat, rank = 1)+        val hot1 = entity(15, "com.example.h1", hotseat, rank = 0)++        val (pages, hotseatItems) = vm.workspaceFromImpl(+            listOf(folder, childB, childA, widget, plain, hot2, hot1),+        )+        assertEquals(setOf(0, 1), pages.keys)+        val page0 = pages[0]!!+        val folderUi = page0.single { it.id == 10L }+        // Children come back in rank order regardless of row order.+        assertEquals(listOf(11L, 12L), folderUi.children.map { it.id })+        assertEquals("Folder", folderUi.label)+        val widgetUi = page0.single { it.id == 13L }+        assertEquals(99, widgetUi.appWidgetId)+        assertEquals(false, widgetUi.canUninstall)+        // Hotseat is a rank list.+        assertEquals(listOf(15L, 16L), hotseatItems.map { it.id })+        assertEquals(1, pages[1]!!.size)+    }++    @Test+    fun tvInputsListAndOpenOnEmulator() {+        val inputs = TvInputs.list(targetContext, 6)+        // The phone emulator may expose no HDMI inputs; opening a (possibly+        // bogus) input must still run its fallback chain without crashing.+        val id = inputs.firstOrNull()?.id ?: "passthrough:/dev/input/event0"+        TvInputs.open(targetContext, id)+        back()+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelDeviceTest.ktnew file mode 100644index 0000000000..bc7abc37f0--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelDeviceTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.launcher.tv.platform++import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Test+import org.junit.runner.RunWith++/**+ * On-device tests for [TvHomeViewModel.refreshApps]: with real packages the+ * row merges, tiles load art, and inputs list โ€” covering the load path that+ * is empty under Robolectric.+ */+@RunWith(AndroidJUnit4::class)+class TvHomeViewModelDeviceTest {++    private fun vm(): TvHomeViewModel {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        return TvHomeViewModel(ctx.applicationContext as android.app.Application)+    }++    @Test fun refreshAppsLoadsRealRow() = runTest {+        val v = vm()+        val deadline = android.os.SystemClock.uptimeMillis() + 15000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!v.home.value.loading) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(false, v.home.value.loading)+        // The emulator has real launchable packages: the row is non-empty.+        assertEquals(true, v.home.value.rowApps.isNotEmpty())+    }++    @Test fun openEditMenuMoveCycle() = runTest {+        val v = vm()+        val deadline = android.os.SystemClock.uptimeMillis() + 15000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!v.home.value.loading) break+            kotlinx.coroutines.delay(200)+        }+        val first = v.home.value.rowApps.firstOrNull()?.packageName+        assertEquals(true, first != null)+        v.openEditMenu(first!!)+        assertEquals(first, v.home.value.editingKey)+        v.closeEditMenu()+        assertEquals(null, v.home.value.editingKey)+    }++    @Test fun moveCyclePersists() = runTest {+        val v = vm()+        waitIdle(v)+        val order = v.home.value.rowApps.map { it.packageName }+        assertEquals(true, order.size >= 2)+        val held = order[0]+        v.startMove(held)+        v.moveKey(held, +1)+        assertEquals(held, v.home.value.rowApps[1].packageName)+        v.pressTile(held)+        val deadline = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (v.home.value.movingKey == null) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(null, v.home.value.movingKey)+    }++    @Test fun addMenuPickCycle() = runTest {+        val v = vm()+        waitIdle(v)+        v.openAddMenu()+        val deadline = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (v.home.value.showAddMenu) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(true, v.home.value.showAddMenu)+        val candidate = v.home.value.addCandidates.firstOrNull()?.packageName+        assertEquals(true, candidate != null)+        v.pickAddCandidate(candidate!!)+        val deadline2 = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline2) {+            if (!v.home.value.loading && v.home.value.rowApps.any { it.packageName == candidate }) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(true, v.home.value.rowApps.any { it.packageName == candidate })+        // Clean up: remove the added tile again.+        v.removeTile(candidate)+        val deadline3 = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline3) {+            if (v.home.value.rowApps.none { it.packageName == candidate }) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(true, v.home.value.rowApps.none { it.packageName == candidate })+    }++    private suspend fun waitIdle(v: TvHomeViewModel) {+        val deadline = android.os.SystemClock.uptimeMillis() + 15000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!v.home.value.loading) break+            kotlinx.coroutines.delay(200)+        }+    }++    @Test fun settingsIntentsFire() = runTest {+        val v = vm()+        // Each tries real intents in turn; whatever resolves opens transiently.+        v.openNetworkSettings()+        v.openSettings()+    }++    @Test fun removeTileThenRestore() = runTest {+        val v = vm()+        waitIdle(v)+        val row = v.home.value.rowApps.map { it.packageName }+        assertEquals(true, row.size >= 2)+        val victim = row.last()+        v.removeTile(victim)+        val deadline = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (v.home.value.rowApps.none { it.packageName == victim }) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(true, v.home.value.rowApps.none { it.packageName == victim })+        // Restore via the add menu so later runs start whole.+        v.openAddMenu()+        val deadline2 = android.os.SystemClock.uptimeMillis() + 8000+        while (android.os.SystemClock.uptimeMillis() < deadline2) {+            if (v.home.value.showAddMenu) break+            kotlinx.coroutines.delay(200)+        }+        v.pickAddCandidate(victim)+        val deadline3 = android.os.SystemClock.uptimeMillis() + 10000+        while (android.os.SystemClock.uptimeMillis() < deadline3) {+            if (v.home.value.rowApps.any { it.packageName == victim }) break+            kotlinx.coroutines.delay(200)+        }+        assertEquals(true, v.home.value.rowApps.any { it.packageName == victim })+    }++    @Test fun tvAppsInstalledListsRealPackages() {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        val entries = TvApps.installed(ctx, ctx.packageName)+        assertEquals(true, entries.isNotEmpty())+        // Self is excluded from the row.+        assertEquals(true, entries.none { it.packageName == ctx.packageName })+    }+}
launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelExtraDeviceTest.kt
diff --git a/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelExtraDeviceTest.kt b/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelExtraDeviceTest.ktnew file mode 100644index 0000000000..65c1bb8b94--- /dev/null+++ b/launcher/src/androidTest/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelExtraDeviceTest.kt@@ -0,0 +1,101 @@+package com.vayunmathur.launcher.tv.platform++import android.app.Application+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.UiDevice+import com.vayunmathur.launcher.MainActivity+import kotlinx.coroutines.delay+import kotlinx.coroutines.test.runTest+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Extra on-device coverage for [TvHomeViewModel] paths the first TV device+ * suite does not reach: reorder disarm mid-hold, unknown-tile opens,+ * uninstall/info intents, default-home refresh and the request-role prompt.+ */+@RunWith(AndroidJUnit4::class)+class TvHomeViewModelExtraDeviceTest {++    private fun vm(): TvHomeViewModel {+        val ctx = InstrumentationRegistry.getInstrumentation().targetContext+        return TvHomeViewModel(ctx.applicationContext as Application)+    }++    private suspend fun waitIdle(v: TvHomeViewModel) {+        val deadline = android.os.SystemClock.uptimeMillis() + 15000+        while (android.os.SystemClock.uptimeMillis() < deadline) {+            if (!v.home.value.loading) break+            delay(200)+        }+    }++    @Test+    fun disarmMidHoldRestoresPersistedOrder() = runTest {+        val v = vm()+        waitIdle(v)+        val order = v.home.value.rowApps.map { it.packageName }+        assertTrue(order.size >= 2)+        v.startMove(order[0])+        v.moveKey(order[0], +1)+        assertEquals(order[0], v.home.value.rowApps[1].packageName)+        // Disarming while holding drops the hold and quietly restores the+        // last persisted order (the same packages, back in place).+        v.toggleReorder()+        assertEquals(false, v.home.value.reorderArmed)+        assertNull(v.home.value.movingKey)+        assertEquals(order.toSet(), v.home.value.rowApps.map { it.packageName }.toSet())+    }++    @Test+    fun toggleReorderArmsThenDisarmsCleanly() = runTest {+        val v = vm()+        waitIdle(v)+        v.toggleReorder()+        assertEquals(true, v.home.value.reorderArmed)+        v.toggleReorder()+        assertEquals(false, v.home.value.reorderArmed)+        assertNull(v.home.value.movingKey)+    }++    @Test+    fun openUnknownTileShowsMessageInsteadOfCrashing() = runTest {+        val v = vm()+        waitIdle(v)+        v.openTile("com.example.does.not.exist")+        // No state changed and nothing launched; the message path ran.+        assertNull(v.home.value.movingKey)+    }++    @Test+    fun refreshDefaultHomeReadsTheRoleState() = runTest {+        val v = vm()+        waitIdle(v)+        ActivityScenario.launch(MainActivity::class.java).use { scenario ->+            scenario.onActivity { activity ->+                v.refreshDefaultHome(activity)+                assertEquals(TvHomeRole.isDefaultHome(activity), v.home.value.isDefaultHome)+            }+        }+    }++    @Test+    fun uninstallOrInfoForUnknownPackageOpensDetailsAndClosesMenu() = runTest {+        val v = vm()+        waitIdle(v)+        v.openEditMenu("com.example.does.not.exist")+        assertEquals("com.example.does.not.exist", v.home.value.editingKey)+        v.uninstallOrInfo("com.example.does.not.exist")+        assertNull(v.home.value.editingKey)+        // Leave whatever settings surface opened.+        val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())+        device.waitForIdle(2_000)+        device.pressBack()+        device.waitForIdle(2_000)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/MainActivityRoboTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/MainActivityRoboTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/MainActivityRoboTest.ktnew file mode 100644index 0000000000..2325007c20--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/MainActivityRoboTest.kt@@ -0,0 +1,137 @@+package com.vayunmathur.launcher++import android.app.UiModeManager+import android.content.Intent+import android.content.res.Configuration+import android.provider.Settings+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Robolectric tests for [MainActivity]'s non-UI paths: lifecycle routing,+ * HOME-intent redelivery, and the bridge getters that do not start other+ * activities. The ViewModel's database is lazy, so the activity can be+ * created on the JVM; the workspace load it kicks off degrades against the+ * unavailable SQLCipher driver without taking the activity down.+ */+@RunWith(AndroidJUnit4::class)+class MainActivityRoboTest {++    @Test+    fun `activity creates in phone mode and answers bridge getters`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        assertFalse(activity.isFinishing)+        // Bridge getters that only resolve or measure must be safe.+        activity.isDefaultHome()+        assertNotNull(activity.launchAnimationOptions(0, 0, 100, 100))+        activity.setWallpaperBlurRadius(40)+        controller.pause().stop().destroy()+    }++    @Test+    fun `home intent redelivery resets the activity intent`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        val home = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)+        controller.newIntent(home)+        assertEquals(Intent.ACTION_MAIN, activity.intent?.action)+        assertTrue(activity.intent?.categories?.contains(Intent.CATEGORY_HOME) == true)+        controller.pause().stop().destroy()+    }++    @Test+    fun `home role request falls back to home settings without the role`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        activity.requestHomeRole()+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Settings.ACTION_HOME_SETTINGS, started.action)+        controller.pause().stop().destroy()+    }++    @Test+    fun `wallpaper request opens a chooser`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        activity.pickWallpaper()+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Intent.ACTION_CHOOSER, started.action)+        controller.pause().stop().destroy()+    }++    @Test+    fun `uninstall without the silent permission uses the system confirmation`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        activity.requestUninstall("com.example.app")+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Intent.ACTION_DELETE, started.action)+        assertEquals("package:com.example.app", started.data.toString())+        controller.pause().stop().destroy()+    }++    @Test+    fun `uninstall with the silent permission never opens the confirmation`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        shadowOf(activity.application).grantPermissions("android.permission.DELETE_PACKAGES")+        activity.requestUninstall("com.example.app")+        // The silent path ran (PackageInstaller under Robolectric), so no+        // ACTION_DELETE intent was started.+        assertEquals(null, shadowOf(activity).nextStartedActivity)+        controller.pause().stop().destroy()+    }++    @Test+    fun `widget bind and configure requests resolve to a result`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        var bindResult: Boolean? = null+        activity.requestBindWidget(+            1234,+            android.content.ComponentName("com.example", "com.example.Widget"),+            profileSerial = 0L,+        ) { bindResult = it }+        // Either the launch failed straight to a false callback, or a+        // consent activity is pending; it must never report success here.+        assertTrue(bindResult == null || bindResult == false)+        var configureResult: Boolean? = null+        activity.startWidgetConfigure(1234) { configureResult = it }+        assertTrue(configureResult == null || configureResult == false)+        controller.pause().stop().destroy()+    }++    @Test+    fun `tv mode routes to the tv navigation`() {+        val probe = Robolectric.buildActivity(MainActivity::class.java).get()+        val uiMode = probe.getSystemService(UiModeManager::class.java)+        shadowOf(uiMode).setCurrentModeType(Configuration.UI_MODE_TYPE_TELEVISION)+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        assertFalse(activity.isFinishing)+        controller.resume()+        controller.pause().stop().destroy()+    }++    @Test+    fun `configuration change without a mode flip does not recreate`() {+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        activity.onConfigurationChanged(+            android.content.res.Configuration(activity.resources.configuration),+        )+        assertFalse(activity.isFinishing)+        controller.pause().stop().destroy()+    }+}
launcher/src/test/java/com/vayunmathur/launcher/data/LauncherDaoTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherDaoTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherDaoTest.ktnew file mode 100644index 0000000000..684bb11b9c--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/data/LauncherDaoTest.kt@@ -0,0 +1,196 @@+package com.vayunmathur.launcher.data++import androidx.room3.Room+import androidx.sqlite.driver.bundled.BundledSQLiteDriver+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.toRaw+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * DAO tests for the workspace table: CRUD round trips, container queries,+ * rank ordering, widget-id bookkeeping, and the folder-child lifecycle that+ * [LauncherRepository] builds on.+ *+ * Runs against a real in-memory Room database under Robolectric.+ */+@RunWith(RobolectricTestRunner::class)+class LauncherDaoTest {++    private lateinit var db: LauncherDatabase+    private lateinit var dao: LauncherItemDao++    @BeforeTest+    fun setUp() {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        db = Room.inMemoryDatabaseBuilder(ctx, LauncherDatabase::class.java)+            .setDriver(BundledSQLiteDriver())+            .allowMainThreadQueries()+            .build()+        dao = db.itemDao()+    }++    @AfterTest+    fun tearDown() {+        db.close()+    }++    private fun app(+        screen: Int = 0,+        cellX: Int = 0,+        cellY: Int = 0,+        packageName: String = "com.example.app",+        className: String = "com.example.app.Main",+    ) = LauncherItemEntity(+        itemType = LauncherItemType.APPLICATION,+        containerId = ContainerRef.Desktop.toRaw(),+        screen = screen,+        cellX = cellX,+        cellY = cellY,+        packageName = packageName,+        className = className,+    )++    @Test+    fun upsertAndGetRoundTrip() = runTest {+        assertNull(dao.get(999))+        val id = dao.upsert(app(cellX = 2, cellY = 3))+        val got = dao.get(id) ?: error("missing")+        assertEquals(2, got.cellX)+        assertEquals(3, got.cellY)+        assertEquals(LauncherItemType.APPLICATION, got.itemType)+        assertEquals("com.example.app", got.packageName)+        // Upsert replaces.+        dao.upsert(got.copy(id = id, cellX = 5))+        assertEquals(5, dao.get(id)?.cellX)+    }++    @Test+    fun countAndGetAll() = runTest {+        assertEquals(0, dao.count())+        dao.upsert(app(cellX = 0))+        dao.upsert(app(cellX = 1))+        assertEquals(2, dao.count())+        assertEquals(2, dao.getAll().size)+    }++    @Test+    fun desktopAndHotseatQueriesSplitByContainer() = runTest {+        val hotseatId = dao.upsert(+            app().copy(containerId = ContainerRef.Hotseat.toRaw(), rank = 0),+        )+        dao.upsert(app(cellX = 1))+        assertEquals(1, dao.getDesktopItems().size)+        val hotseat = dao.getHotseatItems()+        assertEquals(listOf(hotseatId), hotseat.map { it.id })+    }++    @Test+    fun hotseatOrderedByRank() = runTest {+        val first = dao.upsert(app().copy(containerId = ContainerRef.Hotseat.toRaw(), rank = 2))+        val second = dao.upsert(app().copy(containerId = ContainerRef.Hotseat.toRaw(), rank = 0))+        val third = dao.upsert(app().copy(containerId = ContainerRef.Hotseat.toRaw(), rank = 1))+        assertEquals(listOf(second, third, first), dao.getHotseatItems().map { it.id })+    }++    @Test+    fun folderChildrenOrderedByRank() = runTest {+        val folderId = dao.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.FOLDER,+                containerId = ContainerRef.Desktop.toRaw(),+            ),+        )+        val a = dao.upsert(app().copy(containerId = folderId, rank = 1))+        val b = dao.upsert(app().copy(containerId = folderId, rank = 0))+        val children = dao.getFolderChildren(folderId)+        assertEquals(listOf(b, a), children.map { it.id })+        assertEquals(2, dao.countFolderChildren(folderId))+    }++    @Test+    fun moveChangesContainerAndRank() = runTest {+        val id = dao.upsert(app(cellX = 0, cellY = 0))+        dao.move(id, ContainerRef.Hotseat.toRaw(), 0, 0, 0, 2)+        val got = dao.get(id) ?: error("missing")+        assertEquals(ContainerRef.Hotseat, got.container)+        assertEquals(2, got.rank)+        assertTrue(dao.getDesktopItems().none { it.id == id })+    }++    @Test+    fun resizeToChangesSpan() = runTest {+        val id = dao.upsert(app())+        dao.resizeTo(id, 1, 1, 2, 3)+        val got = dao.get(id) ?: error("missing")+        assertEquals(1, got.cellX)+        assertEquals(1, got.cellY)+        assertEquals(2, got.spanX)+        assertEquals(3, got.spanY)+    }++    @Test+    fun setTitleAndRank() = runTest {+        val id = dao.upsert(app())+        assertNull(dao.get(id)?.title)+        dao.setTitle(id, "My App")+        assertEquals("My App", dao.get(id)?.title)+        dao.setRank(id, 4)+        assertEquals(4, dao.get(id)?.rank)+    }++    @Test+    fun setHiddenTogglesVisibility() = runTest {+        val id = dao.upsert(app())+        dao.setHidden(id, true)+        assertEquals(true, dao.get(id)?.hidden)+        dao.setHidden(id, false)+        assertEquals(false, dao.get(id)?.hidden)+    }++    @Test+    fun usedWidgetIdsOnlyListsWidgets() = runTest {+        dao.upsert(app())+        dao.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.APPWIDGET,+                containerId = ContainerRef.Desktop.toRaw(),+                appWidgetId = 42,+                appWidgetProvider = "com.example/.Widget",+            ),+        )+        assertEquals(listOf(42), dao.getUsedWidgetIds())+    }++    @Test+    fun deleteByIdRemovesRow() = runTest {+        val id = dao.upsert(app())+        dao.deleteById(id)+        assertNull(dao.get(id))+        assertEquals(0, dao.count())+    }++    @Test+    fun containerRefRoundTripThroughRaw() = runTest {+        val folderId = dao.upsert(+            LauncherItemEntity(+                itemType = LauncherItemType.FOLDER,+                containerId = ContainerRef.Desktop.toRaw(),+            ),+        )+        val childId = dao.upsert(app().copy(containerId = folderId))+        val child = dao.get(childId) ?: error("missing")+        assertEquals(ContainerRef.Folder(folderId), child.container)+        assertNotNull(dao.get(folderId))+    }+}
launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherAppsMonitorTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherAppsMonitorTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherAppsMonitorTest.ktnew file mode 100644index 0000000000..c4e11e2412--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherAppsMonitorTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.launcher.platform++import android.content.ComponentName+import android.content.Context+import android.os.Process+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.launcher.domain.PackageKey+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Tests for [LauncherAppsMonitor] against Robolectric's LauncherApps shadow,+ * which has no launchable activities installed: refresh publishes an empty+ * list, change notifications fire, and lookups degrade to null/false rather+ * than throwing.+ */+@RunWith(AndroidJUnit4::class)+class LauncherAppsMonitorTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private fun awaitApps(monitor: LauncherAppsMonitor, changes: MutableList<PackageKey?>) {+        val deadline = System.nanoTime() + 10_000_000_000L+        while (System.nanoTime() < deadline) {+            if (changes.isNotEmpty()) return+            Thread.sleep(5)+        }+        throw AssertionError("refresh never notified; apps=${monitor.apps.value}")+    }++    @Test+    fun `start refreshes to an empty list and notifies with no stale package`() {+        val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+        try {+            val monitor = LauncherAppsMonitor(context, scope)+            val changes = mutableListOf<PackageKey?>()+            monitor.start { stale -> synchronized(changes) { changes += stale } }+            awaitApps(monitor, changes)+            assertTrue(monitor.apps.value.isEmpty())+            assertEquals(listOf<PackageKey?>(null), synchronized(changes) { changes.toList() })+            assertTrue(monitor.unavailable.value.isEmpty())+            assertTrue(monitor.installedKeys().isEmpty())+            monitor.stop()+        } finally {+            scope.cancel()+        }+    }++    @Test+    fun `refresh with a stale key reports it to the listener`() {+        val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+        try {+            val monitor = LauncherAppsMonitor(context, scope)+            val changes = mutableListOf<PackageKey?>()+            monitor.start { stale -> synchronized(changes) { changes += stale } }+            awaitApps(monitor, changes)+            val stale = PackageKey("com.example.changed", 0L)+            monitor.refresh(stale)+            val deadline = System.nanoTime() + 10_000_000_000L+            while (System.nanoTime() < deadline) {+                synchronized(changes) { if (changes.contains(stale)) break }+                Thread.sleep(5)+            }+            assertTrue(synchronized(changes) { changes.contains(stale) })+            monitor.stop()+        } finally {+            scope.cancel()+        }+    }++    @Test+    fun `lookups for unknown apps degrade safely`() {+        val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+        try {+            val monitor = LauncherAppsMonitor(context, scope)+            val component = ComponentName("com.example", "com.example.Main")+            assertNull(monitor.entryFor(component, 0L))+            assertNull(monitor.icon(component, 0L, 320))+            assertEquals(Process.myUserHandle(), monitor.userFor(0L))+            assertEquals(emptyList(), monitor.shortcuts("com.example", Process.myUserHandle()))+        } finally {+            scope.cancel()+        }+    }++    @Test+    fun `shortcut operations on an unknown shortcut degrade safely`() {+        val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)+        try {+            val monitor = LauncherAppsMonitor(context, scope)+            val intent = android.content.Intent(android.content.Intent.ACTION_VIEW)+                .setComponent(ComponentName("com.example", "com.example.Main"))+            val shortcut = android.content.pm.ShortcutInfo.Builder(context, "shortcut-1")+                .setShortLabel("Shortcut")+                .setIntent(intent)+                .build()+            // Not the default home app, so the role-gated calls must answer+            // with null/false/empty rather than throwing.+            kotlin.test.assertNull(monitor.shortcutIcon(shortcut, 320))+            kotlin.test.assertEquals(false, monitor.startShortcut(shortcut, null))+            monitor.pinShortcut(shortcut)+        } finally {+            scope.cancel()+        }+    }++    @Test+    fun `app entry keys derive from component and serial`() {+        val component = ComponentName("com.example.app", "com.example.app.Main")+        val entry = AppEntry(+            componentName = component,+            label = "Example",+            user = Process.myUserHandle(),+            profileSerial = 0L,+            isWorkProfile = false,+        )+        assertEquals(ComponentKey(component, 0L), entry.key)+        assertEquals(PackageKey("com.example.app", 0L), entry.packageKey)+        val work = entry.copy(user = Process.myUserHandle(), profileSerial = 10L, isWorkProfile = true)+        assertEquals(PackageKey("com.example.app", 10L), work.packageKey)+        assertTrue(work.isWorkProfile)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherPrivilegeRoboTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherPrivilegeRoboTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherPrivilegeRoboTest.ktnew file mode 100644index 0000000000..9ee4a8ceff--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherPrivilegeRoboTest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.launcher.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Tests for [LauncherPrivilege]: on an ordinary (non-privileged) build all+ * probes read false, the shade does not expand, and quiet mode is refused.+ */+@RunWith(RobolectricTestRunner::class)+class LauncherPrivilegeRoboTest {++    private fun privilege(): LauncherPrivilege {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        return LauncherPrivilege(ctx) { null }+    }++    @Test fun ordinaryBuildHoldsNothing() {+        val p = privilege()+        assertEquals(false, p.hasHomeRole())+        assertEquals(false, p.canUninstallSilently())+        assertEquals(false, p.canToggleQuietMode())+        assertEquals(false, p.canExpandNotificationShade())+    }++    @Test fun shadeExpansionReportsThroughTheStatusBarService() {+        // Under Robolectric the status-bar service answers the reflective+        // call, so expansion reports success; the probe stays false because+        // EXPAND_STATUS_BAR is not held.+        assertEquals(true, privilege().expandNotificationShade())+        assertEquals(false, privilege().canExpandNotificationShade())+    }+}
launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherWidgetHostTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherWidgetHostTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherWidgetHostTest.ktnew file mode 100644index 0000000000..51a44d2939--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/LauncherWidgetHostTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.launcher.platform++import android.appwidget.AppWidgetProviderInfo+import android.content.ComponentName+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Tests for the pure parts of [LauncherWidgetHost]: [spanFor] cell math,+ * [flatten]/[unflatten] round trips, and safe [release]/[releaseOrphans]/+ * [updateSize] no-ops.+ */+@RunWith(RobolectricTestRunner::class)+class LauncherWidgetHostTest {++    private fun flow(): WidgetBindFlow {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        return WidgetBindFlow(+            ctx,+            LauncherWidgetHost(ctx),+            android.appwidget.AppWidgetManager.getInstance(ctx),+        )+    }++    private fun info(minWidth: Int, minHeight: Int) = AppWidgetProviderInfo().apply {+        provider = ComponentName("com.example", "com.example.Widget")+        this.minWidth = minWidth+        this.minHeight = minHeight+    }++    @Test fun spanForCoversMinimum() {+        // minWidth in px; density 1 under Robolectric defaults... cover the math.+        val (x, y) = flow().spanFor(info(200, 100), cellWidthDp = 80, cellHeightDp = 80)+        assertTrue(x >= 1)+        assertTrue(y >= 1)+    }++    @Test fun spanForTinyWidgetIsOneCell() {+        assertEquals(1 to 1, flow().spanFor(info(1, 1), cellWidthDp = 80, cellHeightDp = 80))+    }++    @Test fun flattenRoundTrip() {+        val h = flow()+        val flat = h.flatten(ComponentName("com.example", "com.example.Widget"))+        assertEquals(ComponentName("com.example", "com.example.Widget"), h.unflatten(flat))+        assertEquals(null, h.unflatten(null))+        assertEquals(null, h.unflatten("not a component"))+    }++    @Test fun releaseUnknownIdIsSafe() {+        val h = flow()+        h.release(424242)+        h.releaseOrphans(emptySet())+        // Nothing was bound, and the released id still resolves to nothing.+        kotlin.test.assertEquals(null, h.providerInfo(424242))+    }+}
launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.ktnew file mode 100644index 0000000000..b044c6c93c--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/platform/WidgetBindFlowTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.launcher.platform++import android.appwidget.AppWidgetManager+import android.appwidget.AppWidgetProviderInfo+import android.content.ComponentName+import android.content.Context+import android.os.Bundle+import android.os.Process+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Flow tests for [WidgetBindFlow.add] and provider enumeration, driven by+ * Robolectric's app-widget shadow: bind-allowed vs consent-required,+ * configure vs no-configure, and cancellation releasing the allocated id.+ */+@RunWith(AndroidJUnit4::class)+class WidgetBindFlowTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    private class FakeBridge(+        var bindResult: Boolean = true,+        var configureResult: Boolean = true,+    ) : ActivityBridge {+        val bindRequests = mutableListOf<Int>()+        val configureRequests = mutableListOf<Int>()++        override fun requestBindWidget(+            appWidgetId: Int,+            provider: ComponentName,+            profileSerial: Long,+            onResult: (Boolean) -> Unit,+        ) {+            bindRequests += appWidgetId+            onResult(bindResult)+        }++        override fun startWidgetConfigure(appWidgetId: Int, onResult: (Boolean) -> Unit) {+            configureRequests += appWidgetId+            onResult(configureResult)+        }++        override fun pickWallpaper() {}+        override fun requestHomeRole() {}+        override fun isDefaultHome(): Boolean = false+        override fun requestUninstall(packageName: String) {}+        override fun setWallpaperBlurRadius(radiusPx: Int) {}+        override fun launchAnimationOptions(left: Int, top: Int, right: Int, bottom: Int): Bundle? = null+    }++    private fun flow(): WidgetBindFlow {+        val host = LauncherWidgetHost(context)+        return WidgetBindFlow(context, host, AppWidgetManager.getInstance(context))+    }++    private fun info(configure: ComponentName? = null): AppWidgetProviderInfo {+        val info = AppWidgetProviderInfo()+        info.provider = ComponentName("com.example", "com.example.Widget")+        info.configure = configure+        info.minWidth = 100+        info.minHeight = 100+        return info+    }++    @Test+    fun `providers lists installed providers for the whole device and per profile`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        val shadow = shadowOf(widgetManager)+        val providerInfo = info()+        shadow.addInstalledProvider(providerInfo)+        shadow.addInstalledProvidersForProfile(Process.myUserHandle(), providerInfo)++        val flow = flow()+        assertTrue(flow.providers(null).contains(providerInfo))+        assertTrue(flow.providers(Process.myUserHandle()).contains(providerInfo))+    }++    @Test+    fun `providerInfo returns what the manager holds and null for unknown ids`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        val providerInfo = info()+        shadowOf(widgetManager).putWidgetInfo(777, providerInfo)+        val flow = flow()+        assertEquals(providerInfo, flow.providerInfo(777))+        assertNull(flow.providerInfo(778))+    }++    @Test+    fun `add binds directly when allowed and persists without configure`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        shadowOf(widgetManager).setAllowedToBindAppWidgets(true)+        val bridge = FakeBridge()+        var boundId: Int? = null+        var cancelled = 0+        flow().add(info(), bridge, profileSerial = 0L, onBound = { boundId = it }, onCancelled = { cancelled++ })+        assertTrue(boundId != null)+        assertEquals(0, cancelled)+        assertTrue(bridge.bindRequests.isEmpty())+        assertTrue(bridge.configureRequests.isEmpty())+    }++    @Test+    fun `add runs configure when the provider declares one, then persists`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        shadowOf(widgetManager).setAllowedToBindAppWidgets(true)+        val bridge = FakeBridge(configureResult = true)+        var boundId: Int? = null+        flow().add(+            info(configure = ComponentName("com.example", "com.example.Configure")),+            bridge, profileSerial = 0L, onBound = { boundId = it },+        )+        assertTrue(boundId != null)+        assertEquals(listOf(boundId), bridge.configureRequests)+    }++    @Test+    fun `add abandons when configure is cancelled`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        shadowOf(widgetManager).setAllowedToBindAppWidgets(true)+        val bridge = FakeBridge(configureResult = false)+        var boundId: Int? = null+        var cancelled = 0+        flow().add(+            info(configure = ComponentName("com.example", "com.example.Configure")),+            bridge, profileSerial = 0L, onBound = { boundId = it }, onCancelled = { cancelled++ },+        )+        assertNull(boundId)+        assertEquals(1, cancelled)+    }++    @Test+    fun `add asks for consent when binding is not allowed, and honours the answer`() {+        val widgetManager = AppWidgetManager.getInstance(context)+        shadowOf(widgetManager).setAllowedToBindAppWidgets(false)++        val grantedBridge = FakeBridge(bindResult = true)+        var boundId: Int? = null+        flow().add(info(), grantedBridge, profileSerial = 0L, onBound = { boundId = it })+        assertTrue(boundId != null)+        assertEquals(listOf(boundId), grantedBridge.bindRequests)++        val refusedBridge = FakeBridge(bindResult = false)+        var boundId2: Int? = null+        var cancelled = 0+        flow().add(info(), refusedBridge, profileSerial = 0L, onBound = { boundId2 = it }, onCancelled = { cancelled++ })+        assertNull(boundId2)+        assertEquals(1, cancelled)+        assertEquals(1, refusedBridge.bindRequests.size)+    }++    @Test+    fun `host listening guards are idempotent and bound ids read back`() {+        val host = LauncherWidgetHost(context)+        host.startListeningSafely()+        host.startListeningSafely()+        assertEquals(emptySet(), host.boundIds())+        host.stopListeningSafely()+        host.stopListeningSafely()+        assertEquals(0x4C41, LauncherWidgetHost.HOST_ID)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/data/TvPrefsTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/data/TvPrefsTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/data/TvPrefsTest.ktnew file mode 100644index 0000000000..b6050a38d8--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/data/TvPrefsTest.kt@@ -0,0 +1,52 @@+package com.vayunmathur.launcher.tv.data++import androidx.test.core.app.ApplicationProvider+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Tests for [TvPrefs]: row order and quick-settings round-trip through+ * DataStore, starting from [TvSettings] defaults.+ */+@RunWith(RobolectricTestRunner::class)+class TvPrefsTest {++    private fun prefs(): TvPrefs {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        return TvPrefs(ctx)+    }++    @BeforeTest+    fun clearStore() {+        // DataStore persists per context file: wipe it so tests are independent.+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        ctx.getSharedPreferences("tvlauncher_config.preferences_pb", android.content.Context.MODE_PRIVATE)+            .edit().clear().commit()+        java.io.File(ctx.filesDir.parent, "datastore/tvlauncher_config.preferences_pb").delete()+    }++    @Test fun orderRoundTrip() = runTest {+        val p = prefs()+        p.saveOrder(listOf("com.example.a", "com.example.b"))+        assertEquals(listOf("com.example.a", "com.example.b"), p.settings.first().appOrder)+    }++    @Test fun orderOverwrite() = runTest {+        val p = prefs()+        p.saveOrder(listOf("com.example.a"))+        p.saveOrder(listOf("com.example.b", "com.example.c"))+        assertEquals(listOf("com.example.b", "com.example.c"), p.settings.first().appOrder)+    }++    @Test fun quickRoundTrip() = runTest {+        val p = prefs()+        p.saveQuick(listOf("Bluetooth", "SOUND"))+        // Quick settings are normalised to lowercase.+        assertEquals(listOf("bluetooth", "sound"), p.settings.first().quickSettings)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvArtCacheTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvArtCacheTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvArtCacheTest.ktnew file mode 100644index 0000000000..38955c5b43--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvArtCacheTest.kt@@ -0,0 +1,64 @@+package com.vayunmathur.launcher.tv.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertNull+import kotlin.test.assertSame++/**+ * Tests for [TvArtCache]: unknown packages cache a null rather than throwing,+ * installed packages resolve art, and [TvArtCache.drop] evicts so the next+ * load re-queries.+ */+@RunWith(AndroidJUnit4::class)+class TvArtCacheTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private fun cache() = TvArtCache(app)++    @Test+    fun `unknown package banner and icon are null, repeatedly`() = runTest {+        val cache = cache()+        assertNull(cache.banner("com.example.does.not.exist"))+        assertNull(cache.icon("com.example.does.not.exist"))+        // Cached null: the second round must agree without a package to find.+        assertNull(cache.banner("com.example.does.not.exist"))+        assertNull(cache.icon("com.example.does.not.exist"))+    }++    @Test+    fun `own package icon answer is stable and cached`() = runTest {+        val cache = cache()+        // Under Robolectric the rasterised icon may be null (no real launcher+        // icon pipeline); whatever the answer, it must be cached and stable.+        val first = cache.icon(app.packageName)+        val second = cache.icon(app.packageName)+        assertSame(first, second)+    }++    @Test+    fun `drop evicts so art reloads`() = runTest {+        val cache = cache()+        cache.icon(app.packageName)+        cache.drop(app.packageName)+        // After eviction the art is reloaded and re-cached consistently.+        val reloaded = cache.icon(app.packageName)+        assertSame(reloaded, cache.icon(app.packageName))+        cache.drop("com.example.does.not.exist")+        assertNull(cache.icon("com.example.does.not.exist"))+    }++    @Test+    fun `banner for an installed package without leanback art falls back or is null`() = runTest {+        val cache = cache()+        // The test app declares no TV banner; either the app icon fallback or+        // null is correct, but it must not throw and must be stable once cached.+        val first = cache.banner(app.packageName)+        val second = cache.banner(app.packageName)+        assertSame(first, second)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeRoleTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeRoleTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeRoleTest.ktnew file mode 100644index 0000000000..bfcfcb4923--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeRoleTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.launcher.tv.platform++import android.app.Activity+import android.app.role.RoleManager+import android.content.Intent+import android.provider.Settings+import androidx.test.ext.junit.runners.AndroidJUnit4+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.Shadows.shadowOf+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Tests for [TvHomeRole] under Robolectric: without a HOME role available the+ * request falls back to the home-settings page, and default-home detection+ * resolves through the package manager.+ */+@RunWith(AndroidJUnit4::class)+class TvHomeRoleTest {++    private fun activity(): Activity =+        Robolectric.buildActivity(Activity::class.java).setup().get()++    @Test+    fun `default home resolves to this package under Robolectric`() {+        // Robolectric resolves the HOME intent to the launcher's own+        // MainActivity (declared with the HOME category), so the check that+        // compares the resolved package with ours reads true.+        assertTrue(TvHomeRole.isDefaultHome(activity()))+    }++    @Test+    fun `request falls back to home settings when the role is unavailable`() {+        val activity = activity()+        assertTrue(TvHomeRole.requestHomeRole(activity))+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals(Settings.ACTION_HOME_SETTINGS, started.action)+    }++    @Test+    fun `request uses the role intent when the home role is available`() {+        val activity = activity()+        val roleManager = activity.getSystemService(RoleManager::class.java)+        shadowOf(roleManager).addAvailableRole(RoleManager.ROLE_HOME)+        assertTrue(TvHomeRole.requestHomeRole(activity))+        val started = shadowOf(activity).nextStartedActivity+        assertNotNull(started)+        assertEquals("android.app.role.action.REQUEST_ROLE", started.action)+        assertTrue(Intent.ACTION_MAIN != started.action)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelTest.ktnew file mode 100644index 0000000000..6a4b09c673--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvHomeViewModelTest.kt@@ -0,0 +1,113 @@+package com.vayunmathur.launcher.tv.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows++/**+ * State-machine tests for [TvHomeViewModel]: edit menu, move/hold,+ * reorder arming, tile presses and key moves mutate [TvHomeState]+ * synchronously. Package loading is a no-op under Robolectric (no+ * leanback apps installed), so tests seed [TvHomeState] rows via the+ * edit/move methods themselves.+ */+@RunWith(RobolectricTestRunner::class)+class TvHomeViewModelTest {++    private fun vm(): TvHomeViewModel {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        return TvHomeViewModel(app)+    }++    @Test fun editMenuOpensAndCloses() {+        val v = vm()+        v.openEditMenu("com.example.a")+        assertEquals("com.example.a", v.home.value.editingKey)+        assertNull(v.home.value.movingKey)+        v.closeEditMenu()+        assertNull(v.home.value.editingKey)+    }++    @Test fun startMoveHoldsTileAndArms() {+        val v = vm()+        v.startMove("com.example.a")+        assertEquals("com.example.a", v.home.value.movingKey)+        assertEquals(true, v.home.value.reorderArmed)+        assertNull(v.home.value.editingKey)+    }++    @Test fun toggleReorderArmsAndDisarms() {+        val v = vm()+        assertEquals(false, v.home.value.reorderArmed)+        v.toggleReorder()+        assertEquals(true, v.home.value.reorderArmed)+        v.disarmReorder()+        assertEquals(false, v.home.value.reorderArmed)+    }++    @Test fun pressTileOpensNothingWhenNotArmed() {+        val v = vm()+        // Not armed and not moving: opens the app (a no-op under Robolectric+        // with no such package), and crucially does not hold the tile.+        v.pressTile("com.example.a")+        assertNull(v.home.value.movingKey)+    }++    @Test fun pressTileInReorderModePicksUp() {+        val v = vm()+        v.toggleReorder()+        v.pressTile("com.example.a")+        assertEquals("com.example.a", v.home.value.movingKey)+    }++    @Test fun pressingHeldTileDropsIt() = runTest {+        val v = vm()+        v.toggleReorder()+        v.pressTile("com.example.a")+        assertEquals("com.example.a", v.home.value.movingKey)+        v.pressTile("com.example.a")+        // finishMove persists on an IO dispatcher; the hold only clears after+        // that write lands, which a main-looper idle cannot force. The pickup+        // half above is the synchronous, assertable part.+        Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    @Test fun cancelMoveClearsHold() {+        val v = vm()+        v.startMove("com.example.a")+        v.cancelMove()+        assertNull(v.home.value.movingKey)+    }++    @Test fun disarmWhileHoldingCancelsHold() {+        val v = vm()+        v.startMove("com.example.a")+        v.disarmReorder()+        assertNull(v.home.value.movingKey)+    }++    @Test fun moveKeyIgnoresStalePkg() {+        val v = vm()+        v.startMove("com.example.a")+        // A closure for another tile must not move anything.+        v.moveKey("com.example.b", 1)+        assertEquals("com.example.a", v.home.value.movingKey)+    }++    @Test fun closeEditMenuClearsAddMenu() {+        val v = vm()+        v.openEditMenu("com.example.a")+        v.closeEditMenu()+        val s = v.home.value+        assertNull(s.editingKey)+        assertNull(s.movingKey)+        assertTrue(s.addCandidates.isEmpty())+        assertEquals(false, s.showAddMenu)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvInputsTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvInputsTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvInputsTest.ktnew file mode 100644index 0000000000..e6aea7d744--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/platform/TvInputsTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.launcher.tv.platform++import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Tests for [TvInputs]: with no TV input service under Robolectric the+ * list is empty, and opening an input with no handlers is a safe no-op.+ */+@RunWith(RobolectricTestRunner::class)+class TvInputsTest {++    private fun ctx() = ApplicationProvider.getApplicationContext<android.content.Context>()++    @Test fun noServiceListsNothing() {+        assertEquals(emptyList(), TvInputs.list(ctx(), max = 4))+    }++    @Test fun openWithNoHandlersDoesNotThrow() {+        // No Live TV apps installed: every startActivity throws and is swallowed.+        TvInputs.open(ctx(), "hdmi1")+    }++    @Test fun maxHdmiSlotsMath() {+        // Sanity: the bottom row always keeps room for Settings and Add.+        assertTrue(+            com.vayunmathur.launcher.tv.domain.TvRowOrder.maxHdmiSlots(hasStore = true) <=+                com.vayunmathur.launcher.tv.domain.TvRowOrder.maxHdmiSlots(hasStore = false),+        )+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvEditMenuTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvEditMenuTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvEditMenuTest.ktnew file mode 100644index 0000000000..50c6e0bfa4--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvEditMenuTest.kt@@ -0,0 +1,166 @@+package com.vayunmathur.launcher.tv.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.launcher.tv.platform.TvAppEntry+import com.vayunmathur.launcher.tv.platform.TvHomeState+import com.vayunmathur.launcher.tv.platform.TvTile+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals++/**+ * Compose tests (Robolectric + createComposeRule) for [TvEditMenu]: the+ * edit dialog names the tile and offers Move/Replace/Remove plus+ * Uninstall (user apps) or App info (system apps); the add menu lists+ * candidates.+ */+@RunWith(AndroidJUnit4::class)+class LauncherTvEditMenuTest {++    @get:Rule val rule = createComposeRule()++    private fun tile(pkg: String, label: String, user: Boolean = true) = TvTile(+        packageName = pkg,+        label = label,+        banner = null,+        appIcon = null,+        userInstalled = user,+    )++    private fun show(+        state: TvHomeState,+        onStartMove: (String) -> Unit = {},+        onRemove: () -> Unit = {},+        onUninstallOrInfo: () -> Unit = {},+        onDismiss: () -> Unit = {},+    ) {+        rule.setContent {+            TvEditMenu(+                state = state,+                onDismiss = onDismiss,+                onStartMove = onStartMove,+                onReplace = {},+                onRemove = onRemove,+                onUninstallOrInfo = onUninstallOrInfo,+                onPickAddCandidate = {},+                onCloseAddMenu = {},+            )+        }+    }++    @Test fun userAppMenuOffersUninstall() {+        show(TvHomeState(rowApps = listOf(tile("com.example.a", "Alpha")), editingKey = "com.example.a"))+        rule.onNodeWithText("Alpha").assertIsDisplayed()+        rule.onNodeWithText("Move").assertIsDisplayed()+        rule.onNodeWithText("Replace").assertIsDisplayed()+        rule.onNodeWithText("Remove from home").assertIsDisplayed()+        rule.onNodeWithText("Uninstall").assertIsDisplayed()+    }++    @Test fun systemAppMenuOffersAppInfo() {+        show(+            TvHomeState(+                rowApps = listOf(tile("com.android.sys", "System", user = false)),+                editingKey = "com.android.sys",+            ),+        )+        rule.onNodeWithText("App info").assertIsDisplayed()+    }++    @Test fun moveRowStartsMove() {+        var moved: String? = null+        show(+            TvHomeState(rowApps = listOf(tile("com.example.a", "Alpha")), editingKey = "com.example.a"),+            onStartMove = { moved = it },+        )+        rule.onNodeWithText("Move").performClick()+        assertEquals("com.example.a", moved)+    }++    @Test fun removeRowRemoves() {+        var removed = false+        show(+            TvHomeState(rowApps = listOf(tile("com.example.a", "Alpha")), editingKey = "com.example.a"),+            onRemove = { removed = true },+        )+        rule.onNodeWithText("Remove from home").performClick()+        assertEquals(true, removed)+    }++    @Test fun addMenuListsCandidates() {+        var picked: String? = null+        rule.setContent {+            TvEditMenu(+                state = TvHomeState(+                    showAddMenu = true,+                    addCandidates = listOf(+                        TvAppEntry("com.example.a", "Alpha", true),+                        TvAppEntry("com.example.b", "Beta", true),+                    ),+                ),+                onDismiss = {},+                onStartMove = {},+                onReplace = {},+                onRemove = {},+                onUninstallOrInfo = {},+                onPickAddCandidate = { picked = it },+                onCloseAddMenu = {},+            )+        }+        rule.onNodeWithText("Add an app").assertIsDisplayed()+        rule.onNodeWithText("Beta").performClick()+        assertEquals("com.example.b", picked)+    }++    @Test fun addMenuEmptyReadsEveryAppHere() {+        rule.setContent {+            TvEditMenu(+                state = TvHomeState(showAddMenu = true),+                onDismiss = {},+                onStartMove = {},+                onReplace = {},+                onRemove = {},+                onUninstallOrInfo = {},+                onPickAddCandidate = {},+                onCloseAddMenu = {},+            )+        }+        rule.onNodeWithText("Every app is already here").assertIsDisplayed()+    }++    @Test fun replaceMenuNamesCurrent() {+        rule.setContent {+            TvEditMenu(+                state = TvHomeState(+                    rowApps = listOf(tile("com.example.a", "Alpha")),+                    showAddMenu = true,+                    addReplacesIndex = 0,+                    addCandidates = listOf(TvAppEntry("com.example.b", "Beta", true)),+                ),+                onDismiss = {},+                onStartMove = {},+                onReplace = {},+                onRemove = {},+                onUninstallOrInfo = {},+                onPickAddCandidate = {},+                onCloseAddMenu = {},+            )+        }+        rule.onNodeWithText("Replace Alpha").assertIsDisplayed()+    }++    @Test fun noEditingKeyRendersNothing() {+        show(TvHomeState(rowApps = listOf(tile("com.example.a", "Alpha"))))+        // The tile grid is not this composable's business; only the dialog is.+        assertEquals(+            0,+            rule.onAllNodesWithText("Move").fetchSemanticsNodes().size,+        )+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvPageTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvPageTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvPageTest.ktnew file mode 100644index 0000000000..033142d688--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvPageTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.launcher.tv.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.launcher.tv.platform.TvHomeViewModel+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals++/**+ * Compose tests (Robolectric + createComposeRule): [TvHomePage] wires a+ * real [TvHomeViewModel] to [TvHomeScreen] without crashing, and+ * [TvClockHeader] renders.+ */+@RunWith(AndroidJUnit4::class)+class LauncherTvPageTest {++    @get:Rule val rule = createComposeRule()++    @Test fun tvHomePageComposes() {+        val app = ApplicationProvider.getApplicationContext<android.app.Application>()+        val vm = TvHomeViewModel(app)+        rule.setContent { TvHomePage(viewModel = vm) }+        // Empty grid under Robolectric: no tiles, but the clock header is there.+        assertEquals(0, rule.onAllNodesWithText("Alpha").fetchSemanticsNodes().size)+    }++    @Test fun clockHeaderRenders() {+        rule.setContent { TvClockHeader(onOpenNetworkSettings = {}) }+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvUiTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvUiTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvUiTest.ktnew file mode 100644index 0000000000..7c43570a1e--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/LauncherTvUiTest.kt@@ -0,0 +1,211 @@+package com.vayunmathur.launcher.tv.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.launcher.tv.platform.TvHdmiInput+import com.vayunmathur.launcher.tv.platform.TvHomeState+import com.vayunmathur.launcher.tv.platform.TvTile+import com.vayunmathur.launcher.tv.ui.components.TvBannerTile+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals++/**+ * Compose tests (Robolectric + createComposeRule) for the TV home screen:+ * [TvBannerTile] states and press handling, [TvAppGrid] rows, [TvBottomRow]+ * inputs/store tiles, and [TvHomeScreen] end to end.+ */+@RunWith(AndroidJUnit4::class)+class LauncherTvUiTest {++    @get:Rule val rule = createComposeRule()++    private fun tile(pkg: String, label: String) = TvTile(+        packageName = pkg,+        label = label,+        banner = null,+        appIcon = null,+        userInstalled = true,+    )++    private val tiles = listOf(+        tile("com.example.a", "Alpha"),+        tile("com.example.b", "Beta"),+        tile("com.example.c", "Gamma"),+    )++    @Test fun bannerTileRendersLabelAndPresses() {+        var pressed = false+        rule.setContent {+            TvBannerTile(+                tile = tiles[0],+                tileWidth = 200.dp,+                artHeight = 100.dp,+                moving = false,+                dimmed = false,+                focusRequester = null,+                onPress = { pressed = true },+                onEdit = {},+                onMove = {},+            )+        }+        // Label shows on the tile and in the caption below it.+        assertEquals(2, rule.onAllNodesWithText("Alpha").fetchSemanticsNodes().size)+        rule.onAllNodesWithText("Alpha")[0].performClick()+        assertEquals(true, pressed)+    }++    @Test fun tileWithBannerArtRenders() {+        rule.setContent {+            TvBannerTile(+                tile = tiles[0].copy(banner = android.graphics.drawable.ColorDrawable(0xFF112233.toInt())),+                tileWidth = 200.dp,+                artHeight = 100.dp,+                moving = false,+                dimmed = false,+                focusRequester = null,+                onPress = {},+                onEdit = {},+                onMove = {},+            )+        }+        rule.waitForIdle()+    }++    @Test fun focusedTileShowsRing() {+        val requester = androidx.compose.ui.focus.FocusRequester()+        rule.setContent {+            TvBannerTile(+                tile = tiles[0],+                tileWidth = 200.dp,+                artHeight = 100.dp,+                moving = false,+                dimmed = false,+                focusRequester = requester,+                onPress = {},+                onEdit = {},+                onMove = {},+            )+        }+        rule.runOnIdle { requester.requestFocus() }+        rule.waitForIdle()+        // Focused: caption still shows under the ring.+        assertEquals(2, rule.onAllNodesWithText("Alpha").fetchSemanticsNodes().size)+    }++    @Test fun dimmedTileRenders() {+        rule.setContent {+            TvBannerTile(+                tile = tiles[1],+                tileWidth = 200.dp,+                artHeight = 100.dp,+                moving = false,+                dimmed = true,+                focusRequester = null,+                onPress = {},+                onEdit = {},+                onMove = {},+            )+        }+        assertEquals(2, rule.onAllNodesWithText("Beta").fetchSemanticsNodes().size)+    }++    @Test fun movingTileShowsMovingBadge() {+        rule.setContent {+            TvBannerTile(+                tile = tiles[0],+                tileWidth = 200.dp,+                artHeight = 100.dp,+                moving = true,+                dimmed = false,+                focusRequester = null,+                onPress = {},+                onEdit = {},+                onMove = {},+            )+        }+        rule.onNodeWithText("MOVING", substring = true).assertIsDisplayed()+    }++    @Test fun appGridRendersRowTiles() {+        rule.setContent {+            TvAppGrid(+                state = TvHomeState(rowApps = tiles),+                onPressTile = {},+                onOpenEditMenu = {},+                onMoveKey = { _, _ -> },+            )+        }+        assertEquals(2, rule.onAllNodesWithText("Alpha").fetchSemanticsNodes().size)+        assertEquals(2, rule.onAllNodesWithText("Beta").fetchSemanticsNodes().size)+        assertEquals(2, rule.onAllNodesWithText("Gamma").fetchSemanticsNodes().size)+    }++    @Test fun appGridPressReachesCallback() {+        var pressed: String? = null+        rule.setContent {+            TvAppGrid(+                state = TvHomeState(rowApps = tiles),+                onPressTile = { pressed = it },+                onOpenEditMenu = {},+                onMoveKey = { _, _ -> },+            )+        }+        rule.onAllNodesWithText("Beta")[0].performClick()+        assertEquals("com.example.b", pressed)+    }++    @Test fun bottomRowRendersInputsAndStore() {+        rule.setContent {+            TvBottomRow(+                state = TvHomeState(+                    showAppStore = true,+                    hdmiInputs = listOf(+                        TvHdmiInput("hdmi1", "HDMI 1"),+                    ),+                ),+                onOpenAppStore = {},+                onOpenInput = {},+                onOpenSettings = {},+                onToggleReorder = {},+            )+        }+        rule.onNodeWithText("HDMI 1").assertIsDisplayed()+    }++    @Test fun homeScreenRendersClockAndTiles() {+        var pressed: String? = null+        rule.setContent {+            TvHomeScreen(+                state = TvHomeState(rowApps = tiles),+                onPressTile = { pressed = it },+                onOpenAppStore = {},+                onOpenInput = {},+                onOpenSettings = {},+                onOpenNetworkSettings = {},+                onOpenEditMenu = {},+                onCloseEditMenu = {},+                onStartMove = {},+                onCancelMove = {},+                onToggleReorder = {},+                onDisarmReorder = {},+                onMoveKey = { _, _ -> },+                onRemoveTile = {},+                onOpenAddMenu = {},+                onPickAddCandidate = {},+                onUninstallOrInfo = {},+                onRefreshHome = {},+                onRequestHomeRole = {},+            )+        }+        assertEquals(2, rule.onAllNodesWithText("Alpha").fetchSemanticsNodes().size)+        rule.onAllNodesWithText("Alpha")[0].performClick()+        assertEquals("com.example.a", pressed)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvBannerTileKeyTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvBannerTileKeyTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvBannerTileKeyTest.ktnew file mode 100644index 0000000000..7aa137ef10--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvBannerTileKeyTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.launcher.tv.ui.components++import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.input.key.Key+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performKeyInput+import androidx.compose.ui.test.pressKey+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.launcher.tv.domain.TvRowOrder+import com.vayunmathur.launcher.tv.platform.TvTile+import org.junit.Rule+import org.junit.Test+import org.junit.runner.RunWith+import kotlin.test.assertEquals++/**+ * D-pad key handling for [TvBannerTile]: while a tile is held, direction+ * keys move it (by one, or by a row vertically), Menu is swallowed, and+ * when not held Menu on key-up opens the edit menu instead.+ */+@RunWith(AndroidJUnit4::class)+class TvBannerTileKeyTest {++    @get:Rule+    val composeRule = createComposeRule()++    private fun tile() = TvTile(+        packageName = "com.example.tv",+        label = "TV App",+        banner = null,+        appIcon = null,+        userInstalled = true,+    )++    private class Recorder {+        val moves = mutableListOf<Int>()+        var edits = 0+        var presses = 0+    }++    private fun show(moving: Boolean, recorder: Recorder) {+        composeRule.setContent {+            val focusRequester = remember { FocusRequester() }+            LaunchedEffect(Unit) { focusRequester.requestFocus() }+            TvBannerTile(+                tile = tile(),+                tileWidth = 160.dp,+                artHeight = 90.dp,+                moving = moving,+                dimmed = false,+                focusRequester = focusRequester,+                onPress = { recorder.presses++ },+                onEdit = { recorder.edits++ },+                onMove = { recorder.moves += it },+            )+        }+        composeRule.waitForIdle()+    }++    @Test+    fun `held tile moves with direction keys and swallows menu`() {+        val recorder = Recorder()+        show(moving = true, recorder = recorder)+        composeRule.onRoot().performKeyInput {+            pressKey(Key.DirectionRight)+            pressKey(Key.DirectionLeft)+            pressKey(Key.DirectionDown)+            pressKey(Key.DirectionUp)+            pressKey(Key.Menu)+        }+        composeRule.waitForIdle()+        assertEquals(+            listOf(1, -1, TvRowOrder.PER_ROW, -TvRowOrder.PER_ROW),+            recorder.moves,+        )+        assertEquals(0, recorder.edits)+    }++    @Test+    fun `unheld tile opens edit on menu and ignores directions`() {+        val recorder = Recorder()+        show(moving = false, recorder = recorder)+        composeRule.onRoot().performKeyInput {+            pressKey(Key.DirectionRight)+            pressKey(Key.Menu)+        }+        composeRule.waitForIdle()+        assertEquals(emptyList(), recorder.moves)+        assertEquals(1, recorder.edits)+        assertEquals(0, recorder.presses)+    }+}
launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvReorderHintTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvReorderHintTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvReorderHintTest.ktnew file mode 100644index 0000000000..ce9ca4f895--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/tv/ui/components/TvReorderHintTest.kt@@ -0,0 +1,37 @@+package com.vayunmathur.launcher.tv.ui.components++import androidx.co

Diff truncated.