Modern Apps git

← Modern-Apps.git

wear: launcher becomes the watch app drawer

Commit
898be2aedae37e24c7f7b6d026b67c42be08e75e
Author
Vayun Mathur <[email protected]>
When
2026-11-24 22:24 UTC (11 days ago)
Parents
361daf3
New :launcher:wear module (phone launcher's package/
signing). Stock Wear OS cannot elect a third-party HOME
(privileged system component, no ROLE_HOME for third
parties), so this is a launcher-style app users open/
pin: full app drawer from on-device packages, watch-
local recents, quick access to our wear companions,
local search, and settings rows that only open system
intents that actually resolve (no fake toggles). The
phone hotseat (<=10 favorites) syncs over WearLink;
recents never upload. MAOS could grant real HOME OS-
side later - noted, not implemented.

Verified: wear assemble + 12/12 wear tests + wear lint;
phone launcher compiles, lint + protocol tests pass
(1 pre-existing drawer test failure untouched).

Diff

launcher-wear/AGENTS.md
diff --git a/launcher-wear/AGENTS.md b/launcher-wear/AGENTS.mdnew file mode 100644index 0000000000..064945e6c1--- /dev/null+++ b/launcher-wear/AGENTS.md@@ -0,0 +1,59 @@+# AGENTS.md โ€” launcher-wear/ (':launcher:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `launcher-wear/` + `launcher/` (the phone side of the same feature).++- Gradle: :launcher:wear (dir launcher-wear/) / convention: `common-conventions-wear`+- Package roots present: ui, data, domain, platform, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS launcher-style companion of the phone Launcher (`:launcher`): a+full-screen app drawer / home-replacement *experience* on the watch. This+module deliberately uses `applicationId = "com.vayunmathur.launcher"` (the+phone app's) with the shared dev/release signing from the convention+plugins: WearLink's handshake token requires the same signing certificate+on both sides, so changing either breaks phone<->watch sync. Bootstrap is+a one-time ADB sideload of this APK onto the watch.++## What a watch launcher can and cannot be (platform reality)+- **Stock Wear OS: NOT the system HOME.** The watch home (watch face ++  system app launcher) is a privileged system component. There is no+  public `CATEGORY_HOME` election or `ROLE_HOME` grant for third-party+  apps on stock Wear OS builds (unlike phone/TV, where `:launcher`+  legitimately declares HOME). This module therefore declares only+  MAIN+LAUNCHER and must never claim HOME: users open/pin this app in the+  system launcher and get the launcher experience inside it.+- **What this provides:** app drawer for installed watch apps+  (icon+label, platform launch intents), favorites/pinned row synced+  from the phone hotseat, watch-local recents, quick access to our wear+  companions when installed, local search/filter, and settings rows that+  open only system intents that resolve on the watch (no fake toggles -+  brightness has no public direct intent, so Display opens system+  display settings).+- **Tiles/complications: not provided.** No wear module in this repo uses+  Tiles and `androidx.wear.tiles` is not in the version catalog; adding+  it is a supply-chain/build decision, not a cheap add-on here.+- **MAOS follow-up (OS-side only, not implemented here):** a privileged+  MAOS build could grant this package a real HOME/watch-launcher role+  (privileged permission / default-home configuration). That belongs in+  the OS build, never in this app module.++## Protocol+`domain/WearLauncherProtocol.kt` is a copy of the phone's file (Gradle+cannot depend on another app module). Change both copies together; each+side's `WearLauncherProtocolTest` pins the same golden JSON.++- Favorites + watch-state sync: WearLink data items+  (`/launcher/favorites`, `/launcher/watch-state`)+- Sync request: WearLink message (`/launcher/request-sync`), watch -> phone only+- Only the phone hotseat (pinned row) syncs - not the workspace grid,+  folders or widgets. Recents are watch-local and never sync.+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Verify (this module only)+```+./gradlew :launcher:wear:assembleDev+./gradlew :launcher:wear:testDebugUnitTest+./gradlew :launcher:wear:lint+```
launcher-wear/build.gradle.kts
diff --git a/launcher-wear/build.gradle.kts b/launcher-wear/build.gradle.ktsnew file mode 100644index 0000000000..3b06687978--- /dev/null+++ b/launcher-wear/build.gradle.kts@@ -0,0 +1,34 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "apps"+}++// Version shared with the phone app (root version.txt), as in notes-wear:+// common-conventions-wear inlines 1/"1.0" until a consumer wires the reader.+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+    // Same applicationId + signing as :launcher is load-bearing: WearLink's+    // handshake token requires the same signing certificate on both sides,+    // and the watch app must be installable alongside (not instead of) the+    // phone launcher package identity. The namespace only names resources.+    namespace = "com.vayunmathur.launcher.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.launcher"+        minSdk = 31+        versionCode = wearVersionCode+        versionName = wearVersionName+    }+}++dependencies {+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
launcher-wear/src/main/AndroidManifest.xml
diff --git a/launcher-wear/src/main/AndroidManifest.xml b/launcher-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..f44707a4d5--- /dev/null+++ b/launcher-wear/src/main/AndroidManifest.xml@@ -0,0 +1,55 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Watch hardware: this build only installs on Wear OS. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <uses-permission android:name="android.permission.WAKE_LOCK" />++    <!-- Package visibility for the app drawer (Android 11+). -->+    <queries>+        <intent>+            <action android:name="android.intent.action.MAIN" />+            <category android:name="android.intent.category.LAUNCHER" />+        </intent>+    </queries>++    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">++        <!-- Paired with the phone launcher, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <!--+          Deliberately MAIN + LAUNCHER only, with NO CATEGORY_HOME:+          on stock Wear OS the home/watch-face + system-launcher role is+          held by the privileged system launcher and there is no public+          HOME-intent election or ROLE_HOME grant for third-party apps+          (unlike phone/TV). Claiming HOME here would be a false promise.+          This activity is the launcher-style app users open (and can pin+          in the system launcher); on MAOS a privileged build could grant+          a real HOME role as an OS-side follow-up. See AGENTS.md.+        -->+        <activity+            android:name=".ui.WearMainActivity"+            android:exported="true"+            android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>+</manifest>
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/data/WearLauncherStore.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/data/WearLauncherStore.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/data/WearLauncherStore.ktnew file mode 100644index 0000000000..69827347f2--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/data/WearLauncherStore.kt@@ -0,0 +1,66 @@+package com.vayunmathur.launcher.wear.data++import android.content.Context+import com.vayunmathur.launcher.wear.domain.RecentLaunch+import com.vayunmathur.launcher.wear.domain.WearFavoritesSnapshot+import com.vayunmathur.launcher.wear.domain.WearLauncherWatchState+import com.vayunmathur.launcher.wear.domain.WearLauncherProtocol+import com.vayunmathur.launcher.wear.domain.recordRecentLaunch+import com.vayunmathur.launcher.wear.sync.WearLinkBridge+import com.vayunmathur.library.log.Log+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: the last favorites snapshot from the phone plus+ * watch-local recents, persisted as JSON so the launcher renders offline.+ */+class WearLauncherStore private constructor(private val context: Context) {+    companion object {+        private const val TAG = "WearLauncherStore"++        @Volatile private var instance: WearLauncherStore? = null++        fun get(context: Context): WearLauncherStore = instance ?: synchronized(this) {+            instance ?: WearLauncherStore(context.applicationContext).also { instance = it }+        }+    }++    private val snapshotFile = File(context.filesDir, "wear-launcher-favorites.json")+    private val recentsFile = File(context.filesDir, "wear-launcher-recents.json")++    private val _snapshot = MutableStateFlow(loadSnapshot())+    val snapshot: StateFlow<WearFavoritesSnapshot> = _snapshot.asStateFlow()++    private val _recents = MutableStateFlow(loadRecents())+    val recents: StateFlow<List<RecentLaunch>> = _recents.asStateFlow()++    fun setSnapshot(snapshot: WearFavoritesSnapshot, installedCount: Int) {+        _snapshot.value = snapshot+        runCatching { snapshotFile.writeText(WearLauncherProtocol.json.encodeToString(snapshot)) }+            .onFailure { Log.status(TAG, "persist favorites failed: ${it.message}") }+        publishWatchState(installedCount)+    }++    fun recordLaunch(packageName: String) {+        val updated = recordRecentLaunch(_recents.value, packageName, System.currentTimeMillis())+        _recents.value = updated+        runCatching { recentsFile.writeText(WearLauncherProtocol.json.encodeToString(updated)) }+            .onFailure { Log.status(TAG, "persist recents failed: ${it.message}") }+    }++    fun publishWatchState(installedCount: Int = 0) {+        WearLinkBridge.publishWatchState(context, _snapshot.value, installedCount)+    }++    private fun loadSnapshot(): WearFavoritesSnapshot = runCatching {+        WearLauncherProtocol.json.decodeFromString<WearFavoritesSnapshot>(snapshotFile.readText())+    }.getOrDefault(WearFavoritesSnapshot())++    private fun loadRecents(): List<RecentLaunch> = runCatching {+        WearLauncherProtocol.json.decodeFromString<List<RecentLaunch>>(recentsFile.readText())+    }.getOrDefault(emptyList())+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherModel.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherModel.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherModel.ktnew file mode 100644index 0000000000..e21f7bb7e9--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherModel.kt@@ -0,0 +1,135 @@+package com.vayunmathur.launcher.wear.domain++import kotlinx.serialization.Serializable++/** One launchable watch app (icon is resolved on-device, never synced). */+data class WatchApp(+    val packageName: String,+    val className: String,+    val label: String,+)++/** One watch-local launch, for the recents row. */+@Serializable+data class RecentLaunch(+    val packageName: String,+    val launchedAtMillis: Long,+)++/** Our own wear companions, in quick-access order. Presence is checked, never assumed. */+data class WearCompanion(val packageName: String, val label: String)++val WEAR_COMPANIONS: List<WearCompanion> = listOf(+    WearCompanion("com.vayunmathur.appstore", "App Store"),+    WearCompanion("com.vayunmathur.calendar", "Calendar"),+    WearCompanion("com.vayunmathur.contacts", "Contacts"),+    WearCompanion("com.vayunmathur.notes", "Notes"),+    WearCompanion("com.vayunmathur.weather", "Weather"),+    WearCompanion("com.vayunmathur.clock", "Clock"),+)++const val MAX_RECENTS = 6++/** The watch home's sections, all derived from installed apps + synced favorites. */+data class WearLauncherSections(+    /** Synced phone favorites that are installed on the watch, in phone rank order. */+    val favorites: List<WatchApp> = emptyList(),+    /** Synced favorites with no matching watch app (named so absence is honest). */+    val missingFavorites: List<WearFavorite> = emptyList(),+    val recents: List<WatchApp> = emptyList(),+    val companions: List<WatchApp> = emptyList(),+    val all: List<WatchApp> = emptyList(),+)++/**+ * Maps installed watch apps into home sections. Pure: installed-app+ * enumeration and icon loading stay in `platform/`.+ *+ * - Duplicate packages keep the first label-sorted component.+ * - The launcher itself ([ownPackageName]) is excluded: it is the surface.+ * - A favorite matches by package, preferring its exact component.+ * - Recents exclude favorites (a pinned app needs no second row) and cap+ *   at [MAX_RECENTS]; companions exclude favorites only, so a recently+ *   used companion can appear twice by design (quick access is a shortcut+ *   row, not a partition of all apps).+ */+fun buildWearLauncherSections(+    installed: List<WatchApp>,+    snapshot: WearFavoritesSnapshot,+    recents: List<RecentLaunch>,+    ownPackageName: String,+): WearLauncherSections {+    val sorted = installed+        .filter { it.packageName.isNotBlank() && it.className.isNotBlank() }+        .filter { it.packageName != ownPackageName }+        .sortedWith(compareBy({ it.label.lowercase() }, { it.packageName }, { it.className }))+    // The drawer shows one row per package; favorites may name any component.+    val apps = sorted.distinctBy { it.packageName }+    if (apps.isEmpty()) {+        return WearLauncherSections(missingFavorites = snapshot.favorites)+    }+    val byPackage = apps.associateBy { it.packageName }+    val favorites = mutableListOf<WatchApp>()+    val missing = mutableListOf<WearFavorite>()+    snapshot.favorites.sortedBy { it.rank }.forEach { favorite ->+        val exact = sorted.firstOrNull {+            it.packageName == favorite.packageName && it.className == favorite.className+        }+        val match = exact ?: byPackage[favorite.packageName]+        if (match == null) missing += favorite else favorites += match+    }+    val favoritePackages = favorites.map { it.packageName }.toSet()+    val recentApps = recents+        .sortedByDescending { it.launchedAtMillis }+        .mapNotNull { byPackage[it.packageName] }+        .distinctBy { it.packageName }+        .filterNot { it.packageName in favoritePackages }+        .take(MAX_RECENTS)+    val companions = WEAR_COMPANIONS+        .filterNot { it.packageName in favoritePackages }+        .mapNotNull { byPackage[it.packageName] }+    return WearLauncherSections(favorites, missing, recentApps, companions, apps)+}++/** Phone-parity drawer filter: label prefix matches first, then contains. */+fun filterWatchApps(apps: List<WatchApp>, query: String): List<WatchApp> {+    val trimmed = query.trim()+    if (trimmed.isEmpty()) return apps+    val (prefix, contains) = apps+        .filter { it.label.contains(trimmed, ignoreCase = true) }+        .partition { it.label.startsWith(trimmed, ignoreCase = true) }+    return prefix + contains+}++/** Records a launch at the front of the recents list (watch-local only). */+fun recordRecentLaunch(+    existing: List<RecentLaunch>,+    packageName: String,+    launchedAtMillis: Long,+): List<RecentLaunch> {+    if (packageName.isBlank()) return existing+    return (listOf(RecentLaunch(packageName, launchedAtMillis)) + existing)+        .distinctBy { it.packageName }+        .sortedByDescending { it.launchedAtMillis }+        .take(MAX_RECENTS)+}++/**+ * A settings row the watch may offer. [action] is the platform intent+ * action string; a row exists only when the platform resolves it, so the+ * launcher never renders a fake brightness/sound toggle it cannot honour.+ * Brightness in particular has no public direct intent on Wear OS: the+ * Display row opens the system display settings where brightness lives.+ */+enum class WearSettingsTarget(val label: String, val action: String) {+    DISPLAY("Display & brightness", "android.settings.DISPLAY_SETTINGS"),+    SOUND("Sound", "android.settings.SOUND_SETTINGS"),+    CONNECTIVITY("Connectivity", "android.settings.WIFI_SETTINGS"),+    ACCESSIBILITY("Accessibility", "android.settings.ACCESSIBILITY_SETTINGS"),+    APPS("App info", "android.settings.APPLICATION_SETTINGS"),+    SYSTEM("System settings", "android.settings.SETTINGS"),+}++/** Only the settings rows whose intent actually resolves on this watch. */+fun availableWearSettingsTargets(resolvableActions: Set<String>): List<WearSettingsTarget> =+    WearSettingsTarget.entries.filter { it.action in resolvableActions }
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocol.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocol.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocol.ktnew file mode 100644index 0000000000..cbbc6e1d20--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocol.kt@@ -0,0 +1,116 @@+package com.vayunmathur.launcher.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Launcher companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:launcher:wear`, applicationId `com.vayunmathur.launcher`) carries a copy+ * of this file under `com.vayunmathur.launcher.wear.domain`. Change both+ * copies together; each side's unit tests pin the same golden JSON so a+ * one-sided edit fails loudly on the side that was not updated.+ *+ * What syncs, and what deliberately does not:+ * - Phone -> watch: only the phone hotseat (the pinned/favorites row), as+ *   package + component + label in rank order. The full workspace grid,+ *   folders and widgets do not sync: a round watch has no paged grid to put+ *   them on, and inventing a mapping would misrepresent the phone layout.+ * - Watch -> phone: only a watch-state receipt and a request-sync message.+ *   Recents are watch-local launch history; sending them to the phone would+ *   create a second, competing launch-count truth next to the phone's own.+ *+ * Transport (WearLink, :library:wearlink - RFCOMM, no Play services):+ * presence is a completed handshake for [CAPABILITY] (the applicationId);+ * delivery needs a live session and each side persists what it receives.+ */+object WearLauncherProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "launcher_wear_companion"++    /** Data-item path (phone -> watch): the [WearFavoritesSnapshot] JSON. */+    const val FAVORITES_PATH = "/launcher/favorites"++    /** Data-item path (watch -> phone): the [WearLauncherWatchState] JSON. */+    const val WATCH_STATE_PATH = "/launcher/watch-state"++    /** Message path (watch -> phone): ask the phone to publish fresh favorites. */+    const val REQUEST_SYNC_PATH = "/launcher/request-sync"++    /** Most pinned apps sent; the phone hotseat is capped well below this. */+    const val MAX_FAVORITES = 10++    /** Largest snapshot JSON in UTF-8 bytes, aligned with the other wear apps. */+    const val MAX_JSON_BYTES = 90_000++    /** Label cap applied when a snapshot is built. */+    const val MAX_LABEL_CHARS = 60++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One pinned (hotseat) app in rank order. */+@Serializable+data class WearFavorite(+    val packageName: String,+    /** Flattened component class, empty when the phone row had none. */+    val className: String = "",+    val label: String = "",+    val rank: Int = 0,+)++/** The phone's bounded favorites snapshot for the watch ([WearLauncherProtocol.FAVORITES_PATH]). */+@Serializable+data class WearFavoritesSnapshot(+    val generatedAtMillis: Long = 0L,+    val favorites: List<WearFavorite> = emptyList(),+    /** True when the count/size caps dropped pinned apps. */+    val truncated: Boolean = false,+)++/** What the watch last applied, published at [WearLauncherProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearLauncherWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val favoriteCount: Int = 0,+    val installedCount: Int = 0,+)++/**+ * Builds a bounded favorites snapshot from [candidates]: drops blank+ * packages, de-duplicates by package (lowest rank wins), sorts by rank then+ * label, caps labels, then enforces [WearLauncherProtocol.MAX_FAVORITES] and+ * [WearLauncherProtocol.MAX_JSON_BYTES] dropping lowest-ranked first.+ */+fun buildWearFavorites(+    candidates: List<WearFavorite>,+    generatedAtMillis: Long,+): WearFavoritesSnapshot {+    val cleaned = candidates+        .filter { it.packageName.isNotBlank() }+        .groupBy { it.packageName }+        .values.map { group -> group.minWith(compareBy({ it.rank }, { it.label })) }+        .sortedWith(compareBy({ it.rank }, { it.label.lowercase() }, { it.packageName }))+        .mapIndexed { index, favorite ->+            favorite.copy(label = favorite.label.take(WearLauncherProtocol.MAX_LABEL_CHARS), rank = index)+        }+    var kept = cleaned.take(WearLauncherProtocol.MAX_FAVORITES)+    var truncated = kept.size < cleaned.size+    var snapshot = WearFavoritesSnapshot(generatedAtMillis, kept, truncated)+    while (kept.isNotEmpty() &&+        WearLauncherProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+        WearLauncherProtocol.MAX_JSON_BYTES+    ) {+        kept = kept.dropLast(1)+        truncated = true+        snapshot = WearFavoritesSnapshot(generatedAtMillis, kept, truncated)+    }+    return snapshot+}++/** True when a watch companion completed a WearLink handshake. */+fun wearLauncherCompanionPresent(peerCount: Int): Boolean = peerCount > 0
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/platform/InstalledApps.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/platform/InstalledApps.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/platform/InstalledApps.ktnew file mode 100644index 0000000000..3d93156c56--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/platform/InstalledApps.kt@@ -0,0 +1,63 @@+package com.vayunmathur.launcher.wear.platform++import android.content.ComponentName+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.provider.Settings+import com.vayunmathur.launcher.wear.domain.WatchApp+import com.vayunmathur.launcher.wear.domain.WearSettingsTarget+import com.vayunmathur.launcher.wear.domain.availableWearSettingsTargets++/**+ * Device enumeration for the watch drawer: MAIN+LAUNCHER activities via+ * PackageManager. Icons are loaded by the UI from PackageManager on-device;+ * they never travel over WearLink.+ */+object InstalledApps {+    fun load(context: Context): List<WatchApp> {+        val pm = context.packageManager+        val intent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)+        return runCatching {+            pm.queryIntentActivities(intent, PackageManager.MATCH_ALL)+                .mapNotNull { info ->+                    val activity = info.activityInfo ?: return@mapNotNull null+                    WatchApp(+                        packageName = activity.packageName,+                        className = activity.name,+                        label = info.loadLabel(pm).toString(),+                    )+                }+        }.getOrDefault(emptyList())+    }++    /** The platform launch intent for [app], or null when it vanished since enumeration. */+    fun launchIntent(context: Context, app: WatchApp): Intent? {+        val explicit = Intent(Intent.ACTION_MAIN)+            .addCategory(Intent.CATEGORY_LAUNCHER)+            .setComponent(ComponentName(app.packageName, app.className))+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+        return if (context.packageManager.resolveActivity(explicit, 0) != null) {+            explicit+        } else {+            context.packageManager.getLaunchIntentForPackage(app.packageName)+        }+    }++    /** Settings rows whose system intent resolves on this watch (capability check). */+    fun settingsTargets(context: Context): List<WearSettingsTarget> {+        val pm = context.packageManager+        val resolvable = WearSettingsTarget.entries+            .filter { target ->+                pm.resolveActivity(Intent(target.action), PackageManager.MATCH_DEFAULT_ONLY) != null+            }+            .map { it.action }+            .toSet()+        return availableWearSettingsTargets(resolvable)+    }++    fun settingsIntent(target: WearSettingsTarget): Intent = Intent(target.action)++    /** Generic system-settings fallback entry point. */+    fun systemSettingsIntent(): Intent = Intent(Settings.ACTION_SETTINGS)+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearLinkBridge.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearLinkBridge.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..1abe44b422--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearLinkBridge.kt@@ -0,0 +1,70 @@+package com.vayunmathur.launcher.wear.sync++import android.content.Context+import com.vayunmathur.launcher.wear.data.WearLauncherStore+import com.vayunmathur.launcher.wear.domain.WearFavoritesSnapshot+import com.vayunmathur.launcher.wear.domain.WearLauncherProtocol+import com.vayunmathur.launcher.wear.domain.WearLauncherWatchState+import com.vayunmathur.launcher.wear.platform.InstalledApps+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Launcher: favorites data items land in+ * [WearLauncherStore], watch state goes back as a data item, and+ * request-sync is a message. Delivery is bound to this process being alive;+ * there is no system listener waking a dead watch app.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile private var node: WearLinkNode? = null++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearLauncherProtocol.FAVORITES_PATH) return+                val snapshot = runCatching {+                    WearLauncherProtocol.json.decodeFromString<WearFavoritesSnapshot>(body.decodeToString())+                }.getOrNull()+                if (snapshot == null) {+                    Log.status(TAG, "ignoring malformed favorites snapshot")+                    return+                }+                WearLauncherStore.get(context).setSnapshot(snapshot, InstalledApps.load(context).size)+            }+        }+        return WearLinkNode(context, WearLauncherProtocol.CAPABILITY, listener).also { it.start() }+    }++    fun publishWatchState(context: Context, snapshot: WearFavoritesSnapshot, installedCount: Int) {+        val state = WearLauncherWatchState(+            appliedGeneratedAtMillis = snapshot.generatedAtMillis,+            favoriteCount = snapshot.favorites.size,+            installedCount = installedCount,+        )+        scope.launch {+            get(context).putData(+                WearLauncherProtocol.WATCH_STATE_PATH,+                WearLauncherProtocol.json.encodeToString(state).encodeToByteArray(),+            )+        }+    }++    suspend fun requestSync(context: Context): Boolean =+        get(context).sendMessage(WearLauncherProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearSyncRequest.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearSyncRequest.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearSyncRequest.ktnew file mode 100644index 0000000000..a46517e13a--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/sync/WearSyncRequest.kt@@ -0,0 +1,6 @@+package com.vayunmathur.launcher.wear.sync++import android.content.Context++/** Asks the phone for fresh favorites; false when no session is live. */+suspend fun requestWearSync(context: Context): Boolean = WearLinkBridge.requestSync(context)
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearAllAppsScreen.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearAllAppsScreen.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearAllAppsScreen.ktnew file mode 100644index 0000000000..29f9c20545--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearAllAppsScreen.kt@@ -0,0 +1,106 @@+package com.vayunmathur.launcher.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.launcher.wear.R+import com.vayunmathur.launcher.wear.data.WearLauncherStore+import com.vayunmathur.launcher.wear.domain.WatchApp+import com.vayunmathur.launcher.wear.domain.buildWearLauncherSections+import com.vayunmathur.launcher.wear.domain.filterWatchApps+import com.vayunmathur.launcher.wear.platform.InstalledApps+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/** Full drawer: every launchable watch app, with a local text filter. */+@Composable+fun WearAllAppsScreen(store: WearLauncherStore, onBack: () -> Unit) {+    val context = LocalContext.current+    val snapshot by store.snapshot.collectAsState()+    var query by remember { mutableStateOf("") }+    val installed by produceState(initialValue = emptyList<WatchApp>(), context) {+        value = withContext(Dispatchers.IO) { InstalledApps.load(context) }+    }+    val all = remember(installed, snapshot) {+        buildWearLauncherSections(installed, snapshot, emptyList(), context.packageName).all+    }+    val filtered = remember(all, query) { filterWatchApps(all, query) }+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.wear_all_apps),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            // SCAFFOLD SEARCH EXCEPTION: Wear Compose Material has no scaffold+            // search slot; this is the watch drawer's only search field.+            BasicTextField(+                value = query,+                onValueChange = { query = it },+                singleLine = true,+                textStyle = TextStyle(color = Color.White, fontSize = 14.sp),+                decorationBox = { inner ->+                    if (query.isEmpty()) {+                        Text(stringResource(R.string.wear_search_apps), color = Color.Gray, fontSize = 14.sp)+                    }+                    inner()+                },+                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),+            )+        }+        if (filtered.isEmpty()) {+            item {+                Text(+                    if (all.isEmpty()) stringResource(R.string.wear_no_apps)+                    else stringResource(R.string.wear_no_matches),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(filtered, key = { it.packageName }) { app ->+                WearAppChip(app) {+                    val intent = InstalledApps.launchIntent(context, app) ?: return@WearAppChip+                    store.recordLaunch(app.packageName)+                    runCatching { context.startActivity(intent) }+                }+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearLauncherScreen.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearLauncherScreen.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearLauncherScreen.ktnew file mode 100644index 0000000000..9c82440dda--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearLauncherScreen.kt@@ -0,0 +1,208 @@+package com.vayunmathur.launcher.wear.ui++import android.graphics.drawable.Drawable+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.core.graphics.drawable.toBitmap+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.launcher.wear.R+import com.vayunmathur.launcher.wear.data.WearLauncherStore+import com.vayunmathur.launcher.wear.domain.WatchApp+import com.vayunmathur.launcher.wear.domain.buildWearLauncherSections+import com.vayunmathur.launcher.wear.platform.InstalledApps+import com.vayunmathur.launcher.wear.sync.requestWearSync+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/** Round home: favorites, recents, our-apps shortcuts, then drawer/settings entries. */+@Composable+fun WearLauncherScreen(+    store: WearLauncherStore,+    onOpenAllApps: () -> Unit,+    onOpenSettings: () -> Unit,+) {+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    val snapshot by store.snapshot.collectAsState()+    val recents by store.recents.collectAsState()+    var syncNote by remember { mutableStateOf<String?>(null) }+    val requestedText = stringResource(R.string.wear_sync_requested)+    val noPhoneText = stringResource(R.string.wear_no_phone)+    val installed by produceState(initialValue = emptyList<WatchApp>(), context) {+        value = withContext(Dispatchers.IO) { InstalledApps.load(context) }+    }+    val sections = remember(installed, snapshot, recents) {+        buildWearLauncherSections(installed, snapshot, recents, context.packageName)+    }+    val listState = rememberScalingLazyListState()++    fun launch(app: WatchApp) {+        val intent = InstalledApps.launchIntent(context, app) ?: return+        store.recordLaunch(app.packageName)+        runCatching { context.startActivity(intent) }+    }++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.app_name),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            Text(+                stringResource(R.string.wear_not_home_note),+                style = MaterialTheme.typography.caption2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        syncNote?.let { note ->+            item {+                Text(+                    note,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        if (installed.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_no_apps),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            if (sections.favorites.isNotEmpty()) {+                item { WearSectionHeader(stringResource(R.string.wear_favorites)) }+                items(sections.favorites, key = { "fav:${it.packageName}" }) { app ->+                    WearAppChip(app) { launch(app) }+                }+            } else {+                item {+                    Text(+                        stringResource(R.string.wear_no_favorites),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            sections.missingFavorites.forEach { favorite ->+                item(key = "missing:${favorite.packageName}") {+                    Text(+                        stringResource(R.string.wear_missing_favorite, favorite.label.ifBlank { favorite.packageName }),+                        style = MaterialTheme.typography.caption2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 2.dp),+                    )+                }+            }+            if (sections.recents.isNotEmpty()) {+                item { WearSectionHeader(stringResource(R.string.wear_recent)) }+                items(sections.recents, key = { "recent:${it.packageName}" }) { app ->+                    WearAppChip(app) { launch(app) }+                }+            }+            if (sections.companions.isNotEmpty()) {+                item { WearSectionHeader(stringResource(R.string.wear_our_apps)) }+                items(sections.companions, key = { "ours:${it.packageName}" }) { app ->+                    WearAppChip(app) { launch(app) }+                }+            }+        }+        item {+            Chip(+                onClick = onOpenAllApps,+                label = { Text(stringResource(R.string.wear_all_apps), maxLines = 1) },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onOpenSettings,+                label = { Text(stringResource(R.string.wear_settings), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    scope.launch {+                        syncNote = if (requestWearSync(context)) requestedText else noPhoneText+                    }+                },+                label = { Text(stringResource(R.string.wear_request_sync), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++@Composable+internal fun WearSectionHeader(text: String) {+    Text(+        text,+        style = MaterialTheme.typography.caption1,+        textAlign = TextAlign.Center,+        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+    )+}++/** One launchable app row with its on-device icon (loaded from PackageManager). */+@Composable+internal fun WearAppChip(app: WatchApp, onClick: () -> Unit) {+    val context = LocalContext.current+    val icon by produceState<Drawable?>(initialValue = null, app.packageName) {+        value = withContext(Dispatchers.IO) {+            runCatching { context.packageManager.getApplicationIcon(app.packageName) }.getOrNull()+        }+    }+    Chip(+        onClick = onClick,+        label = { Text(app.label, maxLines = 1) },+        icon = {+            icon?.let { drawable ->+                Image(+                    bitmap = drawable.toBitmap(48, 48).asImageBitmap(),+                    contentDescription = null,+                    modifier = Modifier.size(24.dp),+                )+            }+        },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearMainActivity.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearMainActivity.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..0103131f84--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearMainActivity.kt@@ -0,0 +1,45 @@+package com.vayunmathur.launcher.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.launcher.wear.data.WearLauncherStore++/**+ * Watch launcher entry. This is a launcher-style app drawer, not the system+ * home: stock Wear OS reserves home for the system launcher (see manifest).+ * It renders from installed apps + the last synced favorites, fully offline.+ */+class WearMainActivity : ComponentActivity() {+    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val store = WearLauncherStore.get(this)+        com.vayunmathur.launcher.wear.sync.WearLinkBridge.get(this)+        store.publishWatchState()+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.Home) }+                when (route) {+                    WearRoute.Home -> WearLauncherScreen(+                        store = store,+                        onOpenAllApps = { route = WearRoute.AllApps },+                        onOpenSettings = { route = WearRoute.Settings },+                    )+                    WearRoute.AllApps -> WearAllAppsScreen(+                        store = store,+                        onBack = { route = WearRoute.Home },+                    )+                    WearRoute.Settings -> WearSettingsScreen(+                        onBack = { route = WearRoute.Home },+                    )+                }+            }+        }+    }+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearRoute.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearRoute.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..f2664581c7--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearRoute.kt@@ -0,0 +1,8 @@+package com.vayunmathur.launcher.wear.ui++/** Watch launcher destinations; screens are routes, never selection state. */+sealed interface WearRoute {+    data object Home : WearRoute+    data object AllApps : WearRoute+    data object Settings : WearRoute+}
launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearSettingsScreen.kt
diff --git a/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearSettingsScreen.kt b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearSettingsScreen.ktnew file mode 100644index 0000000000..ac912ed2a1--- /dev/null+++ b/launcher-wear/src/main/java/com/vayunmathur/launcher/wear/ui/WearSettingsScreen.kt@@ -0,0 +1,72 @@+package com.vayunmathur.launcher.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.launcher.wear.R+import com.vayunmathur.launcher.wear.platform.InstalledApps++/**+ * Settings shortcuts: only system intents that resolve on this watch.+ * No brightness/sound toggles are faked here - each row opens the system+ * screen that actually owns the setting.+ */+@Composable+fun WearSettingsScreen(onBack: () -> Unit) {+    val context = LocalContext.current+    val targets = remember(context) { InstalledApps.settingsTargets(context) }+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.wear_settings),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (targets.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_settings_unavailable),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(targets, key = { it.action }) { target ->+                Chip(+                    onClick = {+                        runCatching { context.startActivity(InstalledApps.settingsIntent(target)) }+                    },+                    label = { Text(target.label, maxLines = 1) },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
launcher-wear/src/main/res/values/colors.xml
diff --git a/launcher-wear/src/main/res/values/colors.xml b/launcher-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..f42ada656e--- /dev/null+++ b/launcher-wear/src/main/res/values/colors.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
launcher-wear/src/main/res/values/strings.xml
diff --git a/launcher-wear/src/main/res/values/strings.xml b/launcher-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..e29e1f4907--- /dev/null+++ b/launcher-wear/src/main/res/values/strings.xml@@ -0,0 +1,20 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Launcher</string>+    <string name="wear_favorites">Favorites</string>+    <string name="wear_recent">Recent</string>+    <string name="wear_our_apps">Our apps</string>+    <string name="wear_all_apps">All apps</string>+    <string name="wear_settings">Settings</string>+    <string name="wear_search_apps">Search apps</string>+    <string name="wear_no_apps">No launchable apps found on this watch yet.</string>+    <string name="wear_no_matches">No matches</string>+    <string name="wear_no_favorites">No phone favorites synced yet. Open Launcher on your phone to sync.</string>+    <string name="wear_missing_favorite">Not installed on this watch: %1$s</string>+    <string name="wear_request_sync">Sync favorites</string>+    <string name="wear_sync_requested">Asked your phone for favorites</string>+    <string name="wear_no_phone">Phone not reachable โ€” showing the last synced favorites</string>+    <string name="wear_settings_unavailable">No system settings screen is available on this watch.</string>+    <string name="wear_not_home_note">This is an app, not the watch home screen โ€” stock Wear OS keeps home for the system launcher.</string>+    <string name="wear_back">Back</string>+</resources>
launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherModelTest.kt
diff --git a/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherModelTest.kt b/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherModelTest.ktnew file mode 100644index 0000000000..3b412692c5--- /dev/null+++ b/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherModelTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.launcher.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class WearLauncherModelTest {++    private fun app(pkg: String, label: String, cls: String = "$pkg.Main") =+        WatchApp(pkg, cls, label)++    private val installed = listOf(+        app("com.vayunmathur.calendar", "Calendar"),+        app("com.vayunmathur.weather", "Weather"),+        app("com.example.zebra", "Zebra"),+        app("com.example.alpha", "alpha"),+        app("com.vayunmathur.launcher", "Launcher"),+        app("com.example.alpha", "alpha duplicate", "com.example.alpha.Other"),+        app("", "blank"),+        app("com.example.noclass", "NoClass", ""),+    )++    private val snapshot = WearFavoritesSnapshot(+        generatedAtMillis = 10L,+        favorites = listOf(+            WearFavorite("com.example.zebra", "com.example.zebra.Main", "Zebra", 1),+            WearFavorite("com.vayunmathur.calendar", "", "Calendar", 0),+            WearFavorite("com.example.absent", "", "Absent", 2),+        ),+    )++    @Test+    fun sectionsMapFavoritesRecentsCompanionsAndAll() {+        val sections = buildWearLauncherSections(+            installed = installed,+            snapshot = snapshot,+            recents = listOf(+                RecentLaunch("com.example.alpha", 100L),+                RecentLaunch("com.vayunmathur.calendar", 200L), // favorite: excluded from recents+                RecentLaunch("com.example.gone", 300L), // not installed: dropped+            ),+            ownPackageName = "com.vayunmathur.launcher",+        )+        assertEquals(+            listOf("com.vayunmathur.calendar", "com.example.zebra"),+            sections.favorites.map { it.packageName },+        )+        assertEquals(listOf("com.example.absent"), sections.missingFavorites.map { it.packageName })+        assertEquals(listOf("com.example.alpha"), sections.recents.map { it.packageName })+        // Weather is a companion; Calendar is already a favorite so excluded there.+        assertEquals(listOf("com.vayunmathur.weather"), sections.companions.map { it.packageName })+        // All: self, blanks, no-class and duplicate packages removed; label-sorted.+        assertEquals(+            listOf("com.example.alpha", "com.vayunmathur.calendar", "com.vayunmathur.weather", "com.example.zebra"),+            sections.all.map { it.packageName },+        )+    }++    @Test+    fun favoritePrefersExactComponent() {+        val two = listOf(+            WatchApp("com.example.multi", "com.example.multi.Second", "Multi"),+            WatchApp("com.example.multi", "com.example.multi.First", "Multi"),+        )+        val sections = buildWearLauncherSections(+            two,+            WearFavoritesSnapshot(1L, listOf(WearFavorite("com.example.multi", "com.example.multi.Second", "Multi", 0))),+            emptyList(),+            ownPackageName = "com.vayunmathur.launcher",+        )+        assertEquals("com.example.multi.Second", sections.favorites.single().className)+    }++    @Test+    fun capabilityAbsentYieldsEmptySectionsExceptMissing() {+        val sections = buildWearLauncherSections(+            installed = emptyList(),+            snapshot = snapshot,+            recents = listOf(RecentLaunch("com.example.alpha", 1L)),+            ownPackageName = "com.vayunmathur.launcher",+        )+        assertTrue(sections.favorites.isEmpty())+        assertTrue(sections.recents.isEmpty())+        assertTrue(sections.companions.isEmpty())+        assertTrue(sections.all.isEmpty())+        assertEquals(snapshot.favorites, sections.missingFavorites)+    }++    @Test+    fun noSnapshotStillGivesDrawerAndCompanions() {+        val sections = buildWearLauncherSections(+            installed, WearFavoritesSnapshot(), emptyList(), "com.vayunmathur.launcher",+        )+        assertTrue(sections.favorites.isEmpty())+        assertTrue(sections.missingFavorites.isEmpty())+        assertEquals(4, sections.all.size)+        assertEquals(+            listOf("com.vayunmathur.calendar", "com.vayunmathur.weather"),+            sections.companions.map { it.packageName },+        )+    }++    @Test+    fun filterPrefersPrefixThenContains() {+        val apps = listOf(app("a", "Calendar"), app("b", "Vacation Calendar"), app("c", "Camera"))+        assertEquals(listOf("Calendar", "Vacation Calendar"), filterWatchApps(apps, "cal").map { it.label })+        assertEquals(apps, filterWatchApps(apps, "  "))+        assertTrue(filterWatchApps(apps, "zzz").isEmpty())+    }++    @Test+    fun recordLaunchDedupesCapsAndIgnoresBlank() {+        var recents = emptyList<RecentLaunch>()+        recents = recordRecentLaunch(recents, "a", 1L)+        recents = recordRecentLaunch(recents, "b", 2L)+        recents = recordRecentLaunch(recents, "a", 3L)+        assertEquals(listOf("a", "b"), recents.map { it.packageName })+        assertEquals(recents, recordRecentLaunch(recents, "", 4L))+        (0 until 10).forEach { recents = recordRecentLaunch(recents, "p$it", 10L + it) }+        assertEquals(MAX_RECENTS, recents.size)+    }++    @Test+    fun settingsTargetsOnlyResolvableNoFakeToggles() {+        assertTrue(availableWearSettingsTargets(emptySet()).isEmpty())+        assertEquals(+            listOf(WearSettingsTarget.DISPLAY, WearSettingsTarget.SYSTEM),+            availableWearSettingsTargets(+                setOf("android.settings.DISPLAY_SETTINGS", "android.settings.SETTINGS"),+            ),+        )+    }+}
launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocolTest.kt
diff --git a/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocolTest.kt b/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocolTest.ktnew file mode 100644index 0000000000..58d328b23e--- /dev/null+++ b/launcher-wear/src/test/java/com/vayunmathur/launcher/wear/domain/WearLauncherProtocolTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.launcher.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearLauncherProtocolTest {++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearFavoritesSnapshot(+            generatedAtMillis = 1_000L,+            favorites = listOf(+                WearFavorite("com.example.calendar", "com.example.calendar.Main", "Calendar", 0),+            ),+            truncated = false,+        )+        assertEquals(+            """{"generatedAtMillis":1000,"favorites":[{"packageName":"com.example.calendar",""" ++                """"className":"com.example.calendar.Main","label":"Calendar"}]}""",+            WearLauncherProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun snapshotRoundTrips() {+        val snapshot = WearFavoritesSnapshot(+            generatedAtMillis = 9L,+            favorites = listOf(WearFavorite("com.example.notes", "", "Notes", 1)),+            truncated = true,+        )+        val decoded = WearLauncherProtocol.json.decodeFromString<WearFavoritesSnapshot>(+            WearLauncherProtocol.json.encodeToString(snapshot),+        )+        assertEquals(snapshot, decoded)+    }++    @Test+    fun buildSortsByRankDedupesAndReRanks() {+        val snapshot = buildWearFavorites(+            candidates = listOf(+                WearFavorite("com.example.b", "", "B", 2),+                WearFavorite("com.example.a", "", "A", 1),+                WearFavorite("com.example.a", "", "A duplicate", 0),+                WearFavorite("", "", "blank", 0),+            ),+            generatedAtMillis = 5L,+        )+        // Duplicate keeps lowest rank (0), then re-ranked in rank order.+        assertEquals(listOf("com.example.a", "com.example.b"), snapshot.favorites.map { it.packageName })+        assertEquals(listOf(0, 1), snapshot.favorites.map { it.rank })+        assertEquals("A duplicate", snapshot.favorites[0].label)+        assertFalse(snapshot.truncated)+    }++    @Test+    fun buildCapsCountAndMarksTruncated() {+        val candidates = (0 until WearLauncherProtocol.MAX_FAVORITES + 3).map {+            WearFavorite("com.example.$it", "", "App $it", it)+        }+        val snapshot = buildWearFavorites(candidates, generatedAtMillis = 1L)+        assertEquals(WearLauncherProtocol.MAX_FAVORITES, snapshot.favorites.size)+        assertTrue(snapshot.truncated)+    }++    @Test+    fun companionPresenceIsCountBased() {+        assertFalse(wearLauncherCompanionPresent(0))+        assertTrue(wearLauncherCompanionPresent(1))+    }+}
launcher/build.gradle.kts
diff --git a/launcher/build.gradle.kts b/launcher/build.gradle.ktsindex d8071745db..077bff9204 100644--- a/launcher/build.gradle.kts+++ b/launcher/build.gradle.kts@@ -28,6 +28,8 @@ android { dependencies {     implementRoom(libs)     implementation(project(":library:room"))+    // Phone side of the watch-launcher favorites sync (see domain/WearLauncherProtocol.kt).+    implementation(project(":library:wearlink"))     implementation(libs.androidx.datastore.preferences)     // 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.
launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt b/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.ktindex 876989731e..dbffa8cfad 100644--- a/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt+++ b/launcher/src/main/java/com/vayunmathur/launcher/MainActivity.kt@@ -85,6 +85,9 @@ class MainActivity : MaActivity(), ActivityBridge {     override fun onCreateBeforeContent() {         tvMode = isTvMode()         viewModel.bridge = this+        // Wear favorites sync (phone hotseat -> watch launcher). No-op state+        // when there is no watch: absence is normal, never an error.+        if (!tvMode) com.vayunmathur.launcher.sync.WearLauncherSync.get(this).start()     }      @Composable@@ -122,6 +125,9 @@ class MainActivity : MaActivity(), ActivityBridge {         // Cheap enough to redo every time we come back: an app may have been installed or         // uninstalled while we were away without us being alive to hear the callback.         viewModel.reconcileNowImpl()+        // Republish the hotseat snapshot: layout edits since the last resume+        // are exactly what the watch favorites row should reflect.+        com.vayunmathur.launcher.sync.WearLauncherSync.get(this).syncNow()     }      override fun onStop() {
launcher/src/main/java/com/vayunmathur/launcher/domain/WearLauncherProtocol.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/domain/WearLauncherProtocol.kt b/launcher/src/main/java/com/vayunmathur/launcher/domain/WearLauncherProtocol.ktnew file mode 100644index 0000000000..2e23788b49--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/domain/WearLauncherProtocol.kt@@ -0,0 +1,116 @@+package com.vayunmathur.launcher.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Launcher companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:launcher:wear`, applicationId `com.vayunmathur.launcher`) carries a copy+ * of this file under `com.vayunmathur.launcher.wear.domain`. Change both+ * copies together; each side's unit tests pin the same golden JSON so a+ * one-sided edit fails loudly on the side that was not updated.+ *+ * What syncs, and what deliberately does not:+ * - Phone -> watch: only the phone hotseat (the pinned/favorites row), as+ *   package + component + label in rank order. The full workspace grid,+ *   folders and widgets do not sync: a round watch has no paged grid to put+ *   them on, and inventing a mapping would misrepresent the phone layout.+ * - Watch -> phone: only a watch-state receipt and a request-sync message.+ *   Recents are watch-local launch history; sending them to the phone would+ *   create a second, competing launch-count truth next to the phone's own.+ *+ * Transport (WearLink, :library:wearlink - RFCOMM, no Play services):+ * presence is a completed handshake for [CAPABILITY] (the applicationId);+ * delivery needs a live session and each side persists what it receives.+ */+object WearLauncherProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "launcher_wear_companion"++    /** Data-item path (phone -> watch): the [WearFavoritesSnapshot] JSON. */+    const val FAVORITES_PATH = "/launcher/favorites"++    /** Data-item path (watch -> phone): the [WearLauncherWatchState] JSON. */+    const val WATCH_STATE_PATH = "/launcher/watch-state"++    /** Message path (watch -> phone): ask the phone to publish fresh favorites. */+    const val REQUEST_SYNC_PATH = "/launcher/request-sync"++    /** Most pinned apps sent; the phone hotseat is capped well below this. */+    const val MAX_FAVORITES = 10++    /** Largest snapshot JSON in UTF-8 bytes, aligned with the other wear apps. */+    const val MAX_JSON_BYTES = 90_000++    /** Label cap applied when a snapshot is built. */+    const val MAX_LABEL_CHARS = 60++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One pinned (hotseat) app in rank order. */+@Serializable+data class WearFavorite(+    val packageName: String,+    /** Flattened component class, empty when the phone row had none. */+    val className: String = "",+    val label: String = "",+    val rank: Int = 0,+)++/** The phone's bounded favorites snapshot for the watch ([WearLauncherProtocol.FAVORITES_PATH]). */+@Serializable+data class WearFavoritesSnapshot(+    val generatedAtMillis: Long = 0L,+    val favorites: List<WearFavorite> = emptyList(),+    /** True when the count/size caps dropped pinned apps. */+    val truncated: Boolean = false,+)++/** What the watch last applied, published at [WearLauncherProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearLauncherWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val favoriteCount: Int = 0,+    val installedCount: Int = 0,+)++/**+ * Builds a bounded favorites snapshot from [candidates]: drops blank+ * packages, de-duplicates by package (lowest rank wins), sorts by rank then+ * label, caps labels, then enforces [WearLauncherProtocol.MAX_FAVORITES] and+ * [WearLauncherProtocol.MAX_JSON_BYTES] dropping lowest-ranked first.+ */+fun buildWearFavorites(+    candidates: List<WearFavorite>,+    generatedAtMillis: Long,+): WearFavoritesSnapshot {+    val cleaned = candidates+        .filter { it.packageName.isNotBlank() }+        .groupBy { it.packageName }+        .values.map { group -> group.minWith(compareBy({ it.rank }, { it.label })) }+        .sortedWith(compareBy({ it.rank }, { it.label.lowercase() }, { it.packageName }))+        .mapIndexed { index, favorite ->+            favorite.copy(label = favorite.label.take(WearLauncherProtocol.MAX_LABEL_CHARS), rank = index)+        }+    var kept = cleaned.take(WearLauncherProtocol.MAX_FAVORITES)+    var truncated = kept.size < cleaned.size+    var snapshot = WearFavoritesSnapshot(generatedAtMillis, kept, truncated)+    while (kept.isNotEmpty() &&+        WearLauncherProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+        WearLauncherProtocol.MAX_JSON_BYTES+    ) {+        kept = kept.dropLast(1)+        truncated = true+        snapshot = WearFavoritesSnapshot(generatedAtMillis, kept, truncated)+    }+    return snapshot+}++/** True when a watch companion completed a WearLink handshake. */+fun wearLauncherCompanionPresent(peerCount: Int): Boolean = peerCount > 0
launcher/src/main/java/com/vayunmathur/launcher/sync/WearLauncherSync.kt
diff --git a/launcher/src/main/java/com/vayunmathur/launcher/sync/WearLauncherSync.kt b/launcher/src/main/java/com/vayunmathur/launcher/sync/WearLauncherSync.ktnew file mode 100644index 0000000000..1c4708a32f--- /dev/null+++ b/launcher/src/main/java/com/vayunmathur/launcher/sync/WearLauncherSync.kt@@ -0,0 +1,150 @@+package com.vayunmathur.launcher.sync++import android.content.Context+import android.content.pm.PackageManager+import com.vayunmathur.launcher.data.LauncherRepository+import com.vayunmathur.launcher.domain.ContainerRef+import com.vayunmathur.launcher.domain.LauncherItemType+import com.vayunmathur.launcher.domain.WearFavorite+import com.vayunmathur.launcher.domain.WearLauncherProtocol+import com.vayunmathur.launcher.domain.WearLauncherWatchState+import com.vayunmathur.launcher.domain.buildWearFavorites+import com.vayunmathur.launcher.domain.wearLauncherCompanionPresent+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString++/** Phone-side wear status; absence of a watch is a normal state, never an error. */+data class WearLauncherSyncState(+    val companionPresent: Boolean = false,+    val lastPublishedAtMillis: Long? = null,+    val lastWatchAppliedAtMillis: Long? = null,+    val lastPublishedFavoriteCount: Int = 0,+)++/**+ * Phone side of the launcher wear sync over WearLink (RFCOMM,+ * :library:wearlink): presence is a completed handshake, the favorites+ * snapshot is a data item, and the watch's request-sync is a message+ * handled here while this process lives. There is no Play-services+ * listener service: a request arriving while the launcher is dead waits+ * until it next runs (it republish on connect in any case).+ *+ * Only the hotseat - the pinned/favorites row - is exported. The paged+ * workspace, folders and widgets stay phone-only by design (see the+ * protocol file), and watch recents never come back here.+ */+class WearLauncherSync private constructor(context: Context) {+    companion object {+        private const val TAG = "WearLauncherSync"++        @Volatile private var instance: WearLauncherSync? = null++        fun get(context: Context): WearLauncherSync = instance ?: synchronized(this) {+            instance ?: WearLauncherSync(context.applicationContext).also { instance = it }+        }+    }++    private val appContext = context.applicationContext+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private val _state = MutableStateFlow(WearLauncherSyncState())+    val state: StateFlow<WearLauncherSyncState> = _state.asStateFlow()++    private val listener = object : WearLinkListener {+        override fun onData(path: String, body: ByteArray) {+            if (path != WearLauncherProtocol.WATCH_STATE_PATH) return+            val watchState = runCatching {+                WearLauncherProtocol.json.decodeFromString<WearLauncherWatchState>(body.decodeToString())+            }.getOrNull() ?: return+            _state.update {+                it.copy(+                    lastWatchAppliedAtMillis = watchState.appliedGeneratedAtMillis+                        .takeIf { applied -> applied > 0L },+                )+            }+        }++        override fun onMessage(path: String, body: ByteArray) {+            if (path != WearLauncherProtocol.REQUEST_SYNC_PATH) return+            scope.launch { publishFavorites() }+        }+    }++    private val node = WearLinkNode(appContext, WearLauncherProtocol.CAPABILITY, listener)+    private var started = false++    fun start() {+        if (started) return+        started = true+        scope.launch {+            node.state.collect { linkState ->+                val present = linkState is WearLinkState.Connected+                val wasPresent = _state.value.companionPresent+                _state.update {+                    it.copy(companionPresent = wearLauncherCompanionPresent(if (present) 1 else 0))+                }+                if (present && !wasPresent) publishFavorites()+            }+        }+        node.start()+    }++    /** Layout changed (or manual sync): republish the hotseat snapshot. */+    fun syncNow() {+        scope.launch { publishFavorites() }+    }++    suspend fun publishFavorites() {+        val snapshot = withContext(Dispatchers.IO) { buildSnapshot() } ?: return+        val sent = node.putData(+            WearLauncherProtocol.FAVORITES_PATH,+            WearLauncherProtocol.json.encodeToString(snapshot).encodeToByteArray(),+        )+        if (sent) {+            _state.update {+                it.copy(+                    lastPublishedAtMillis = snapshot.generatedAtMillis,+                    lastPublishedFavoriteCount = snapshot.favorites.size,+                )+            }+        } else {+            Log.status(TAG, "publish favorites not delivered (no live WearLink session)")+        }+    }++    private suspend fun buildSnapshot() = runCatching {+        val items = LauncherRepository.get(appContext).getAll()+        val pm = appContext.packageManager+        val candidates = items+            .filter { it.container == ContainerRef.Hotseat }+            .filter { it.itemType == LauncherItemType.APPLICATION && !it.hidden }+            .sortedBy { it.rank }+            .mapNotNull { item ->+                val packageName = item.packageName ?: return@mapNotNull null+                val label = item.title ?: appLabel(pm, packageName)+                WearFavorite(+                    packageName = packageName,+                    className = item.className.orEmpty(),+                    label = label,+                    rank = item.rank,+                )+            }+        buildWearFavorites(candidates, System.currentTimeMillis())+    }.onFailure { Log.status(TAG, "build favorites failed: ${it.message}") }.getOrNull()++    private fun appLabel(pm: PackageManager, packageName: String): String = runCatching {+        pm.getApplicationLabel(pm.getApplicationInfo(packageName, 0)).toString()+    }.getOrDefault(packageName.substringAfterLast('.'))+}
launcher/src/test/java/com/vayunmathur/launcher/domain/WearLauncherProtocolTest.kt
diff --git a/launcher/src/test/java/com/vayunmathur/launcher/domain/WearLauncherProtocolTest.kt b/launcher/src/test/java/com/vayunmathur/launcher/domain/WearLauncherProtocolTest.ktnew file mode 100644index 0000000000..0832a458bd--- /dev/null+++ b/launcher/src/test/java/com/vayunmathur/launcher/domain/WearLauncherProtocolTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.launcher.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearLauncherProtocolTest {++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearFavoritesSnapshot(+            generatedAtMillis = 1_000L,+            favorites = listOf(+                WearFavorite("com.example.calendar", "com.example.calendar.Main", "Calendar", 0),+            ),+            truncated = false,+        )+        assertEquals(+            """{"generatedAtMillis":1000,"favorites":[{"packageName":"com.example.calendar",""" ++                """"className":"com.example.calendar.Main","label":"Calendar"}]}""",+            WearLauncherProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun snapshotRoundTrips() {+        val snapshot = WearFavoritesSnapshot(+            generatedAtMillis = 9L,+            favorites = listOf(WearFavorite("com.example.notes", "", "Notes", 1)),+            truncated = true,+        )+        val decoded = WearLauncherProtocol.json.decodeFromString<WearFavoritesSnapshot>(+            WearLauncherProtocol.json.encodeToString(snapshot),+        )+        assertEquals(snapshot, decoded)+    }++    @Test+    fun buildSortsByRankDedupesAndReRanks() {+        val snapshot = buildWearFavorites(+            candidates = listOf(+                WearFavorite("com.example.b", "", "B", 2),+                WearFavorite("com.example.a", "", "A", 1),+                WearFavorite("com.example.a", "", "A duplicate", 0),+                WearFavorite("", "", "blank", 0),+            ),+            generatedAtMillis = 5L,+        )+        // Duplicate keeps lowest rank (0), then re-ranked in rank order.+        assertEquals(listOf("com.example.a", "com.example.b"), snapshot.favorites.map { it.packageName })+        assertEquals(listOf(0, 1), snapshot.favorites.map { it.rank })+        assertEquals("A duplicate", snapshot.favorites[0].label)+        assertFalse(snapshot.truncated)+    }++    @Test+    fun buildCapsCountAndMarksTruncated() {+        val candidates = (0 until WearLauncherProtocol.MAX_FAVORITES + 3).map {+            WearFavorite("com.example.$it", "", "App $it", it)+        }+        val snapshot = buildWearFavorites(candidates, generatedAtMillis = 1L)+        assertEquals(WearLauncherProtocol.MAX_FAVORITES, snapshot.favorites.size)+        assertTrue(snapshot.truncated)+    }++    @Test+    fun companionPresenceIsCountBased() {+        assertFalse(wearLauncherCompanionPresent(0))+        assertTrue(wearLauncherCompanionPresent(1))+    }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex a4f460dab3..df5214d43b 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -161,6 +161,8 @@ include(":madeveloper") include(":shop") include(":share") include(":launcher")+include(":launcher:wear")+project(":launcher:wear").projectDir = file("launcher-wear") include(":cast") include(":cast:protocol") include(":cast:tv")