Modern Apps git

← Modern-Apps.git

wear: contacts companion (appstore/calendar swept by parents)

Commit
295837d8d9244d2a9231b0408d73fbfa13ad3f55
Author
Vayun Mathur <[email protected]>
When
2026-11-24 17:59 UTC (11 days ago)
Parents
3a5ccd9
New :contacts-wear module: same package and signing as
the phone Contacts app (Data Layer requirement, verified
via apksigner), watch feature declared, round-friendly
Wear Compose list/detail from a locally persisted
snapshot - offline-capable. Phone publishes over Data
Layer: favourites-first cap of 1,000 contacts (<=3
phones/emails each, field-truncated), <=50 KB chunks with
the manifest last and generation-checked reassembly on
the watch; the watch UI states 'N of M contacts (watch
limit)' honestly. Actions on the watch follow an honest
policy (on-watch only if a handler resolves, else phone
handoff, else no button). Phone Settings gains watch
presence + Sync now. Also in this shared-tree commit:
the parallel App Store/Calendar wear work where it
shares settings/build-logic (incl. the hyphenated-
namespace fix blocking all wear modules).

Verified: wear assemble + 8/8 wear tests; phone wear
protocol tests green.

Diff

appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex 43d2f96a71..522153d20d 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -149,6 +149,10 @@ dependencies {     // HttpURLConnection-based PlayHttpClient/AnonymousAuthRepository/PlayDownloader – no okhttp     implementation(libs.kotlinx.serialization.json)     implementation(libs.auroraoss.gplayapi)+    // Phone side of the Wear OS sync (sync/WearSyncManager): capability+    // discovery, catalog publish and APK streaming to :appstore:wear, which+    // shares this app's applicationId and signing certificate.+    implementation(libs.play.services.wearable)      // --- Accrescent app source -------------------------------------------------------     // gRPC (appstore-api.accrescent.app) over grpc-okhttp, with protobuf-lite messages and
appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt b/appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.ktnew file mode 100644index 0000000000..93539d848e--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt@@ -0,0 +1,296 @@+package com.vayunmathur.appstore.domain++import java.io.File+import java.io.InputStream+import java.security.MessageDigest+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS App Store.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only+ * connects apps that share a package name and signing certificate, but Gradle+ * cannot let one application module depend on another, so the wear module+ * (`:appstore:wear`, applicationId `com.vayunmathur.appstore`) carries a+ * byte-identical copy of this file under `com.vayunmathur.appstore.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.+ *+ * Transport split:+ * - Capability advertisement (res string-array `android_wear_capabilities` on+ *   the watch) tells the phone the wear store is present at all.+ * - DataClient carries the small, durable state: [CATALOG_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. DataItems survive disconnects and+ *   reconcile the two sides when they meet again.+ * - MessageClient carries ephemeral commands/results ([OFFER_PATH],+ *   [INSTALL_RESULT_PATH], [REQUEST_STATE_PATH]).+ * - ChannelClient ([apkChannelPath]) streams the APK itself: DataClient assets+ *   are size-capped and base64-inflated in transit, a channel is a raw stream.+ *+ * Install honesty: nothing here can install silently. The watch verifies the+ * stream against [ApkOffer.sha256], then a person on the watch taps Install+ * and confirms the system PackageInstaller prompt. States say exactly that —+ * there is no state that claims an install the OS has not confirmed.+ */+object WearSyncProtocol {+    /** Capability the wear store advertises; the phone looks for it on connected nodes. */+    const val CAPABILITY = "appstore_wear_store"++    /** DataClient path (phone -> watch): the [WearCatalog] JSON snapshot. */+    const val CATALOG_PATH = "/appstore/catalog"++    /** DataClient path (watch -> phone): the [WatchState] JSON snapshot. */+    const val WATCH_STATE_PATH = "/appstore/watch-state"++    /** MessageClient path (phone -> watch): an [ApkOffer] precedes every channel. */+    const val OFFER_PATH = "/appstore/apk-offer"++    /** MessageClient path (watch -> phone): an [InstallResult] after the OS answers. */+    const val INSTALL_RESULT_PATH = "/appstore/install-result"++    /** MessageClient path (phone -> watch): ask the watch to republish [WATCH_STATE_PATH]. */+    const val REQUEST_STATE_PATH = "/appstore/request-state"++    /**+     * MessageClient path (phone -> watch): ask the watch to surface its Install+     * action for the package named in the payload. This only *asks* — a person+     * on the watch still taps Install and confirms the system prompt.+     */+    const val REQUEST_INSTALL_PATH = "/appstore/request-install"++    /** ChannelClient path prefix (phone -> watch); the package name is the last segment. */+    const val APK_CHANNEL_PREFIX = "/appstore/apk/"++    /** Largest single APK this slice will stream (a watch has little storage to spare). */+    const val MAX_APK_BYTES = 200L * 1024 * 1024++    /** Channel path streaming [packageName]'s APK. */+    fun apkChannelPath(packageName: String): String = APK_CHANNEL_PREFIX + packageName++    /** The package a channel path streams, or null when [path] is not an APK channel. */+    fun packageFromChannelPath(path: String): String? =+        path.takeIf { it.startsWith(APK_CHANNEL_PREFIX) }+            ?.removePrefix(APK_CHANNEL_PREFIX)+            ?.takeIf { it.isNotBlank() && '/' !in it }++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One catalog row the phone offers the watch. Mirrors the phone catalog, trimmed to watch size. */+@Serializable+data class WearCatalogApp(+    val packageName: String,+    val name: String,+    val versionName: String? = null,+    val versionCode: Long = 0L,+    val sizeBytes: Long = 0L,+)++/** The phone's catalog snapshot for the watch ([WearSyncProtocol.CATALOG_PATH]). */+@Serializable+data class WearCatalog(val apps: List<WearCatalogApp> = emptyList())++/**+ * Metadata announced over MessageClient immediately before an APK channel opens.+ * The watch refuses bytes that do not match [sizeBytes]/[sha256] — the channel+ * itself carries no metadata, so this offer is the integrity contract.+ */+@Serializable+data class ApkOffer(+    val packageName: String,+    val name: String,+    val versionCode: Long,+    val sizeBytes: Long,+    /** Lowercase hex SHA-256 of the exact bytes about to be streamed. */+    val sha256: String,+)++/** Per-app truth as the watch knows it, published in [WatchState]. */+@Serializable+data class WatchAppEntry(+    val packageName: String,+    /** The APK for this version is fully received and hash-verified on the watch. */+    val downloadedVersionCode: Long = 0L,+    /** The version the watch's PackageManager reports installed, 0 when absent. */+    val installedVersionCode: Long = 0L,+    /** True while a verified APK sits waiting for the user to tap Install. */+    val installPending: Boolean = false,+)++/** The watch's downloaded/installed snapshot ([WearSyncProtocol.WATCH_STATE_PATH]). */+@Serializable+data class WatchState(val apps: List<WatchAppEntry> = emptyList())++/** The OS install verdict, sent watch -> phone once PackageInstaller answers. */+@Serializable+data class InstallResult(+    val packageName: String,+    val versionCode: Long,+    val installed: Boolean,+    /** Plain-language failure from the OS/status, empty on success. */+    val message: String = "",+)++/** Per-app sync state on the phone, per package. */+enum class PhoneWearState {+    /** No watch, or the watch has never been offered this app. */+    NOT_DOWNLOADED,+    /** The APK channel is open and bytes are moving. */+    SENDING,+    /** Verified APK is on the watch; nobody has asked to install it yet. */+    ON_WATCH,+    /** Install was requested; the watch still owes a user tap + OS confirmation. */+    INSTALL_REQUESTED,+    /** The watch's PackageManager confirms this (or a newer) version installed. */+    INSTALLED,+    /** The last send/verify/install step failed; see the message kept beside the state. */+    FAILED,+}++/** Events that move the phone-side per-app state. */+sealed interface PhoneWearEvent {+    data object SendStarted : PhoneWearEvent+    data class SendFinished(val success: Boolean) : PhoneWearEvent+    data object InstallRequested : PhoneWearEvent+    data class ResultReceived(val result: InstallResult) : PhoneWearEvent+    data class Reconciled(val entry: WatchAppEntry?, val catalogVersionCode: Long) : PhoneWearEvent+    data object WatchGone : PhoneWearEvent+}++/** Pure phone-side state machine; the Android transport only feeds it events. */+object PhoneWearMachine {+    fun reduce(state: PhoneWearState, event: PhoneWearEvent): PhoneWearState = when (event) {+        PhoneWearEvent.SendStarted -> PhoneWearState.SENDING+        is PhoneWearEvent.SendFinished ->+            if (event.success) PhoneWearState.ON_WATCH else PhoneWearState.FAILED+        PhoneWearEvent.InstallRequested ->+            if (state == PhoneWearState.ON_WATCH) PhoneWearState.INSTALL_REQUESTED else state+        is PhoneWearEvent.ResultReceived ->+            if (event.result.installed) PhoneWearState.INSTALLED else PhoneWearState.FAILED+        is PhoneWearEvent.Reconciled -> reconcile(state, event.entry, event.catalogVersionCode)+        PhoneWearEvent.WatchGone ->+            if (state == PhoneWearState.SENDING) PhoneWearState.FAILED else state+    }++    /**+     * Fold the watch's published truth into the local state. A live transfer+     * ([PhoneWearState.SENDING]) is never overwritten by a stale snapshot; an+     * install the watch confirms wins over everything else.+     */+    private fun reconcile(+        state: PhoneWearState,+        entry: WatchAppEntry?,+        catalogVersionCode: Long,+    ): PhoneWearState {+        if (state == PhoneWearState.SENDING) return state+        if (entry == null) {+            return if (state == PhoneWearState.INSTALLED) PhoneWearState.NOT_DOWNLOADED else state+        }+        return when {+            entry.installedVersionCode >= catalogVersionCode && catalogVersionCode > 0 ->+                PhoneWearState.INSTALLED+            entry.installPending -> PhoneWearState.INSTALL_REQUESTED+            entry.downloadedVersionCode >= catalogVersionCode && catalogVersionCode > 0 ->+                PhoneWearState.ON_WATCH+            entry.downloadedVersionCode > 0 -> PhoneWearState.ON_WATCH+            else -> state+        }+    }+}++/** Per-app state on the watch, per package. */+enum class WatchAppPhase {+    /** Offered in the catalog; no bytes yet. */+    LISTED,+    /** Channel open, bytes arriving. */+    RECEIVING,+    /** Stream arrived but failed the size/hash contract; bytes deleted. */+    REJECTED,+    /** Verified APK on disk, waiting for the user to tap Install. */+    READY_TO_INSTALL,+    /** PackageInstaller session committed; waiting for the OS verdict. */+    INSTALLING,+    /** PackageManager confirms the package installed. */+    INSTALLED,+    /** Install was attempted and the OS (or user) said no. */+    INSTALL_FAILED,+}++/** Events that move the watch-side per-app state. */+sealed interface WatchAppEvent {+    data object ReceiveStarted : WatchAppEvent+    data class ReceiveFinished(val verified: Boolean) : WatchAppEvent+    data object InstallTapped : WatchAppEvent+    data class InstallFinished(val installed: Boolean) : WatchAppEvent+    data object BecameInstalled : WatchAppEvent+}++/** Pure watch-side state machine; services/installers only feed it events. */+object WatchAppMachine {+    fun reduce(phase: WatchAppPhase, event: WatchAppEvent): WatchAppPhase = when (event) {+        WatchAppEvent.ReceiveStarted -> WatchAppPhase.RECEIVING+        is WatchAppEvent.ReceiveFinished ->+            if (event.verified) WatchAppPhase.READY_TO_INSTALL else WatchAppPhase.REJECTED+        WatchAppEvent.InstallTapped ->+            if (phase == WatchAppPhase.READY_TO_INSTALL ||+                phase == WatchAppPhase.INSTALL_FAILED+            ) {+                WatchAppPhase.INSTALLING+            } else {+                phase+            }+        is WatchAppEvent.InstallFinished ->+            if (event.installed) WatchAppPhase.INSTALLED else WatchAppPhase.INSTALL_FAILED+        WatchAppEvent.BecameInstalled -> WatchAppPhase.INSTALLED+    }+}++/**+ * Whether the phone can offer this catalog row to the watch at all.+ *+ * The catalog cannot prove a phone UI will be usable on a watch, and this does+ * not pretend otherwise: the gate is purely technical — one streamable APK+ * (split sets need a multi-file session protocol this slice does not carry)+ * with known bytes to hash. A truly incompatible APK is refused by the watch's+ * PackageManager at install time and that verdict is reported, not hidden.+ */+fun watchSendEligibility(+    apkUrl: String?,+    splitCount: Int,+    sizeBytes: Long,+): String? = when {+    apkUrl.isNullOrBlank() -> "this source published no downloadable APK"+    splitCount > 0 -> "split APK sets cannot be sent to the watch yet"+    sizeBytes > WearSyncProtocol.MAX_APK_BYTES -> "too large for the watch"+    else -> null+}++/** Streaming SHA-256 helpers: the offer/watch verification contract. */+object ApkHash {+    private const val BUFFER_SIZE = 64 * 1024++    /** Lowercase hex SHA-256 of [input]'s contents (consumed, not closed). */+    fun sha256Hex(input: InputStream): String {+        val digest = MessageDigest.getInstance("SHA-256")+        val buffer = ByteArray(BUFFER_SIZE)+        while (true) {+            val read = input.read(buffer)+            if (read < 0) break+            if (read > 0) digest.update(buffer, 0, read)+        }+        return digest.digest().joinToString("") { "%02x".format(it) }+    }++    /** Lowercase hex SHA-256 of [file]. */+    fun sha256Hex(file: File): String = file.inputStream().buffered().use { sha256Hex(it) }++    /**+     * True when [file] is exactly [offer]'s bytes. A mismatch (or a truncated+     * stream, which the size check catches first) means the bytes are refused:+     * callers delete the file and never hand it to PackageInstaller.+     */+    fun verify(file: File, offer: ApkOffer): Boolean =+        file.length() == offer.sizeBytes && sha256Hex(file) == offer.sha256.lowercase()+}
appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreUiContract.ktindex 8b76e067db..a006a1183e 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreUiContract.kt@@ -105,6 +105,15 @@ data class AppDetailUiState(     val installedIcon: Drawable? = null,     /** True while richer details are being fetched over the network. */     val isLoadingDetails: Boolean = false,+    /** True when a watch running the Wear OS App Store is connected. */+    val watchConnected: Boolean = false,+    /** This app's sync state on the watch; NOT_DOWNLOADED when unknown/absent. */+    val wearState: com.vayunmathur.appstore.domain.PhoneWearState =+        com.vayunmathur.appstore.domain.PhoneWearState.NOT_DOWNLOADED,+    /** Why this app cannot be sent to the watch, or null when it can. */+    val wearIneligibleReason: String? = null,+    /** Plain-language detail for the last wear send/install result, where any. */+    val wearMessage: String? = null, ) {     val isInstalled: Boolean get() = installedInfo != null @@ -206,6 +215,10 @@ interface AppDetailActions : AppActions {     fun openInBrowser(url: String) {}     fun shareApp(app: UnifiedApp) {}     fun dismissInstallFailure(packageName: String) {}+    /** Stream this app's APK to the connected watch (user confirms install there). */+    fun sendToWatch(app: UnifiedApp) {}+    /** Ask the watch to surface its Install action; the tap still happens on the watch. */+    fun requestWatchInstall(packageName: String) {}      /** Provides a no-op AppDetailActions for previews and defaults. */     companion object {
appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreViewModel.ktindex 6c8329b712..70c38272a5 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/platform/AppStoreViewModel.kt@@ -39,7 +39,9 @@ import com.vayunmathur.appstore.data.priority import com.vayunmathur.appstore.data.searchCandidate import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.appstore.domain.PhoneWearState import com.vayunmathur.appstore.domain.SearchRanking+import com.vayunmathur.appstore.sync.WearSyncManager import com.vayunmathur.library.util.AppMessages import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -79,6 +81,9 @@ class AppStoreViewModel(     internal val installer =         InstallCoordinator(context, db, play, accrescent, viewModelScope) { ownSigningCertificates } +    /** Phone side of the Wear OS sync; degrades to "no watch" when unavailable. */+    internal val wearSync = WearSyncManager(context, viewModelScope)+     /** Third-party APKs are off by default: the periodic check may also download and install updates unattended. */     val autoInstallUpdates: StateFlow<Boolean> = settings.autoInstallUpdates @@ -327,12 +332,30 @@ class AppStoreViewModel(         )     }.stateIn(viewModelScope, SharingStarted.Eagerly, SearchUiState()) +    /** Wear-sync snapshot for the detail screen, kept as one flow for the combine below. */+    private data class WearUi(+        val connected: Boolean,+        val states: Map<String, PhoneWearState>,+        val messages: Map<String, String>,+    )++    private val wearUi: StateFlow<WearUi> = combine(+        wearSync.watchConnected,+        wearSync.states,+        wearSync.messages,+    ) { connected, states, messages -> WearUi(connected, states, messages) }+        .stateIn(+            viewModelScope, SharingStarted.Eagerly,+            WearUi(false, emptyMap(), emptyMap()),+        )+     val detail: StateFlow<AppDetailUiState> = combine(         detailAppFlow,         isLoadingDetailsFlow,         chrome,         installer.verification,-    ) { app, loading, rows, verification ->+        wearUi,+    ) { app, loading, rows, verification, wear ->         val pkg = app?.packageName         AppDetailUiState(             app = app,@@ -341,6 +364,10 @@ class AppStoreViewModel(             stage = rows.stages[pkg],             installedIcon = rows.icons[pkg],             isLoadingDetails = loading,+            watchConnected = wear.connected,+            wearState = pkg?.let { wear.states[it] } ?: PhoneWearState.NOT_DOWNLOADED,+            wearIneligibleReason = app?.let { wearSync.eligibility(it) },+            wearMessage = pkg?.let { wear.messages[it] },         )     }.stateIn(viewModelScope, SharingStarted.Eagerly, AppDetailUiState()) @@ -415,6 +442,16 @@ class AppStoreViewModel(     // --- Lifecycle -------------------------------------------------------------------      init {+        // Wear sync is best-effort: no watch (or no wear store on it) simply+        // leaves watchConnected false and the detail screen says so.+        wearSync.start()+        viewModelScope.launch {+            sections.collect { homeSections ->+                wearSync.syncCatalog(+                    homeSections.flatMap { it.apps }.distinctBy { it.packageName },+                )+            }+        }         viewModelScope.launch {             // Crash-orphaned APKs first: a dead install attempt's staged files are             // garbage, and the 24h age gate keeps this from racing anything@@ -607,6 +644,11 @@ class AppStoreViewModel(      override fun shareApp(app: UnifiedApp) = shareAppImpl(app) +    override fun sendToWatch(app: UnifiedApp) = wearSync.sendToWatch(app)++    override fun requestWatchInstall(packageName: String) =+        wearSync.requestInstall(packageName)+     // --- Updates ----------------------------------------------------------------------     // Bodies live in AppStoreUpdateOps.kt; these overrides keep interface conformance. 
appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.kt b/appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.ktnew file mode 100644index 0000000000..01c249d6d7--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.kt@@ -0,0 +1,368 @@+package com.vayunmathur.appstore.sync++import android.content.Context+import com.google.android.gms.tasks.Task+import com.google.android.gms.wearable.CapabilityClient+import com.google.android.gms.wearable.CapabilityInfo+import com.google.android.gms.wearable.DataClient+import com.google.android.gms.wearable.DataEvent+import com.google.android.gms.wearable.DataEventBuffer+import com.google.android.gms.wearable.DataMapItem+import com.google.android.gms.wearable.MessageClient+import com.google.android.gms.wearable.MessageEvent+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.domain.ApkHash+import com.vayunmathur.appstore.domain.ApkOffer+import com.vayunmathur.appstore.domain.InstallResult+import com.vayunmathur.appstore.domain.PhoneWearEvent+import com.vayunmathur.appstore.domain.PhoneWearMachine+import com.vayunmathur.appstore.domain.PhoneWearState+import com.vayunmathur.appstore.domain.WatchState+import com.vayunmathur.appstore.domain.WearCatalog+import com.vayunmathur.appstore.domain.WearCatalogApp+import com.vayunmathur.appstore.domain.WearSyncProtocol+import com.vayunmathur.appstore.domain.watchSendEligibility+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.network.NetworkClient+import java.io.File+import java.io.IOException+import java.net.HttpURLConnection+import java.net.URL+import javax.net.ssl.HttpsURLConnection+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+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.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString++/** Await a Play services [Task] without taking a coroutines-play-services dependency. */+private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->+    addOnSuccessListener { cont.resume(it) }+    addOnFailureListener { cont.resumeWithException(it) }+}++/**+ * Phone side of the wear sync: capability discovery, catalog publish, APK+ * streaming and per-app state reconciliation.+ *+ * Every Wearable call is wrapped so that "no Play services / no watch / watch+ * without the wear store" is a normal state ([watchConnected] = false), never+ * a crash. The Data Layer only connects the two stores because they share the+ * package name `com.vayunmathur.appstore` and a signing certificate — dev+ * builds both use the debug key, release builds both use the same release key.+ */+class WearSyncManager(+    private val context: Context,+    private val scope: CoroutineScope,+) : CapabilityClient.OnCapabilityChangedListener,+    DataClient.OnDataChangedListener,+    MessageClient.OnMessageReceivedListener {++    /** Holds constants for the wear sync transport. */+    companion object {+        private const val TAG = "WearSyncManager"+        private const val KEY_JSON = "json"+        private const val KEY_SENT_AT = "sent_at"+    }++    private val _watchConnected = MutableStateFlow(false)++    /** True only when a reachable node advertises the wear store's capability. */+    val watchConnected: StateFlow<Boolean> = _watchConnected.asStateFlow()++    private val _states = MutableStateFlow<Map<String, PhoneWearState>>(emptyMap())++    /** Per-package sync state, keyed by package name. */+    val states: StateFlow<Map<String, PhoneWearState>> = _states.asStateFlow()++    private val _messages = MutableStateFlow<Map<String, String>>(emptyMap())++    /** Per-package plain-language detail for the last failure/result, where any. */+    val messages: StateFlow<Map<String, String>> = _messages.asStateFlow()++    @Volatile+    private var watchNodeId: String? = null++    private var started = false++    /** Begin capability/data/message listening; no-op when already started or unavailable. */+    fun start() {+        if (started) return+        started = true+        runCatching {+            Wearable.getCapabilityClient(context).addListener(this, WearSyncProtocol.CAPABILITY)+            Wearable.getDataClient(context).addListener(this)+            Wearable.getMessageClient(context).addListener(this)+        }.onFailure { Log.status(TAG, "Wearable listeners unavailable: ${it.message}") }+        scope.launch { refreshCapability() }+    }++    override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) {+        updateNodes(capabilityInfo.nodes.map { it.id })+    }++    override fun onDataChanged(dataEvents: DataEventBuffer) {+        for (event in dataEvents) {+            if (event.type != DataEvent.TYPE_CHANGED) continue+            val item = event.dataItem+            if (item.uri.path != WearSyncProtocol.WATCH_STATE_PATH) continue+            val json = runCatching {+                DataMapItem.fromDataItem(item).dataMap.getString(KEY_JSON)+            }.getOrNull() ?: continue+            val watchState = runCatching {+                WearSyncProtocol.json.decodeFromString<WatchState>(json)+            }.getOrNull() ?: continue+            reconcile(watchState)+        }+    }++    override fun onMessageReceived(messageEvent: MessageEvent) {+        if (messageEvent.path != WearSyncProtocol.INSTALL_RESULT_PATH) return+        val result = runCatching {+            WearSyncProtocol.json.decodeFromString<InstallResult>(+                messageEvent.data.decodeToString(),+            )+        }.getOrNull() ?: return+        applyEvent(+            result.packageName,+            PhoneWearEvent.ResultReceived(result),+            message = result.message.takeIf { it.isNotBlank() },+        )+    }++    /** Publish the watch-eligible catalog snapshot so the watch can list it standalone. */+    fun syncCatalog(apps: List<UnifiedApp>) {+        noteCatalogVersions(apps)+        val catalog = WearCatalog(+            apps.filter { watchSendEligibility(it.apkUrl, it.splitFiles.size, it.sizeBytes) == null }+                .map {+                    WearCatalogApp(+                        packageName = it.packageName,+                        name = it.name,+                        versionName = it.versionName,+                        versionCode = it.versionCode,+                        sizeBytes = it.sizeBytes,+                    )+                },+        )+        scope.launch(Dispatchers.IO) {+            runCatching {+                val request = PutDataMapRequest.create(WearSyncProtocol.CATALOG_PATH).apply {+                    dataMap.putString(+                        KEY_JSON,+                        WearSyncProtocol.json.encodeToString(catalog),+                    )+                    dataMap.putLong(KEY_SENT_AT, System.currentTimeMillis())+                }.asPutDataRequest().setUrgent()+                Wearable.getDataClient(context).putDataItem(request).awaitTask()+            }.onFailure { Log.status(TAG, "catalog publish failed: ${it.message}") }+        }+    }++    /** Why [app] cannot be sent, or null when it can. Exact mirror of the catalog filter. */+    fun eligibility(app: UnifiedApp): String? =+        watchSendEligibility(app.apkUrl, app.splitFiles.size, app.sizeBytes)++    /**+     * Download [app]'s APK (once, into the wear staging dir), hash it, announce+     * the [ApkOffer], then stream the raw bytes over a channel. The watch does+     * the verifying; this side reports SENDING -> ON_WATCH/FAILED honestly.+     */+    fun sendToWatch(app: UnifiedApp) {+        val nodeId = watchNodeId+        if (nodeId == null) {+            applyEvent(+                app.packageName, PhoneWearEvent.WatchGone, "no watch with the Wear OS App Store is connected",+            )+            return+        }+        eligibility(app)?.let {+            _messages.update { m -> m + (app.packageName to it) }+            return+        }+        applyEvent(app.packageName, PhoneWearEvent.SendStarted)+        scope.launch(Dispatchers.IO) {+            try {+                val file = stageApk(app)+                val offer = ApkOffer(+                    packageName = app.packageName,+                    name = app.name,+                    versionCode = app.versionCode,+                    sizeBytes = file.length(),+                    sha256 = ApkHash.sha256Hex(file),+                )+                Wearable.getMessageClient(context).sendMessage(+                    nodeId, WearSyncProtocol.OFFER_PATH,+                    WearSyncProtocol.json.encodeToString(offer).encodeToByteArray(),+                ).awaitTask()+                val channelClient = Wearable.getChannelClient(context)+                val channel = channelClient+                    .openChannel(nodeId, WearSyncProtocol.apkChannelPath(app.packageName))+                    .awaitTask()+                try {+                    channelClient.getOutputStream(channel).awaitTask().use { out ->+                        file.inputStream().buffered().use { it.copyTo(out) }+                    }+                } finally {+                    runCatching { channelClient.close(channel).awaitTask() }+                }+                applyEvent(app.packageName, PhoneWearEvent.SendFinished(true))+                requestWatchState(nodeId)+            } catch (expected: Exception) {+                Log.error(TAG, "send ${app.packageName} failed", expected)+                applyEvent(+                    app.packageName,+                    PhoneWearEvent.SendFinished(false),+                    expected.message ?: "could not send to the watch",+                )+            }+        }+    }++    /**+     * Ask the watch to surface its Install action for [packageName]. This only+     * asks: the person on the watch taps Install and confirms the system prompt.+     */+    fun requestInstall(packageName: String) {+        val nodeId = watchNodeId ?: return+        applyEvent(packageName, PhoneWearEvent.InstallRequested)+        scope.launch(Dispatchers.IO) {+            runCatching {+                Wearable.getMessageClient(context).sendMessage(+                    nodeId, WearSyncProtocol.REQUEST_INSTALL_PATH,+                    packageName.encodeToByteArray(),+                ).awaitTask()+            }.onFailure { Log.status(TAG, "request-install failed: ${it.message}") }+        }+    }++    private suspend fun stageApk(app: UnifiedApp): File = withContext(Dispatchers.IO) {+        val dir = File(context.cacheDir, "wear").apply { mkdirs() }+        val target = File(dir, "${app.packageName}.apk")+        val fresh = target.exists() && target.length() > 0 &&+            (app.sizeBytes <= 0 || target.length() == app.sizeBytes) &&+            (app.apkSha256 == null || ApkHash.sha256Hex(target) == app.apkSha256.lowercase())+        if (!fresh) download(app.apkUrl!!, target)+        if (app.apkSha256 != null &&+            !ApkHash.sha256Hex(target).equals(app.apkSha256, ignoreCase = true)+        ) {+            target.delete()+            throw IOException("downloaded APK does not match the catalog hash")+        }+        target+    }++    private fun download(url: String, target: File) {+        val connection = URL(url).openConnection()+        val sslSocketFactory = NetworkClient.defaultSslSocketFactory+        if (sslSocketFactory != null && connection is HttpsURLConnection) {+            connection.sslSocketFactory = sslSocketFactory+        }+        val conn = (connection as HttpURLConnection).apply {+            connectTimeout = 30_000+            readTimeout = 120_000+            instanceFollowRedirects = true+        }+        try {+            val code = conn.responseCode+            if (code !in 200..299) throw IOException("the server returned HTTP $code")+            conn.inputStream.use { input ->+                target.outputStream().use { input.copyTo(it) }+            }+        } finally {+            conn.disconnect()+        }+    }++    private fun reconcile(watchState: WatchState) {+        val byPackage = watchState.apps.associateBy { it.packageName }+        _states.update { current ->+            current.mapValues { (pkg, state) ->+                PhoneWearMachine.reduce(+                    state,+                    PhoneWearEvent.Reconciled(byPackage[pkg], catalogVersionOf(pkg)),+                )+            }+        }+        // Packages the watch knows but this side has never tracked still reconcile.+        _states.update { current ->+            var next = current+            for (entry in watchState.apps) {+                if (entry.packageName !in next) {+                    next = next + (entry.packageName to PhoneWearMachine.reduce(+                        PhoneWearState.NOT_DOWNLOADED,+                        PhoneWearEvent.Reconciled(entry, entry.downloadedVersionCode),+                    ))+                }+            }+            next+        }+    }++    private val catalogVersions = MutableStateFlow<Map<String, Long>>(emptyMap())++    private fun catalogVersionOf(packageName: String): Long =+        catalogVersions.value[packageName] ?: 0L++    private suspend fun refreshCapability() {+        runCatching {+            val capability = Wearable.getCapabilityClient(context)+                .getCapability(WearSyncProtocol.CAPABILITY, CapabilityClient.FILTER_REACHABLE)+                .awaitTask()+            updateNodes(capability.nodes.map { it.id })+        }.onFailure {+            _watchConnected.value = false+            Log.status(TAG, "capability check unavailable: ${it.message}")+        }+    }++    private fun updateNodes(nodeIds: List<String>) {+        watchNodeId = nodeIds.firstOrNull()+        _watchConnected.value = nodeIds.isNotEmpty()+        if (nodeIds.isEmpty()) {+            _states.update { current ->+                current.mapValues { (_, state) ->+                    PhoneWearMachine.reduce(state, PhoneWearEvent.WatchGone)+                }+            }+        }+    }++    private fun requestWatchState(nodeId: String) {+        scope.launch(Dispatchers.IO) {+            runCatching {+                Wearable.getMessageClient(context).sendMessage(+                    nodeId, WearSyncProtocol.REQUEST_STATE_PATH, byteArrayOf(),+                ).awaitTask()+            }+        }+    }++    private fun applyEvent(+        packageName: String,+        event: PhoneWearEvent,+        message: String? = null,+    ) {+        _states.update { current ->+            val old = current[packageName] ?: PhoneWearState.NOT_DOWNLOADED+            current + (packageName to PhoneWearMachine.reduce(old, event))+        }+        if (message != null) {+            _messages.update { it + (packageName to message) }+        }+    }++    /** Remember catalog versions so reconciliation can compare like with like. */+    fun noteCatalogVersions(apps: List<UnifiedApp>) {+        catalogVersions.value = apps.associate { it.packageName to it.versionCode }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailScreen.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailScreen.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailScreen.ktindex 7fc7a412a9..20b28e834d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailScreen.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailScreen.kt@@ -71,6 +71,7 @@ fun AppDetailScreen(         ) {             AppDetailHeader(state)             AppInstallActions(state, actions, onUninstall = { showUninstallConfirm = true })+            AppWearSection(state, actions)             if (app.screenshots.isNotEmpty()) {                 AppScreenshotStrip(app.screenshots, app.name, onOpen = onOpenScreenshot)             }
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.ktindex 3b80f1b7a1..2b309b7f20 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailSections.kt@@ -112,6 +112,71 @@ internal fun AppInstallActions(     } } +/**+ * The watch half of this listing: whether a watch is there, whether this app+ * can be sent, and where the last send got to. Installs are never silent —+ * every state here says the confirmation happens on the watch.+ */+@Composable+internal fun AppWearSection(+    state: AppDetailUiState,+    actions: AppDetailActions,+) {+    val app = state.app ?: return+    Card(+        modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp),+    ) {+        Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {+            Text(+                stringResource(R.string.wear_title),+                style = MaterialTheme.typography.titleSmall,+                fontWeight = FontWeight.SemiBold,+            )+            when {+                !state.watchConnected -> Text(+                    stringResource(R.string.wear_no_watch),+                    style = MaterialTheme.typography.bodySmall,+                )+                state.wearIneligibleReason != null -> Text(+                    state.wearIneligibleReason,+                    style = MaterialTheme.typography.bodySmall,+                )+                else -> {+                    Text(+                        when (state.wearState) {+                            com.vayunmathur.appstore.domain.PhoneWearState.SENDING ->+                                stringResource(R.string.wear_sending)+                            com.vayunmathur.appstore.domain.PhoneWearState.ON_WATCH ->+                                stringResource(R.string.wear_on_watch)+                            com.vayunmathur.appstore.domain.PhoneWearState.INSTALL_REQUESTED ->+                                stringResource(R.string.wear_install_requested)+                            com.vayunmathur.appstore.domain.PhoneWearState.INSTALLED ->+                                stringResource(R.string.wear_installed)+                            com.vayunmathur.appstore.domain.PhoneWearState.FAILED ->+                                stringResource(+                                    R.string.wear_failed,+                                    state.wearMessage ?: "",+                                )+                            else -> stringResource(R.string.wear_not_sent)+                        },+                        style = MaterialTheme.typography.bodySmall,+                    )+                    when (state.wearState) {+                        com.vayunmathur.appstore.domain.PhoneWearState.ON_WATCH ->+                            FilledTonalButton(+                                onClick = { actions.requestWatchInstall(app.packageName) },+                            ) { Text(stringResource(R.string.wear_request_install)) }+                        com.vayunmathur.appstore.domain.PhoneWearState.SENDING -> Unit+                        else -> FilledTonalButton(+                            onClick = { actions.sendToWatch(app) },+                        ) { Text(stringResource(R.string.wear_send)) }+                    }+                }+            }+        }+    }+}+ /**  * What can be checked about this app's download, and what the last install proved.  *
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex c54780c02d..e3f12a0411 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -132,6 +132,18 @@     <string name="action_install">Install</string>     <string name="action_update">Update</string>     <string name="action_dismiss">Dismiss</string>+    <!-- Wear OS sync (detail screen). Installs are never silent: the watch+         always asks its wearer to confirm. -->+    <string name="wear_title">On your watch</string>+    <string name="wear_no_watch">No watch with the Wear OS App Store is connected. Install it on a watch once, then apps can be sent from here.</string>+    <string name="wear_send">Send to watch</string>+    <string name="wear_sending">Sending to watch…</string>+    <string name="wear_on_watch">On the watch — open the App Store there to install it.</string>+    <string name="wear_install_requested">Install requested — tap Install on the watch and confirm there.</string>+    <string name="wear_installed">Installed on the watch.</string>+    <string name="wear_request_install">Ask watch to install</string>+    <string name="wear_not_sent">Not sent to the watch yet.</string>+    <string name="wear_failed">Watch sync failed: %1$s</string>     <string name="action_read_more">Read more</string>     <string name="action_show_less">Show less</string>     <string name="stage_preparing">Preparing…</string>
appstore/src/test/java/com/vayunmathur/appstore/domain/WearSyncProtocolTest.kt
diff --git a/appstore/src/test/java/com/vayunmathur/appstore/domain/WearSyncProtocolTest.kt b/appstore/src/test/java/com/vayunmathur/appstore/domain/WearSyncProtocolTest.ktnew file mode 100644index 0000000000..5671fcfe72--- /dev/null+++ b/appstore/src/test/java/com/vayunmathur/appstore/domain/WearSyncProtocolTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.appstore.domain++import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearSyncProtocolTest {++    @Test+    fun `golden wire json is stable across both apps`() {+        // The wear module pins these exact strings in its own copy of this test:+        // a one-sided protocol edit breaks one side or the other, never silently both.+        val catalog = WearCatalog(listOf(WearCatalogApp("com.example.a", "A", "1.0", 7L, 123L)))+        assertEquals(+            """{"apps":[{"packageName":"com.example.a","name":"A","versionName":"1.0","versionCode":7,"sizeBytes":123}]}""",+            WearSyncProtocol.json.encodeToString(catalog),+        )+        val offer = ApkOffer("com.example.a", "A", 7L, 123L, "ab12")+        assertEquals(+            """{"packageName":"com.example.a","name":"A","versionCode":7,"sizeBytes":123,"sha256":"ab12"}""",+            WearSyncProtocol.json.encodeToString(offer),+        )+        assertEquals("/appstore/apk/com.example.a", WearSyncProtocol.apkChannelPath("com.example.a"))+        assertEquals("com.example.a", WearSyncProtocol.packageFromChannelPath("/appstore/apk/com.example.a"))+        assertNull(WearSyncProtocol.packageFromChannelPath("/appstore/catalog"))+    }++    @Test+    fun `phone machine walks send to installed and never fakes a step`() {+        var state = PhoneWearState.NOT_DOWNLOADED+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.SendStarted)+        assertEquals(PhoneWearState.SENDING, state)+        // Install cannot be requested before the bytes are on the watch.+        assertEquals(+            PhoneWearState.SENDING,+            PhoneWearMachine.reduce(state, PhoneWearEvent.InstallRequested),+        )+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.SendFinished(true))+        assertEquals(PhoneWearState.ON_WATCH, state)+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.InstallRequested)+        assertEquals(PhoneWearState.INSTALL_REQUESTED, state)+        state = PhoneWearMachine.reduce(+            state,+            PhoneWearEvent.ResultReceived(InstallResult("com.example.a", 7L, installed = false, "user cancelled")),+        )+        assertEquals(PhoneWearState.FAILED, state)+    }++    @Test+    fun `reconcile trusts the watch snapshot except during a live send`() {+        val entry = WatchAppEntry("com.example.a", downloadedVersionCode = 7L, installedVersionCode = 7L)+        assertEquals(+            PhoneWearState.INSTALLED,+            PhoneWearMachine.reduce(+                PhoneWearState.ON_WATCH,+                PhoneWearEvent.Reconciled(entry, catalogVersionCode = 7L),+            ),+        )+        assertEquals(+            PhoneWearState.SENDING,+            PhoneWearMachine.reduce(+                PhoneWearState.SENDING,+                PhoneWearEvent.Reconciled(entry, catalogVersionCode = 7L),+            ),+        )+        assertEquals(+            PhoneWearState.FAILED,+            PhoneWearMachine.reduce(PhoneWearState.SENDING, PhoneWearEvent.WatchGone),+        )+        // No capability / no watch: nothing about the app breaks or changes.+        assertEquals(+            PhoneWearState.ON_WATCH,+            PhoneWearMachine.reduce(PhoneWearState.ON_WATCH, PhoneWearEvent.WatchGone),+        )+    }++    @Test+    fun `watch machine requires verified bytes and an explicit install tap`() {+        var phase = WatchAppPhase.LISTED+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveStarted)+        assertEquals(WatchAppPhase.RECEIVING, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveFinished(verified = false))+        assertEquals(WatchAppPhase.REJECTED, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveStarted)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveFinished(verified = true))+        assertEquals(WatchAppPhase.READY_TO_INSTALL, phase)+        // No tap, no install: RECEIVING/READY states never advance on their own.+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.InstallTapped)+        assertEquals(WatchAppPhase.INSTALLING, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.InstallFinished(installed = true))+        assertEquals(WatchAppPhase.INSTALLED, phase)+    }++    @Test+    fun `hash mismatch and truncation are rejected`() {+        val dir = java.nio.file.Files.createTempDirectory("wear-sync").toFile()+        try {+            val file = File(dir, "a.apk").apply { writeBytes("hello watch".toByteArray()) }+            val good = ApkOffer(+                "com.example.a", "A", 1L, file.length(),+                ApkHash.sha256Hex(file),+            )+            assertTrue(ApkHash.verify(file, good))+            assertFalse(ApkHash.verify(file, good.copy(sha256 = "00".repeat(32))))+            assertFalse(ApkHash.verify(file, good.copy(sizeBytes = file.length() + 1)))+        } finally {+            dir.deleteRecursively()+        }+    }++    @Test+    fun `eligibility is a technical gate only`() {+        assertNull(watchSendEligibility("https://x/a.apk", splitCount = 0, sizeBytes = 10L))+        assertTrue(watchSendEligibility(null, 0, 10L) != null)+        assertTrue(watchSendEligibility("https://x/a.apk", splitCount = 2, sizeBytes = 10L) != null)+        assertTrue(+            watchSendEligibility(+                "https://x/a.apk", 0, WearSyncProtocol.MAX_APK_BYTES + 1,+            ) != null,+        )+    }+}
appstore/wear/AGENTS.md
diff --git a/appstore/wear/AGENTS.md b/appstore/wear/AGENTS.mdnew file mode 100644index 0000000000..99b065f379--- /dev/null+++ b/appstore/wear/AGENTS.md@@ -0,0 +1,38 @@+# AGENTS.md — appstore/wear/ (':appstore:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `appstore/wear/` + the rest of `appstore/` (the phone side of the same feature).++- Gradle: :appstore:wear / dir: appstore/wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, platform, service+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone App Store (`:appstore`). The Wearable Data+Layer only connects apps sharing a **package name and signing certificate**,+so this module deliberately uses `applicationId = "com.vayunmathur.appstore"`+(the phone app's) with the shared dev/release signing from the convention+plugins. Changing either breaks phone<->watch sync silently. Bootstrap is a+one-time ADB sideload of this APK onto the watch.++## Protocol+`domain/WearSyncProtocol.kt` is a byte-identical copy of the phone's file+(Gradle cannot depend on another app module). Change both copies together;+each side's `WearSyncProtocolTest` pins the same golden JSON.++- Catalog + watch-state sync: DataClient (`/appstore/catalog`, `/appstore/watch-state`)+- Offers / install requests / results: MessageClient+- APK bytes: ChannelClient (`/appstore/apk/<package>`), verified size+SHA-256+  against the preceding offer before PackageInstaller ever sees them++## Install honesty+A normal Wear OS app **cannot silently install**. Verified APKs wait in+app-private storage until the wearer taps Install and confirms the system+PackageInstaller prompt. No state may claim otherwise.++## Verify (this module only)+```+./gradlew :appstore:wear:assembleDev+./gradlew :appstore:wear:testDebugUnitTest+./gradlew :appstore:wear:lint+```
appstore/wear/build.gradle.kts
diff --git a/appstore/wear/build.gradle.kts b/appstore/wear/build.gradle.ktsnew file mode 100644index 0000000000..acec432974--- /dev/null+++ b/appstore/wear/build.gradle.kts@@ -0,0 +1,32 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "store"+}++android {+    // The Wearable Data Layer only connects apps that share a package name and+    // signing certificate, so this module MUST ship as the phone app's package:+    // same applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The convention plugin derives this module's namespace from its+    // Gradle path (:appstore:wear -> com.vayunmathur.appstore.wear).+    defaultConfig {+        applicationId = "com.vayunmathur.appstore"+        // The wear convention plugin pins 30, but :library:log (which it also+        // wires in) requires 31. Wear OS devices on API 30 lose out; the+        // alternative is dropping the repo logging facade, which is worse.+        minSdk = 31+    }+}++dependencies {+    // Watch side of the Wear OS sync (see domain/WearSyncProtocol.kt, the+    // byte-identical copy of the phone protocol it must stay in step with).+    implementation(libs.play.services.wearable)+    implementation(libs.kotlinx.coroutines.android)+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
appstore/wear/src/main/AndroidManifest.xml
diff --git a/appstore/wear/src/main/AndroidManifest.xml b/appstore/wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..34a4e1360a--- /dev/null+++ b/appstore/wear/src/main/AndroidManifest.xml@@ -0,0 +1,66 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Wear OS form factor. Declaring the watch hardware makes this build+         installable on Wear OS; the touchscreen is not required there. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <!-- PackageInstaller asks the wearer to confirm every install; this+         permission is the phone-API equivalent gate for requesting one. -->+    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />+    <uses-permission android:name="android.permission.WAKE_LOCK" />++    <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 app, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <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>++        <!-- Receives catalog/data updates, APK offers and APK channels from+             the phone, including while the UI is not running. -->+        <service+            android:name=".service.WearDataListenerService"+            android:exported="true">+            <!-- Filtered listeners (not BIND_LISTENER): only this app's own+                 /appstore/ paths wake the service. -->+            <intent-filter>+                <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />+                <data android:host="*" android:pathPrefix="/appstore/" android:scheme="wear" />+            </intent-filter>+            <intent-filter>+                <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />+                <data android:host="*" android:pathPrefix="/appstore/" android:scheme="wear" />+            </intent-filter>+            <intent-filter>+                <action android:name="com.google.android.gms.wearable.CHANNEL_EVENT" />+                <data android:host="*" android:pathPrefix="/appstore/" android:scheme="wear" />+            </intent-filter>+        </service>++        <receiver+            android:name=".platform.InstallResultReceiver"+            android:exported="false" />+    </application>+</manifest>
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/data/WearStore.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/data/WearStore.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/data/WearStore.ktnew file mode 100644index 0000000000..3119689f69--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/data/WearStore.kt@@ -0,0 +1,212 @@+package com.vayunmathur.appstore.wear.data++import android.content.Context+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.appstore.wear.domain.ApkOffer+import com.vayunmathur.appstore.wear.domain.WatchAppEntry+import com.vayunmathur.appstore.wear.domain.WatchAppMachine+import com.vayunmathur.appstore.wear.domain.WatchAppEvent+import com.vayunmathur.appstore.wear.domain.WatchAppPhase+import com.vayunmathur.appstore.wear.domain.WatchState+import com.vayunmathur.appstore.wear.domain.WearCatalog+import com.vayunmathur.appstore.wear.domain.WearCatalogApp+import com.vayunmathur.appstore.wear.domain.WearSyncProtocol+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.coroutines.flow.update+import kotlinx.serialization.encodeToString++/** One row the watch UI draws: catalog facts plus where the local copy stands. */+data class WearRow(+    val app: WearCatalogApp,+    val phase: WatchAppPhase,+    /** True when the phone asked for install; cleared once the user acts. */+    val installRequested: Boolean = false,+)++/**+ * The watch's local truth: the last catalog the phone published, the verified+ * APKs on disk, and each app's phase.+ *+ * Everything survives the phone going away — the catalog and phases persist+ * as JSON in app-private storage and the APKs as files — so the watch app+ * works standalone with whatever it already has. Phases move only through+ * [WearAppMachine]; this class just persists and publishes the result.+ */+class WearStore private constructor(private val context: Context) {++    /** Holds singleton access. */+    companion object {+        private const val TAG = "WearStore"+        private const val KEY_JSON = "json"+        private const val KEY_SENT_AT = "sent_at"++        @Volatile+        private var instance: WearStore? = null++        /** The process-wide store (service and UI must agree on one). */+        fun get(context: Context): WearStore = instance ?: synchronized(this) {+            instance ?: WearStore(context.applicationContext).also { instance = it }+        }+    }++    private val apkDir = File(context.filesDir, "wear-apks").apply { mkdirs() }+    private val catalogFile = File(context.filesDir, "wear-catalog.json")+    private val phasesFile = File(context.filesDir, "wear-phases.json")++    private val _catalog = MutableStateFlow(loadCatalog())++    /** Last catalog snapshot from the phone; empty until the first sync. */+    val catalog: StateFlow<WearCatalog> = _catalog.asStateFlow()++    private val _phases = MutableStateFlow(loadPhases())++    /** Per-package install phase, persisted across process death. */+    val phases: StateFlow<Map<String, WatchAppPhase>> = _phases.asStateFlow()++    private val _requested = MutableStateFlow<Set<String>>(emptySet())++    /** Packages the phone asked the watch to surface Install for. */+    val requested: StateFlow<Set<String>> = _requested.asStateFlow()++    /** Offers announced but not yet fully streamed, by package. */+    private val pendingOffers = mutableMapOf<String, ApkOffer>()++    /** Rows for the UI: catalog order, plus on-disk apps the catalog forgot. */+    fun rows(): List<WearRow> {+        val known = _catalog.value.apps.map { app ->+            WearRow(+                app = app,+                phase = phaseOf(app.packageName),+                installRequested = app.packageName in _requested.value,+            )+        }+        val onDiskOnly = downloadedPackages()+            .filter { pkg -> known.none { it.app.packageName == pkg } }+            .map { pkg ->+                WearRow(+                    app = WearCatalogApp(packageName = pkg, name = pkg.substringAfterLast('.')),+                    phase = phaseOf(pkg),+                    installRequested = pkg in _requested.value,+                )+            }+        return known + onDiskOnly+    }++    /** Current phase of [packageName], reconciled with what PackageManager says. */+    fun phaseOf(packageName: String): WatchAppPhase {+        if (installedVersion(packageName) > 0) return WatchAppPhase.INSTALLED+        return _phases.value[packageName] ?: WatchAppPhase.LISTED+    }++    /** Version of [packageName] PackageManager reports installed, 0 when absent. */+    fun installedVersion(packageName: String): Long = runCatching {+        context.packageManager.getPackageInfo(packageName, 0).longVersionCode+    }.getOrDefault(0L)++    /** File a verified APK for [packageName] lives at once received. */+    fun apkFile(packageName: String): File = File(apkDir, "$packageName.apk")++    /** Packages with a (verified) APK currently on disk. */+    fun downloadedPackages(): List<String> =+        apkDir.listFiles { f -> f.isFile && f.name.endsWith(".apk") }+            ?.map { it.name.removeSuffix(".apk") }+            ?.sorted()+            ?: emptyList()++    /** Replace the catalog snapshot (DataClient push from the phone). */+    fun setCatalog(catalog: WearCatalog) {+        _catalog.value = catalog+        runCatching { catalogFile.writeText(WearSyncProtocol.json.encodeToString(catalog)) }+            .onFailure { Log.status(TAG, "persist catalog failed: ${it.message}") }+    }++    /** Remember [offer] until its channel finishes (or fails) arriving. */+    fun noteOffer(offer: ApkOffer) {+        synchronized(pendingOffers) { pendingOffers[offer.packageName] = offer }+    }++    /** The offer a channel for [packageName] must verify against, if any. */+    fun offerFor(packageName: String): ApkOffer? =+        synchronized(pendingOffers) { pendingOffers[packageName] }++    /** Forget [packageName]'s offer once its stream has been dealt with. */+    fun clearOffer(packageName: String) {+        synchronized(pendingOffers) { pendingOffers.remove(packageName) }+    }++    /** Feed [event] for [packageName] through the state machine and persist. */+    fun applyEvent(packageName: String, event: WatchAppEvent) {+        _phases.update { current ->+            val old = current[packageName] ?: WatchAppPhase.LISTED+            val next = WatchAppMachine.reduce(old, event)+            if (next == old) current else (current + (packageName to next)).also { persistPhases(it) }+        }+        if (event is WatchAppEvent.InstallTapped) {+            _requested.update { it - packageName }+        }+    }++    /** The phone asked for install: surface it, never perform it. */+    fun noteInstallRequested(packageName: String) {+        _requested.update { it + packageName }+    }++    /**+     * Publish this watch's truth to the phone ([WearSyncProtocol.WATCH_STATE_PATH])+     * so the phone's per-app sync view can reconcile.+     */+    fun publishWatchState() {+        val packages = (_catalog.value.apps.map { it.packageName } + downloadedPackages()).distinct()+        val state = WatchState(+            packages.map { pkg ->+                WatchAppEntry(+                    packageName = pkg,+                    downloadedVersionCode = downloadedVersionOf(pkg),+                    installedVersionCode = installedVersion(pkg),+                    installPending = phaseOf(pkg) == WatchAppPhase.READY_TO_INSTALL ||+                        pkg in _requested.value,+                )+            },+        )+        runCatching {+            val request = PutDataMapRequest.create(WearSyncProtocol.WATCH_STATE_PATH).apply {+                dataMap.putString(KEY_JSON, WearSyncProtocol.json.encodeToString(state))+                dataMap.putLong(KEY_SENT_AT, System.currentTimeMillis())+            }.asPutDataRequest().setUrgent()+            Wearable.getDataClient(context).putDataItem(request)+        }.onFailure { Log.status(TAG, "publish watch state failed: ${it.message}") }+    }++    private fun downloadedVersionOf(packageName: String): Long =+        _catalog.value.apps.firstOrNull { it.packageName == packageName }+            ?.versionCode+            ?.takeIf { apkFile(packageName).exists() }+            ?: if (apkFile(packageName).exists()) 1L else 0L++    private fun loadCatalog(): WearCatalog = runCatching {+        WearSyncProtocol.json.decodeFromString<WearCatalog>(catalogFile.readText())+    }.getOrDefault(WearCatalog())++    // Persisted as phase *names*: kotlinx JSON cannot use enum map keys.+    private fun loadPhases(): Map<String, WatchAppPhase> = runCatching {+        WearSyncProtocol.json.decodeFromString<Map<String, String>>(phasesFile.readText())+            .mapNotNull { (pkg, name) ->+                runCatching { WatchAppPhase.valueOf(name) }+                    .getOrNull()?.let { pkg to it }+            }+            .toMap()+    }.getOrDefault(emptyMap())++    private fun persistPhases(phases: Map<String, WatchAppPhase>) {+        runCatching {+            phasesFile.writeText(+                WearSyncProtocol.json.encodeToString(phases.mapValues { it.value.name }),+            )+        }.onFailure { Log.status(TAG, "persist phases failed: ${it.message}") }+    }+}
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocol.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocol.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocol.ktnew file mode 100644index 0000000000..1e81cacc17--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocol.kt@@ -0,0 +1,296 @@+package com.vayunmathur.appstore.wear.domain++import java.io.File+import java.io.InputStream+import java.security.MessageDigest+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS App Store.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only+ * connects apps that share a package name and signing certificate, but Gradle+ * cannot let one application module depend on another, so the wear module+ * (`:appstore:wear`, applicationId `com.vayunmathur.appstore`) carries a+ * byte-identical copy of this file under `com.vayunmathur.appstore.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.+ *+ * Transport split:+ * - Capability advertisement (res string-array `android_wear_capabilities` on+ *   the watch) tells the phone the wear store is present at all.+ * - DataClient carries the small, durable state: [CATALOG_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. DataItems survive disconnects and+ *   reconcile the two sides when they meet again.+ * - MessageClient carries ephemeral commands/results ([OFFER_PATH],+ *   [INSTALL_RESULT_PATH], [REQUEST_STATE_PATH]).+ * - ChannelClient ([apkChannelPath]) streams the APK itself: DataClient assets+ *   are size-capped and base64-inflated in transit, a channel is a raw stream.+ *+ * Install honesty: nothing here can install silently. The watch verifies the+ * stream against [ApkOffer.sha256], then a person on the watch taps Install+ * and confirms the system PackageInstaller prompt. States say exactly that —+ * there is no state that claims an install the OS has not confirmed.+ */+object WearSyncProtocol {+    /** Capability the wear store advertises; the phone looks for it on connected nodes. */+    const val CAPABILITY = "appstore_wear_store"++    /** DataClient path (phone -> watch): the [WearCatalog] JSON snapshot. */+    const val CATALOG_PATH = "/appstore/catalog"++    /** DataClient path (watch -> phone): the [WatchState] JSON snapshot. */+    const val WATCH_STATE_PATH = "/appstore/watch-state"++    /** MessageClient path (phone -> watch): an [ApkOffer] precedes every channel. */+    const val OFFER_PATH = "/appstore/apk-offer"++    /** MessageClient path (watch -> phone): an [InstallResult] after the OS answers. */+    const val INSTALL_RESULT_PATH = "/appstore/install-result"++    /** MessageClient path (phone -> watch): ask the watch to republish [WATCH_STATE_PATH]. */+    const val REQUEST_STATE_PATH = "/appstore/request-state"++    /**+     * MessageClient path (phone -> watch): ask the watch to surface its Install+     * action for the package named in the payload. This only *asks* — a person+     * on the watch still taps Install and confirms the system prompt.+     */+    const val REQUEST_INSTALL_PATH = "/appstore/request-install"++    /** ChannelClient path prefix (phone -> watch); the package name is the last segment. */+    const val APK_CHANNEL_PREFIX = "/appstore/apk/"++    /** Largest single APK this slice will stream (a watch has little storage to spare). */+    const val MAX_APK_BYTES = 200L * 1024 * 1024++    /** Channel path streaming [packageName]'s APK. */+    fun apkChannelPath(packageName: String): String = APK_CHANNEL_PREFIX + packageName++    /** The package a channel path streams, or null when [path] is not an APK channel. */+    fun packageFromChannelPath(path: String): String? =+        path.takeIf { it.startsWith(APK_CHANNEL_PREFIX) }+            ?.removePrefix(APK_CHANNEL_PREFIX)+            ?.takeIf { it.isNotBlank() && '/' !in it }++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One catalog row the phone offers the watch. Mirrors the phone catalog, trimmed to watch size. */+@Serializable+data class WearCatalogApp(+    val packageName: String,+    val name: String,+    val versionName: String? = null,+    val versionCode: Long = 0L,+    val sizeBytes: Long = 0L,+)++/** The phone's catalog snapshot for the watch ([WearSyncProtocol.CATALOG_PATH]). */+@Serializable+data class WearCatalog(val apps: List<WearCatalogApp> = emptyList())++/**+ * Metadata announced over MessageClient immediately before an APK channel opens.+ * The watch refuses bytes that do not match [sizeBytes]/[sha256] — the channel+ * itself carries no metadata, so this offer is the integrity contract.+ */+@Serializable+data class ApkOffer(+    val packageName: String,+    val name: String,+    val versionCode: Long,+    val sizeBytes: Long,+    /** Lowercase hex SHA-256 of the exact bytes about to be streamed. */+    val sha256: String,+)++/** Per-app truth as the watch knows it, published in [WatchState]. */+@Serializable+data class WatchAppEntry(+    val packageName: String,+    /** The APK for this version is fully received and hash-verified on the watch. */+    val downloadedVersionCode: Long = 0L,+    /** The version the watch's PackageManager reports installed, 0 when absent. */+    val installedVersionCode: Long = 0L,+    /** True while a verified APK sits waiting for the user to tap Install. */+    val installPending: Boolean = false,+)++/** The watch's downloaded/installed snapshot ([WearSyncProtocol.WATCH_STATE_PATH]). */+@Serializable+data class WatchState(val apps: List<WatchAppEntry> = emptyList())++/** The OS install verdict, sent watch -> phone once PackageInstaller answers. */+@Serializable+data class InstallResult(+    val packageName: String,+    val versionCode: Long,+    val installed: Boolean,+    /** Plain-language failure from the OS/status, empty on success. */+    val message: String = "",+)++/** Per-app sync state on the phone, per package. */+enum class PhoneWearState {+    /** No watch, or the watch has never been offered this app. */+    NOT_DOWNLOADED,+    /** The APK channel is open and bytes are moving. */+    SENDING,+    /** Verified APK is on the watch; nobody has asked to install it yet. */+    ON_WATCH,+    /** Install was requested; the watch still owes a user tap + OS confirmation. */+    INSTALL_REQUESTED,+    /** The watch's PackageManager confirms this (or a newer) version installed. */+    INSTALLED,+    /** The last send/verify/install step failed; see the message kept beside the state. */+    FAILED,+}++/** Events that move the phone-side per-app state. */+sealed interface PhoneWearEvent {+    data object SendStarted : PhoneWearEvent+    data class SendFinished(val success: Boolean) : PhoneWearEvent+    data object InstallRequested : PhoneWearEvent+    data class ResultReceived(val result: InstallResult) : PhoneWearEvent+    data class Reconciled(val entry: WatchAppEntry?, val catalogVersionCode: Long) : PhoneWearEvent+    data object WatchGone : PhoneWearEvent+}++/** Pure phone-side state machine; the Android transport only feeds it events. */+object PhoneWearMachine {+    fun reduce(state: PhoneWearState, event: PhoneWearEvent): PhoneWearState = when (event) {+        PhoneWearEvent.SendStarted -> PhoneWearState.SENDING+        is PhoneWearEvent.SendFinished ->+            if (event.success) PhoneWearState.ON_WATCH else PhoneWearState.FAILED+        PhoneWearEvent.InstallRequested ->+            if (state == PhoneWearState.ON_WATCH) PhoneWearState.INSTALL_REQUESTED else state+        is PhoneWearEvent.ResultReceived ->+            if (event.result.installed) PhoneWearState.INSTALLED else PhoneWearState.FAILED+        is PhoneWearEvent.Reconciled -> reconcile(state, event.entry, event.catalogVersionCode)+        PhoneWearEvent.WatchGone ->+            if (state == PhoneWearState.SENDING) PhoneWearState.FAILED else state+    }++    /**+     * Fold the watch's published truth into the local state. A live transfer+     * ([PhoneWearState.SENDING]) is never overwritten by a stale snapshot; an+     * install the watch confirms wins over everything else.+     */+    private fun reconcile(+        state: PhoneWearState,+        entry: WatchAppEntry?,+        catalogVersionCode: Long,+    ): PhoneWearState {+        if (state == PhoneWearState.SENDING) return state+        if (entry == null) {+            return if (state == PhoneWearState.INSTALLED) PhoneWearState.NOT_DOWNLOADED else state+        }+        return when {+            entry.installedVersionCode >= catalogVersionCode && catalogVersionCode > 0 ->+                PhoneWearState.INSTALLED+            entry.installPending -> PhoneWearState.INSTALL_REQUESTED+            entry.downloadedVersionCode >= catalogVersionCode && catalogVersionCode > 0 ->+                PhoneWearState.ON_WATCH+            entry.downloadedVersionCode > 0 -> PhoneWearState.ON_WATCH+            else -> state+        }+    }+}++/** Per-app state on the watch, per package. */+enum class WatchAppPhase {+    /** Offered in the catalog; no bytes yet. */+    LISTED,+    /** Channel open, bytes arriving. */+    RECEIVING,+    /** Stream arrived but failed the size/hash contract; bytes deleted. */+    REJECTED,+    /** Verified APK on disk, waiting for the user to tap Install. */+    READY_TO_INSTALL,+    /** PackageInstaller session committed; waiting for the OS verdict. */+    INSTALLING,+    /** PackageManager confirms the package installed. */+    INSTALLED,+    /** Install was attempted and the OS (or user) said no. */+    INSTALL_FAILED,+}++/** Events that move the watch-side per-app state. */+sealed interface WatchAppEvent {+    data object ReceiveStarted : WatchAppEvent+    data class ReceiveFinished(val verified: Boolean) : WatchAppEvent+    data object InstallTapped : WatchAppEvent+    data class InstallFinished(val installed: Boolean) : WatchAppEvent+    data object BecameInstalled : WatchAppEvent+}++/** Pure watch-side state machine; services/installers only feed it events. */+object WatchAppMachine {+    fun reduce(phase: WatchAppPhase, event: WatchAppEvent): WatchAppPhase = when (event) {+        WatchAppEvent.ReceiveStarted -> WatchAppPhase.RECEIVING+        is WatchAppEvent.ReceiveFinished ->+            if (event.verified) WatchAppPhase.READY_TO_INSTALL else WatchAppPhase.REJECTED+        WatchAppEvent.InstallTapped ->+            if (phase == WatchAppPhase.READY_TO_INSTALL ||+                phase == WatchAppPhase.INSTALL_FAILED+            ) {+                WatchAppPhase.INSTALLING+            } else {+                phase+            }+        is WatchAppEvent.InstallFinished ->+            if (event.installed) WatchAppPhase.INSTALLED else WatchAppPhase.INSTALL_FAILED+        WatchAppEvent.BecameInstalled -> WatchAppPhase.INSTALLED+    }+}++/**+ * Whether the phone can offer this catalog row to the watch at all.+ *+ * The catalog cannot prove a phone UI will be usable on a watch, and this does+ * not pretend otherwise: the gate is purely technical — one streamable APK+ * (split sets need a multi-file session protocol this slice does not carry)+ * with known bytes to hash. A truly incompatible APK is refused by the watch's+ * PackageManager at install time and that verdict is reported, not hidden.+ */+fun watchSendEligibility(+    apkUrl: String?,+    splitCount: Int,+    sizeBytes: Long,+): String? = when {+    apkUrl.isNullOrBlank() -> "this source published no downloadable APK"+    splitCount > 0 -> "split APK sets cannot be sent to the watch yet"+    sizeBytes > WearSyncProtocol.MAX_APK_BYTES -> "too large for the watch"+    else -> null+}++/** Streaming SHA-256 helpers: the offer/watch verification contract. */+object ApkHash {+    private const val BUFFER_SIZE = 64 * 1024++    /** Lowercase hex SHA-256 of [input]'s contents (consumed, not closed). */+    fun sha256Hex(input: InputStream): String {+        val digest = MessageDigest.getInstance("SHA-256")+        val buffer = ByteArray(BUFFER_SIZE)+        while (true) {+            val read = input.read(buffer)+            if (read < 0) break+            if (read > 0) digest.update(buffer, 0, read)+        }+        return digest.digest().joinToString("") { "%02x".format(it) }+    }++    /** Lowercase hex SHA-256 of [file]. */+    fun sha256Hex(file: File): String = file.inputStream().buffered().use { sha256Hex(it) }++    /**+     * True when [file] is exactly [offer]'s bytes. A mismatch (or a truncated+     * stream, which the size check catches first) means the bytes are refused:+     * callers delete the file and never hand it to PackageInstaller.+     */+    fun verify(file: File, offer: ApkOffer): Boolean =+        file.length() == offer.sizeBytes && sha256Hex(file) == offer.sha256.lowercase()+}
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/InstallResultReceiver.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/InstallResultReceiver.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/InstallResultReceiver.ktnew file mode 100644index 0000000000..1599e2f7a7--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/InstallResultReceiver.kt@@ -0,0 +1,91 @@+package com.vayunmathur.appstore.wear.platform++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.content.pm.PackageInstaller+import android.os.Build+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.appstore.wear.data.WearStore+import com.vayunmathur.appstore.wear.domain.InstallResult+import com.vayunmathur.appstore.wear.domain.WatchAppEvent+import com.vayunmathur.appstore.wear.domain.WearSyncProtocol+import com.vayunmathur.library.log.Log+import kotlinx.serialization.encodeToString++/**+ * Receives the PackageInstaller verdict for watch installs.+ *+ * STATUS_PENDING_USER_ACTION is the honest centre of this feature: the OS is+ * asking the wearer, and this receiver's job is only to put that prompt in+ * front of them (and, later, to report what they and the OS decided).+ */+class InstallResultReceiver : BroadcastReceiver() {++    /** Holds broadcast constants for install-result callbacks. */+    companion object {+        const val ACTION_INSTALL_RESULT = "com.vayunmathur.appstore.wear.INSTALL_RESULT"+        const val EXTRA_PACKAGE = "package"+        private const val TAG = "InstallResultReceiver"+        private const val UNKNOWN_STATUS = -1+    }++    override fun onReceive(context: Context, intent: Intent) {+        val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, UNKNOWN_STATUS)+        val message = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE).orEmpty()+        val packageName = intent.getStringExtra(EXTRA_PACKAGE)+            ?: intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME)+            ?: return+        val store = WearStore.get(context)++        when (status) {+            PackageInstaller.STATUS_PENDING_USER_ACTION -> {+                val userAction = if (Build.VERSION.SDK_INT >= 33) {+                    intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)+                } else {+                    @Suppress("DEPRECATION")+                    intent.getParcelableExtra(Intent.EXTRA_INTENT)+                } ?: return+                userAction.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+                runCatching { context.startActivity(userAction) }+                    .onFailure { Log.status(TAG, "show install prompt failed: ${it.message}") }+            }++            PackageInstaller.STATUS_SUCCESS -> {+                store.applyEvent(packageName, WatchAppEvent.InstallFinished(installed = true))+                store.publishWatchState()+                report(context, InstallResult(packageName, store.installedVersion(packageName), true))+            }++            else -> {+                // Includes STATUS_FAILURE_ABORTED (wearer backed out): a real+                // outcome the phone should show, not a silent disappearance.+                store.applyEvent(packageName, WatchAppEvent.InstallFinished(installed = false))+                store.publishWatchState()+                report(+                    context,+                    InstallResult(+                        packageName,+                        0L,+                        installed = false,+                        message.ifBlank { "install failed (status $status)" },+                    ),+                )+            }+        }+    }++    private fun report(context: Context, result: InstallResult) {+        runCatching {+            Wearable.getNodeClient(context).connectedNodes.addOnSuccessListener { nodes ->+                for (node in nodes) {+                    Wearable.getMessageClient(context).sendMessage(+                        node.id,+                        WearSyncProtocol.INSTALL_RESULT_PATH,+                        WearSyncProtocol.json.encodeToString(result).encodeToByteArray(),+                    )+                }+            }+        }.onFailure { Log.status(TAG, "report result failed: ${it.message}") }+    }+}
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/WearInstaller.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/WearInstaller.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/WearInstaller.ktnew file mode 100644index 0000000000..e031406273--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/platform/WearInstaller.kt@@ -0,0 +1,74 @@+package com.vayunmathur.appstore.wear.platform++import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageInstaller+import com.vayunmathur.appstore.wear.data.WearStore+import com.vayunmathur.appstore.wear.domain.WatchAppEvent+import com.vayunmathur.library.log.Log+import java.io.File++/**+ * Hands one verified APK to PackageInstaller — with the user action required.+ *+ * A regular Wear OS app cannot silently install anything: the session is+ * committed without USER_ACTION_NOT_REQUIRED, so the OS shows its own+ * confirmation to the wearer and [InstallResultReceiver] forwards that prompt+ * and reports the verdict. Nothing in this file may claim success before the+ * OS does.+ */+object WearInstaller {++    private const val TAG = "WearInstaller"++    /**+     * Commit [file] for [packageName]. Returns true when the session was+     * committed (the OS verdict still arrives via [InstallResultReceiver]).+     */+    fun install(context: Context, packageName: String, file: File): Boolean {+        if (!file.exists() || file.length() == 0L) return false+        val store = WearStore.get(context)+        return try {+            val installer = context.packageManager.packageInstaller+            installer.mySessions+                .filter { it.appPackageName == packageName }+                .forEach { runCatching { installer.abandonSession(it.sessionId) } }++            val params = PackageInstaller.SessionParams(+                PackageInstaller.SessionParams.MODE_FULL_INSTALL,+            ).apply {+                setSize(file.length())+                setAppPackageName(packageName)+            }+            val sessionId = installer.createSession(params)+            val session = installer.openSession(sessionId)+            try {+                session.openWrite(file.name, 0, file.length()).use { out ->+                    file.inputStream().use { it.copyTo(out) }+                    session.fsync(out)+                }+                val intent = Intent(context, InstallResultReceiver::class.java).apply {+                    action = InstallResultReceiver.ACTION_INSTALL_RESULT+                    putExtra(InstallResultReceiver.EXTRA_PACKAGE, packageName)+                }+                val pending = PendingIntent.getBroadcast(+                    context,+                    sessionId,+                    intent,+                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE,+                )+                session.commit(pending.intentSender)+                session.close()+                store.applyEvent(packageName, WatchAppEvent.InstallTapped)+                true+            } catch (expected: Exception) {+                runCatching { session.abandon() }+                throw expected+            }+        } catch (expected: Exception) {+            Log.error(TAG, "install $packageName failed to start", expected)+            false+        }+    }+}
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/service/WearDataListenerService.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/service/WearDataListenerService.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/service/WearDataListenerService.ktnew file mode 100644index 0000000000..cebe73ff50--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/service/WearDataListenerService.kt@@ -0,0 +1,172 @@+package com.vayunmathur.appstore.wear.service++import com.google.android.gms.tasks.Task+import com.google.android.gms.wearable.ChannelClient+import com.google.android.gms.wearable.DataEvent+import com.google.android.gms.wearable.DataEventBuffer+import com.google.android.gms.wearable.DataMapItem+import com.google.android.gms.wearable.MessageEvent+import com.google.android.gms.wearable.Wearable+import com.google.android.gms.wearable.WearableListenerService+import com.vayunmathur.appstore.wear.data.WearStore+import com.vayunmathur.appstore.wear.domain.ApkHash+import com.vayunmathur.appstore.wear.domain.ApkOffer+import com.vayunmathur.appstore.wear.domain.InstallResult+import com.vayunmathur.appstore.wear.domain.WatchAppEvent+import com.vayunmathur.appstore.wear.domain.WearCatalog+import com.vayunmathur.appstore.wear.domain.WearSyncProtocol+import com.vayunmathur.appstore.wear.ui.WearMainActivity+import com.vayunmathur.library.log.Log+import java.io.File+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.serialization.encodeToString++/** Await a Play services [Task] without taking a coroutines-play-services dependency. */+private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->+    addOnSuccessListener { cont.resume(it) }+    addOnFailureListener { cont.resumeWithException(it) }+}++/**+ * Watch side of the Data Layer: catalog pushes, APK offers, APK channels and+ * install requests from the phone.+ *+ * APK bytes only ever land in app-private storage after the stream has been+ * checked against its [ApkOffer] (size, then SHA-256). A mismatch deletes the+ * file, marks the app REJECTED and tells the phone — unverified bytes are+ * never handed to PackageInstaller.+ */+class WearDataListenerService : WearableListenerService() {++    /** Holds constants for the listener service. */+    companion object {+        private const val TAG = "WearDataListener"+        private const val KEY_JSON = "json"+        private const val OFFER_WAIT_MS = 5_000L+    }++    private val scope = CoroutineScope(Dispatchers.IO)++    override fun onDataChanged(dataEvents: DataEventBuffer) {+        val store = WearStore.get(this)+        for (event in dataEvents) {+            if (event.type != DataEvent.TYPE_CHANGED) continue+            if (event.dataItem.uri.path != WearSyncProtocol.CATALOG_PATH) continue+            val json = runCatching {+                DataMapItem.fromDataItem(event.dataItem).dataMap.getString(KEY_JSON)+            }.getOrNull() ?: continue+            runCatching { WearSyncProtocol.json.decodeFromString<WearCatalog>(json) }+                .onSuccess { store.setCatalog(it) }+                .onFailure { Log.status(TAG, "bad catalog push: ${it.message}") }+        }+    }++    override fun onMessageReceived(messageEvent: MessageEvent) {+        val store = WearStore.get(this)+        when (messageEvent.path) {+            WearSyncProtocol.OFFER_PATH -> runCatching {+                WearSyncProtocol.json.decodeFromString<ApkOffer>(+                    messageEvent.data.decodeToString(),+                )+            }.onSuccess { store.noteOffer(it) }+                .onFailure { Log.status(TAG, "bad apk offer: ${it.message}") }++            WearSyncProtocol.REQUEST_STATE_PATH -> store.publishWatchState()++            WearSyncProtocol.REQUEST_INSTALL_PATH -> {+                // Asking is all the phone can do: surface the app so the wearer+                // can tap Install and confirm the system prompt themselves.+                store.noteInstallRequested(messageEvent.data.decodeToString())+                store.publishWatchState()+                runCatching {+                    startActivity(+                        android.content.Intent(this, WearMainActivity::class.java)+                            .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK),+                    )+                }+            }+        }+    }++    override fun onChannelOpened(channel: ChannelClient.Channel) {+        val packageName = WearSyncProtocol.packageFromChannelPath(channel.path) ?: run {+            runCatching { Wearable.getChannelClient(this@WearDataListenerService).close(channel) }+            return+        }+        val store = WearStore.get(this)+        scope.launch { receiveApk(channel, packageName, store) }+    }++    private suspend fun receiveApk(+        channel: ChannelClient.Channel,+        packageName: String,+        store: WearStore,+    ) {+        // The offer message is sent before the channel opens, but the two+        // travel independently: give it a moment to land before refusing.+        var offer = store.offerFor(packageName)+        var waited = 0L+        while (offer == null && waited < OFFER_WAIT_MS) {+            delay(200)+            waited += 200+            offer = store.offerFor(packageName)+        }+        val target = store.apkFile(packageName)+        val partial = File(target.parentFile, "$packageName.partial")+        try {+            if (offer == null) {+                Log.error(TAG, "channel for $packageName arrived without an offer; refusing")+                reportFailure(packageName, 0L, "no download offer from the phone")+                return+            }+            store.applyEvent(packageName, WatchAppEvent.ReceiveStarted)+            val input = Wearable.getChannelClient(this).getInputStream(channel).awaitTask()+            input.use { stream ->+                partial.outputStream().use { stream.copyTo(it) }+            }+            if (ApkHash.verify(partial, offer)) {+                partial.renameTo(target)+                store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = true))+            } else {+                // Truncated or tampered stream: the bytes die here, unsigned+                // claims and all, and the phone hears about it.+                partial.delete()+                store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = false))+                reportFailure(+                    packageName, offer.versionCode,+                    "download did not match the size/hash the phone announced",+                )+            }+        } catch (expected: Exception) {+            Log.error(TAG, "receive $packageName failed", expected)+            runCatching { partial.delete() }+            store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = false))+            reportFailure(packageName, offer?.versionCode ?: 0L, expected.message ?: "transfer failed")+        } finally {+            store.clearOffer(packageName)+            runCatching { Wearable.getChannelClient(this).close(channel) }+            store.publishWatchState()+        }+    }++    private fun reportFailure(packageName: String, versionCode: Long, message: String) {+        val result = InstallResult(packageName, versionCode, installed = false, message)+        runCatching {+            Wearable.getNodeClient(this).connectedNodes.addOnSuccessListener { nodes ->+                for (node in nodes) {+                    Wearable.getMessageClient(this).sendMessage(+                        node.id,+                        WearSyncProtocol.INSTALL_RESULT_PATH,+                        WearSyncProtocol.json.encodeToString(result).encodeToByteArray(),+                    )+                }+            }+        }+    }+}
appstore/wear/src/main/java/com/vayunmathur/appstore/wear/ui/WearMainActivity.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/ui/WearMainActivity.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..db0d556676--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/ui/WearMainActivity.kt@@ -0,0 +1,139 @@+package com.vayunmathur.appstore.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+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.appstore.wear.R+import com.vayunmathur.appstore.wear.data.WearStore+import com.vayunmathur.appstore.wear.domain.WatchAppPhase+import com.vayunmathur.appstore.wear.platform.WearInstaller++/**+ * The whole watch store: what the phone offered, what is already downloaded+ * here, and an Install action for anything verified and waiting.+ *+ * Deliberately tiny — one scrolling column, no navigation. It reads only the+ * watch's own persisted state, so it works standalone (phone absent, app+ * cold-started) with whatever has already been downloaded.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val store = WearStore.get(this)+        store.publishWatchState()+        setContent {+            MaterialTheme {+                WearStoreScreen(store)+            }+        }+    }++    override fun onResume() {+        super.onResume()+        // Catch installs the system prompt completed while we were away.+        WearStore.get(this).publishWatchState()+    }+}++/** Stateless list body for [WearMainActivity]; state comes from [WearStore]. */+@Composable+fun WearStoreScreen(store: WearStore) {+    val catalog by store.catalog.collectAsState()+    val phases by store.phases.collectAsState()+    val requested by store.requested.collectAsState()+    // Recompute rows when any input moves; rows() also folds in PackageManager.+    val rows = store.rows()+    val context = androidx.compose.ui.platform.LocalContext.current+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.app_name),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (rows.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+            return@ScalingLazyColumn+        }+        items(rows, key = { it.app.packageName }) { row ->+            val phase = store.phaseOf(row.app.packageName)+            WearRowChip(row.app.name, phase, row.installRequested || row.app.packageName in requested) {+                if (phase == WatchAppPhase.READY_TO_INSTALL ||+                    phase == WatchAppPhase.INSTALL_FAILED+                ) {+                    WearInstaller.install(+                        context,+                        row.app.packageName,+                        store.apkFile(row.app.packageName),+                    )+                }+            }+        }+    }+}++/** One app row: name + honest phase, tappable only when install can start. */+@Composable+private fun WearRowChip(+    name: String,+    phase: WatchAppPhase,+    installRequested: Boolean,+    onClick: () -> Unit,+) {+    val label = when (phase) {+        WatchAppPhase.LISTED -> stringResource(R.string.wear_state_listed)+        WatchAppPhase.RECEIVING -> stringResource(R.string.wear_state_receiving)+        WatchAppPhase.REJECTED -> stringResource(R.string.wear_state_rejected)+        WatchAppPhase.READY_TO_INSTALL ->+            if (installRequested) {+                stringResource(R.string.wear_state_ready)+            } else {+                stringResource(R.string.wear_state_ready)+            }+        WatchAppPhase.INSTALLING -> stringResource(R.string.wear_state_installing)+        WatchAppPhase.INSTALLED -> stringResource(R.string.wear_state_installed)+        WatchAppPhase.INSTALL_FAILED -> stringResource(R.string.wear_state_failed)+    }+    val tappable = phase == WatchAppPhase.READY_TO_INSTALL ||+        phase == WatchAppPhase.INSTALL_FAILED+    Chip(+        onClick = onClick,+        enabled = tappable,+        label = { Text(name, maxLines = 1) },+        secondaryLabel = { Text(label, maxLines = 2) },+        colors = if (tappable) {+            ChipDefaults.primaryChipColors()+        } else {+            ChipDefaults.secondaryChipColors()+        },+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}
appstore/wear/src/main/res/values/colors.xml
diff --git a/appstore/wear/src/main/res/values/colors.xml b/appstore/wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..aaf92ba664--- /dev/null+++ b/appstore/wear/src/main/res/values/colors.xml@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Referenced by the generated adaptive launcher icon. Phone apps inherit+     this from :library; the wear convention does not, so the wear store+     declares its own. -->+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
appstore/wear/src/main/res/values/strings.xml
diff --git a/appstore/wear/src/main/res/values/strings.xml b/appstore/wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..f85188581c--- /dev/null+++ b/appstore/wear/src/main/res/values/strings.xml@@ -0,0 +1,15 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">App Store</string>+    <string name="wear_empty">Nothing here yet. Send an app from the App Store on your phone.</string>+    <string name="wear_install">Install</string>+    <string name="wear_retry_install">Try install again</string>+    <string name="wear_state_listed">On your phone — not sent yet</string>+    <string name="wear_state_receiving">Receiving…</string>+    <string name="wear_state_rejected">Download did not check out — send it again</string>+    <string name="wear_state_ready">Downloaded — tap Install, then confirm</string>+    <string name="wear_state_installing">Waiting for your confirmation…</string>+    <string name="wear_state_installed">Installed</string>+    <string name="wear_state_failed">Install failed — you can try again</string>+    <string name="wear_downloaded_section">Downloaded on this watch</string>+</resources>
appstore/wear/src/main/res/values/wear_capabilities.xml
diff --git a/appstore/wear/src/main/res/values/wear_capabilities.xml b/appstore/wear/src/main/res/values/wear_capabilities.xmlnew file mode 100644index 0000000000..3904a1f876--- /dev/null+++ b/appstore/wear/src/main/res/values/wear_capabilities.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Capability the phone's CapabilityClient looks for: advertising it is+     what makes the phone offer "Send to watch" at all. Must match+     WearSyncProtocol.CAPABILITY in domain/WearSyncProtocol.kt. -->+<resources>+    <string-array name="android_wear_capabilities">+        <item>appstore_wear_store</item>+    </string-array>+</resources>
appstore/wear/src/test/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocolTest.kt
diff --git a/appstore/wear/src/test/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocolTest.kt b/appstore/wear/src/test/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocolTest.ktnew file mode 100644index 0000000000..068f1922d4--- /dev/null+++ b/appstore/wear/src/test/java/com/vayunmathur/appstore/wear/domain/WearSyncProtocolTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.appstore.wear.domain++import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearSyncProtocolTest {++    @Test+    fun `golden wire json is stable across both apps`() {+        // The wear module pins these exact strings in its own copy of this test:+        // a one-sided protocol edit breaks one side or the other, never silently both.+        val catalog = WearCatalog(listOf(WearCatalogApp("com.example.a", "A", "1.0", 7L, 123L)))+        assertEquals(+            """{"apps":[{"packageName":"com.example.a","name":"A","versionName":"1.0","versionCode":7,"sizeBytes":123}]}""",+            WearSyncProtocol.json.encodeToString(catalog),+        )+        val offer = ApkOffer("com.example.a", "A", 7L, 123L, "ab12")+        assertEquals(+            """{"packageName":"com.example.a","name":"A","versionCode":7,"sizeBytes":123,"sha256":"ab12"}""",+            WearSyncProtocol.json.encodeToString(offer),+        )+        assertEquals("/appstore/apk/com.example.a", WearSyncProtocol.apkChannelPath("com.example.a"))+        assertEquals("com.example.a", WearSyncProtocol.packageFromChannelPath("/appstore/apk/com.example.a"))+        assertNull(WearSyncProtocol.packageFromChannelPath("/appstore/catalog"))+    }++    @Test+    fun `phone machine walks send to installed and never fakes a step`() {+        var state = PhoneWearState.NOT_DOWNLOADED+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.SendStarted)+        assertEquals(PhoneWearState.SENDING, state)+        // Install cannot be requested before the bytes are on the watch.+        assertEquals(+            PhoneWearState.SENDING,+            PhoneWearMachine.reduce(state, PhoneWearEvent.InstallRequested),+        )+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.SendFinished(true))+        assertEquals(PhoneWearState.ON_WATCH, state)+        state = PhoneWearMachine.reduce(state, PhoneWearEvent.InstallRequested)+        assertEquals(PhoneWearState.INSTALL_REQUESTED, state)+        state = PhoneWearMachine.reduce(+            state,+            PhoneWearEvent.ResultReceived(InstallResult("com.example.a", 7L, installed = false, "user cancelled")),+        )+        assertEquals(PhoneWearState.FAILED, state)+    }++    @Test+    fun `reconcile trusts the watch snapshot except during a live send`() {+        val entry = WatchAppEntry("com.example.a", downloadedVersionCode = 7L, installedVersionCode = 7L)+        assertEquals(+            PhoneWearState.INSTALLED,+            PhoneWearMachine.reduce(+                PhoneWearState.ON_WATCH,+                PhoneWearEvent.Reconciled(entry, catalogVersionCode = 7L),+            ),+        )+        assertEquals(+            PhoneWearState.SENDING,+            PhoneWearMachine.reduce(+                PhoneWearState.SENDING,+                PhoneWearEvent.Reconciled(entry, catalogVersionCode = 7L),+            ),+        )+        assertEquals(+            PhoneWearState.FAILED,+            PhoneWearMachine.reduce(PhoneWearState.SENDING, PhoneWearEvent.WatchGone),+        )+        // No capability / no watch: nothing about the app breaks or changes.+        assertEquals(+            PhoneWearState.ON_WATCH,+            PhoneWearMachine.reduce(PhoneWearState.ON_WATCH, PhoneWearEvent.WatchGone),+        )+    }++    @Test+    fun `watch machine requires verified bytes and an explicit install tap`() {+        var phase = WatchAppPhase.LISTED+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveStarted)+        assertEquals(WatchAppPhase.RECEIVING, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveFinished(verified = false))+        assertEquals(WatchAppPhase.REJECTED, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveStarted)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.ReceiveFinished(verified = true))+        assertEquals(WatchAppPhase.READY_TO_INSTALL, phase)+        // No tap, no install: RECEIVING/READY states never advance on their own.+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.InstallTapped)+        assertEquals(WatchAppPhase.INSTALLING, phase)+        phase = WatchAppMachine.reduce(phase, WatchAppEvent.InstallFinished(installed = true))+        assertEquals(WatchAppPhase.INSTALLED, phase)+    }++    @Test+    fun `hash mismatch and truncation are rejected`() {+        val dir = java.nio.file.Files.createTempDirectory("wear-sync").toFile()+        try {+            val file = File(dir, "a.apk").apply { writeBytes("hello watch".toByteArray()) }+            val good = ApkOffer(+                "com.example.a", "A", 1L, file.length(),+                ApkHash.sha256Hex(file),+            )+            assertTrue(ApkHash.verify(file, good))+            assertFalse(ApkHash.verify(file, good.copy(sha256 = "00".repeat(32))))+            assertFalse(ApkHash.verify(file, good.copy(sizeBytes = file.length() + 1)))+        } finally {+            dir.deleteRecursively()+        }+    }++    @Test+    fun `eligibility is a technical gate only`() {+        assertNull(watchSendEligibility("https://x/a.apk", splitCount = 0, sizeBytes = 10L))+        assertTrue(watchSendEligibility(null, 0, 10L) != null)+        assertTrue(watchSendEligibility("https://x/a.apk", splitCount = 2, sizeBytes = 10L) != null)+        assertTrue(+            watchSendEligibility(+                "https://x/a.apk", 0, WearSyncProtocol.MAX_APK_BYTES + 1,+            ) != null,+        )+    }+}
build-logic/src/main/kotlin/common-conventions-wear.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts b/build-logic/src/main/kotlin/common-conventions-wear.gradle.ktsindex 660d539927..675a3984af 100644--- a/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-wear.gradle.kts@@ -64,7 +64,8 @@ configure<com.android.build.api.dsl.ApplicationExtension> {         compose = true     } -    namespace = "com.vayunmathur${path.replace(":", ".")}"+    // Hyphens are not valid in a Java package: `:contacts-wear` -> `com.vayunmathur.contacts.wear`.+    namespace = "com.vayunmathur${path.replace(":", ".").replace("-", ".")}"     compileSdk {         // Platform 37.1+ for the current Compose train (BOM 2026.09.00).         version = release(37) {
calendar/build.gradle.kts
diff --git a/calendar/build.gradle.kts b/calendar/build.gradle.ktsindex 724eede06e..6ebf4a44be 100644--- a/calendar/build.gradle.kts+++ b/calendar/build.gradle.kts@@ -17,6 +17,11 @@ android {  dependencies {     implementation(project(":library:widgets"))+    // Phone side of the Wear OS sync (sync/WearCalendarSync): capability+    // discovery and snapshot publish to :calendar-wear, which shares this+    // app's applicationId and signing certificate.+    implementation(libs.play.services.wearable)+    implementation(libs.kotlinx.coroutines.android)     testImplementation(libs.androidx.glance.testing)     testImplementation(libs.androidx.glance.appwidget.testing) 
calendar/src/main/AndroidManifest.xml
diff --git a/calendar/src/main/AndroidManifest.xml b/calendar/src/main/AndroidManifest.xmlindex fe98309862..dce6c61e38 100644--- a/calendar/src/main/AndroidManifest.xml+++ b/calendar/src/main/AndroidManifest.xml@@ -139,6 +139,15 @@                 android:resource="@xml/calendar_month_widget_info" />         </receiver> +        <!-- Watch-originated sync requests while the UI is not running. -->+        <service+            android:name=".service.WearCalendarListenerService"+            android:exported="true">+            <intent-filter>+                <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />+                <data android:scheme="wear" android:host="*" android:pathPrefix="/calendar/request-sync" />+            </intent-filter>+        </service>         <receiver             android:name=".platform.ReminderReceiver"             android:enabled="true"
calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt b/calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.ktnew file mode 100644index 0000000000..b1c49d4921--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt@@ -0,0 +1,150 @@+package com.vayunmathur.calendar.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Calendar companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only+ * connects apps that share a package name and signing certificate, but Gradle+ * cannot let one application module depend on another, so the wear module+ * (`:calendar:wear`, applicationId `com.vayunmathur.calendar`) carries a copy+ * of this file under `com.vayunmathur.calendar.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.+ *+ * Transport split:+ * - Capability advertisement (res string-array `android_wear_capabilities` on+ *   the watch) tells the phone the wear companion is present at all.+ * - DataClient carries the durable snapshot: [SNAPSHOT_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. DataItems survive disconnects and+ *   reconcile the two sides when they meet again.+ * - MessageClient carries one ephemeral command, [REQUEST_SYNC_PATH]+ *   watch -> phone: the watch asks for a fresh snapshot. That is the only+ *   watch-originated write. There is no event editing or RSVP: the phone's+ *   calendar model has no attendee/self-status for its local calendars, so+ *   inventing an RSVP write would fake a change the provider never made.+ */+object WearCalendarProtocol {+    /** Capability the wear companion advertises; the phone looks for it on connected nodes. */+    const val CAPABILITY = "calendar_wear_companion"++    /** DataClient path (phone -> watch): the [WearCalendarSnapshot] JSON. */+    const val SNAPSHOT_PATH = "/calendar/snapshot"++    /** DataClient path (watch -> phone): the [WearWatchState] JSON. */+    const val WATCH_STATE_PATH = "/calendar/watch-state"++    /** MessageClient path (watch -> phone): ask the phone to publish a fresh snapshot. */+    const val REQUEST_SYNC_PATH = "/calendar/request-sync"++    /** Days ahead of the window start included in a snapshot. */+    const val WINDOW_DAYS = 30++    /** Most events in one snapshot; a watch has little storage and a tiny screen. */+    const val MAX_EVENTS = 200++    /**+     * Largest snapshot JSON, in UTF-8 bytes. DataClient caps a DataItem at+     * 100 KB; staying under it keeps the snapshot on DataClient (durable,+     * reconciled on reconnect) instead of needing a channel.+     */+    const val MAX_JSON_BYTES = 90_000++    /** Field caps applied when a snapshot is built, so one huge event cannot crowd out the rest. */+    const val MAX_TITLE_CHARS = 120+    const val MAX_LOCATION_CHARS = 120+    const val MAX_DESCRIPTION_CHARS = 280+    const val MAX_CALENDAR_NAME_CHARS = 60++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One event occurrence in a [WearCalendarSnapshot], trimmed to watch size. */+@Serializable+data class WearCalendarEvent(+    /** Phone provider event id; with [startMillis] it identifies one occurrence. */+    val eventId: Long,+    val title: String,+    val location: String = "",+    val description: String = "",+    val calendarName: String = "",+    /** ARGB display colour of the owning calendar, 0 when unknown. */+    val color: Int = 0,+    val startMillis: Long,+    val endMillis: Long,+    val allDay: Boolean = false,+    val timezone: String = "UTC",+)++/** The phone's bounded calendar snapshot for the watch ([WearCalendarProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearCalendarSnapshot(+    /** When the phone built this snapshot, epoch millis. */+    val generatedAtMillis: Long = 0L,+    /** Inclusive window start, epoch millis; the watch renders only inside the window. */+    val windowStartMillis: Long = 0L,+    /** Exclusive window end, epoch millis (window start + [WearCalendarProtocol.WINDOW_DAYS] days). */+    val windowEndMillis: Long = 0L,+    val events: List<WearCalendarEvent> = emptyList(),+    /** True when the window/size caps dropped events the window actually contained. */+    val truncated: Boolean = false,+)++/** What the watch last applied, published at [WearCalendarProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+    /** generatedAtMillis of the snapshot the watch is rendering from, 0 when none yet. */+    val appliedGeneratedAtMillis: Long = 0L,+    val eventCount: Int = 0,+)++/**+ * Builds a bounded snapshot from [candidates]: keeps occurrences that overlap+ * [[windowStartMillis], [windowEndMillis]), sorts by start, applies the field+ * caps, then enforces [WearCalendarProtocol.MAX_EVENTS] and+ * [WearCalendarProtocol.MAX_JSON_BYTES] (dropping latest-first, which keeps+ * today's agenda — the watch's main screen — intact longest).+ */+fun buildWearSnapshot(+    candidates: List<WearCalendarEvent>,+    generatedAtMillis: Long,+    windowStartMillis: Long,+    windowEndMillis: Long,+): WearCalendarSnapshot {+    val inWindow = candidates+        .filter { it.endMillis > windowStartMillis && it.startMillis < windowEndMillis }+        .sortedWith(compareBy({ it.startMillis }, { it.eventId }))+        .map { event ->+            event.copy(+                title = event.title.take(WearCalendarProtocol.MAX_TITLE_CHARS),+                location = event.location.take(WearCalendarProtocol.MAX_LOCATION_CHARS),+                description = event.description.take(WearCalendarProtocol.MAX_DESCRIPTION_CHARS),+                calendarName = event.calendarName.take(WearCalendarProtocol.MAX_CALENDAR_NAME_CHARS),+            )+        }+    var kept = inWindow.take(WearCalendarProtocol.MAX_EVENTS)+    var truncated = kept.size < inWindow.size+    var snapshot = WearCalendarSnapshot(+        generatedAtMillis = generatedAtMillis,+        windowStartMillis = windowStartMillis,+        windowEndMillis = windowEndMillis,+        events = kept,+        truncated = truncated,+    )+    while (kept.isNotEmpty() &&+        WearCalendarProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+        WearCalendarProtocol.MAX_JSON_BYTES+    ) {+        kept = kept.dropLast(1)+        truncated = true+        snapshot = snapshot.copy(events = kept, truncated = true)+    }+    return snapshot+}++/** True when [nodeIdsWithCapability] is non-empty: a watch companion is present. */+fun wearCompanionPresent(nodeIdsWithCapability: Collection<String>): Boolean =+    nodeIdsWithCapability.isNotEmpty()
calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarUiContract.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarUiContract.kt b/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarUiContract.ktindex 6f546d9327..8dcd3090b5 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarUiContract.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarUiContract.kt@@ -52,6 +52,12 @@ data class SettingsUiState(     val calendarVisibility: Map<Long, Boolean> = emptyMap(),     val layout: CalendarViewModel.CalendarLayout = CalendarViewModel.CalendarLayout.FullWeek,     val themeMode: CalendarViewModel.ThemeMode = CalendarViewModel.ThemeMode.System,+    /** True when a watch advertising the calendar companion capability is reachable. */+    val wearCompanionPresent: Boolean = false,+    /** When the phone last published a wear snapshot, epoch millis; null when never. */+    val wearLastSyncMillis: Long? = null,+    /** Events in the last published wear snapshot. */+    val wearLastSyncEventCount: Int = 0, )  /**@@ -117,6 +123,9 @@ interface SettingsActions {     /** Same, restricted to one calendar. Read-only calendars are exportable too. */     fun exportCalendarIcs(calendarId: Long) {} +    /** Publish a fresh calendar snapshot to the wear companion now. */+    fun syncWearNow() {}+     /** No-op settings actions used by previews, which render the screen without behaviour. */     companion object {         val Noop: SettingsActions = object : SettingsActions {}
calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarViewModel.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarViewModel.kt b/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarViewModel.ktindex 8ad1e1a672..fd7bf8412c 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarViewModel.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/platform/CalendarViewModel.kt@@ -45,6 +45,14 @@ class CalendarViewModel(application: Application) :     private val _events = MutableStateFlow<List<Event>>(emptyList())     val events: StateFlow<List<Event>> = _events.asStateFlow() +    /** Wear companion presence + last-sync truth, owned by the sync singleton. */+    val wearSyncState = com.vayunmathur.calendar.sync.WearCalendarSync.get(application).state++    /** Manual wear sync from Settings. */+    override fun syncWearNow() {+        com.vayunmathur.calendar.sync.WearCalendarSync.get(getApplication()).syncNow()+    }+     private val _calendars = MutableStateFlow<List<Calendar>>(emptyList())     val calendars: StateFlow<List<Calendar>> = _calendars.asStateFlow() @@ -287,6 +295,12 @@ class CalendarViewModel(application: Application) :     }      init {+        val wearSync = com.vayunmathur.calendar.sync.WearCalendarSync.get(application)+        wearSync.start()+        // Calendar changes republish the wear snapshot (coalesced in the sync).+        viewModelScope.launch {+            events.collect { wearSync.onCalendarChanged() }+        }         loadData()         viewModelScope.launch {             dataStore.stringFlow("default_calendar_layout").collect { saved ->
calendar/src/main/java/com/vayunmathur/calendar/service/WearCalendarListenerService.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/service/WearCalendarListenerService.kt b/calendar/src/main/java/com/vayunmathur/calendar/service/WearCalendarListenerService.ktnew file mode 100644index 0000000000..09ac70d15c--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/service/WearCalendarListenerService.kt@@ -0,0 +1,27 @@+package com.vayunmathur.calendar.service++import com.google.android.gms.wearable.MessageEvent+import com.google.android.gms.wearable.WearableListenerService+import com.vayunmathur.calendar.domain.WearCalendarProtocol+import com.vayunmathur.calendar.sync.WearCalendarSync+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Phone listener for watch-originated messages while the UI is not running.+ * The only one is [WearCalendarProtocol.REQUEST_SYNC_PATH]: the watch asks+ * for a fresh snapshot. There are no watch-originated event writes to handle.+ */+class WearCalendarListenerService : WearableListenerService() {++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    override fun onMessageReceived(messageEvent: MessageEvent) {+        if (messageEvent.path != WearCalendarProtocol.REQUEST_SYNC_PATH) return+        val sync = WearCalendarSync.get(this)+        sync.start()+        scope.launch { sync.publishSnapshot() }+    }+}
calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.kt b/calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.ktnew file mode 100644index 0000000000..879908f6d7--- /dev/null+++ b/calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.kt@@ -0,0 +1,216 @@+package com.vayunmathur.calendar.sync++import android.content.Context+import com.google.android.gms.tasks.Task+import com.google.android.gms.wearable.CapabilityClient+import com.google.android.gms.wearable.CapabilityInfo+import com.google.android.gms.wearable.DataClient+import com.google.android.gms.wearable.DataEvent+import com.google.android.gms.wearable.DataEventBuffer+import com.google.android.gms.wearable.DataMapItem+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.calendar.data.Calendar+import com.vayunmathur.calendar.data.Event+import com.vayunmathur.calendar.data.Instance+import com.vayunmathur.calendar.domain.WearCalendarEvent+import com.vayunmathur.calendar.domain.WearCalendarProtocol+import com.vayunmathur.calendar.domain.WearWatchState+import com.vayunmathur.calendar.domain.buildWearSnapshot+import com.vayunmathur.calendar.domain.wearCompanionPresent+import com.vayunmathur.library.log.Log+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+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.suspendCancellableCoroutine+import kotlinx.coroutines.withContext+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.toLocalDateTime+import kotlinx.serialization.encodeToString+import kotlin.time.Clock+import kotlin.time.Duration.Companion.days+import kotlin.time.Instant++/** Await a Play services [Task] without taking a coroutines-play-services dependency. */+private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->+    addOnSuccessListener { cont.resume(it) }+    addOnFailureListener { cont.resumeWithException(it) }+}++/** Phone-side wear status the Settings screen shows; absence is a normal state, never an error. */+data class WearSyncState(+    val companionPresent: Boolean = false,+    /** When the phone last published a snapshot, epoch millis; null when never. */+    val lastPublishedAtMillis: Long? = null,+    /** generatedAtMillis the watch last reported applying, epoch millis; null when unreported. */+    val lastWatchAppliedAtMillis: Long? = null,+    val lastPublishedEventCount: Int = 0,+)++/**+ * Phone side of the wear sync: capability discovery, snapshot publish, and+ * watch-state intake.+ *+ * Every Wearable call is wrapped so "no Play services / no watch / watch+ * without the companion" is a normal state ([WearSyncState.companionPresent]+ * = false), never a crash. The Data Layer only connects the two calendars+ * because they share the package name `com.vayunmathur.calendar` and a+ * signing certificate — dev builds both use the debug key, release builds+ * both use the same release key.+ */+class WearCalendarSync private constructor(context: Context) :+    CapabilityClient.OnCapabilityChangedListener,+    DataClient.OnDataChangedListener {++    /** Holds singleton access. */+    companion object {+        private const val TAG = "WearCalendarSync"+        private const val KEY_JSON = "json"+        private const val KEY_SENT_AT = "sent_at"++        @Volatile+        private var instance: WearCalendarSync? = null++        /** The process-wide sync (ViewModel and listener service must agree on one). */+        fun get(context: Context): WearCalendarSync = instance ?: synchronized(this) {+            instance ?: WearCalendarSync(context.applicationContext).also { instance = it }+        }+    }++    private val appContext = context.applicationContext+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    private val _state = MutableStateFlow(WearSyncState())++    /** Current wear presence + last-sync truth for the UI. */+    val state: StateFlow<WearSyncState> = _state.asStateFlow()++    private var started = false+    private var pendingPublish: Job? = null++    /** Begin capability/data listening; no-op when already started or unavailable. */+    fun start() {+        if (started) return+        started = true+        runCatching {+            Wearable.getCapabilityClient(appContext)+                .addListener(this, WearCalendarProtocol.CAPABILITY)+            Wearable.getDataClient(appContext).addListener(this)+        }.onFailure { Log.status(TAG, "Wearable listeners unavailable: ${it.message}") }+        scope.launch { refreshCapability() }+    }++    override fun onCapabilityChanged(capabilityInfo: CapabilityInfo) {+        updatePresence(capabilityInfo.nodes.map { it.id })+    }++    override fun onDataChanged(dataEvents: DataEventBuffer) {+        for (event in dataEvents) {+            if (event.type != DataEvent.TYPE_CHANGED) continue+            val item = event.dataItem+            if (item.uri.path != WearCalendarProtocol.WATCH_STATE_PATH) continue+            val raw = runCatching {+                DataMapItem.fromDataItem(item).dataMap.getString(KEY_JSON)+            }.getOrNull() ?: continue+            val watchState = runCatching {+                WearCalendarProtocol.json.decodeFromString<WearWatchState>(raw)+            }.getOrNull() ?: continue+            _state.update {+                it.copy(lastWatchAppliedAtMillis = watchState.appliedGeneratedAtMillis+                    .takeIf { applied -> applied > 0L })+            }+        }+    }++    /** Calendar data changed: republish shortly, coalescing bursts (imports, bulk edits). */+    fun onCalendarChanged() {+        if (!_state.value.companionPresent) return+        pendingPublish?.cancel()+        pendingPublish = scope.launch {+            delay(1_000)+            publishSnapshot()+        }+    }++    /** Manual sync from Settings; publishes even when presence is stale/unknown. */+    fun syncNow() {+        scope.launch { publishSnapshot() }+    }++    /** Build the bounded snapshot from the provider and publish it on DataClient. */+    suspend fun publishSnapshot() {+        val snapshot = withContext(Dispatchers.IO) { buildSnapshot() } ?: return+        runCatching {+            val request = PutDataMapRequest.create(WearCalendarProtocol.SNAPSHOT_PATH).apply {+                dataMap.putString(KEY_JSON, WearCalendarProtocol.json.encodeToString(snapshot))+                dataMap.putLong(KEY_SENT_AT, snapshot.generatedAtMillis)+            }.asPutDataRequest().setUrgent()+            Wearable.getDataClient(appContext).putDataItem(request).awaitTask()+            _state.update {+                it.copy(+                    lastPublishedAtMillis = snapshot.generatedAtMillis,+                    lastPublishedEventCount = snapshot.events.size,+                )+            }+        }.onFailure { Log.status(TAG, "publish snapshot failed: ${it.message}") }+    }++    private suspend fun refreshCapability() {+        runCatching {+            val info = Wearable.getCapabilityClient(appContext)+                .getCapability(WearCalendarProtocol.CAPABILITY, CapabilityClient.FILTER_REACHABLE)+                .awaitTask()+            updatePresence(info.nodes.map { it.id })+        }.onFailure { Log.status(TAG, "capability lookup unavailable: ${it.message}") }+    }++    private fun updatePresence(nodeIds: List<String>) {+        val present = wearCompanionPresent(nodeIds)+        val wasPresent = _state.value.companionPresent+        _state.update { it.copy(companionPresent = present) }+        if (present && !wasPresent) syncNow()+    }++    private fun buildSnapshot(): com.vayunmathur.calendar.domain.WearCalendarSnapshot? =+        runCatching {+            val now = Clock.System.now()+            val zone = TimeZone.currentSystemDefault()+            val today = now.toLocalDateTime(zone).date+            val windowStart = today.atStartOfDayIn(zone)+            val windowEnd = windowStart + WearCalendarProtocol.WINDOW_DAYS.days+            val instances = Instance.getVisibleInstances(appContext, windowStart, windowEnd)+            val eventsById = Event.getAllEvents(appContext).associateBy { it.id }+            val calendarsById = Ca

Diff truncated.