Modern Apps git

← Modern-Apps.git

wearlink: first-party phone-watch protocol, GMS Data Layer removed

Commit
c7d57293d792d623f2dc976315d2d88f8ff0f254
Author
Vayun Mathur <[email protected]>
When
2026-11-24 18:52 UTC (11 days ago)
Parents
65ec1f7
library/wearlink implements our own protocol over
Bluetooth RFCOMM: length-prefixed framing, nonce-bound
handshake requiring the same signing certificate hash
(proves the same-signed app on the paired device - the
strongest proof available to third-party apps), data
items with chunking/reassembly, and resumable byte
streams (STREAM_ACK durable offsets, re-hashed prefix,
never whole-in-memory). Bounded sizes, 1s->30s
reconnect backoff, all IO off the main thread.

App Store, Calendar, and Contacts (both sides) migrated
behind their existing seams; all Wearable/Data/Message/
Channel/Capability call sites, GMS listener services,
wear_capabilities resources, and the
play-services-wearable dependency (all six build files
+ version catalog) are deleted. Zero Play services.

Honest degradations vs GMS, documented in code: no
background system wakeups (app-lifecycle-bound), no
store-and-forward, presence = completed handshake.

Verified: wearlink unit tests + all six modules'
protocol tests green; compiles/assembles + lints
green. One calendar full-suite failure in an unrelated
holiday-UI test flagged as likely pre-existing.

Diff

appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex 522153d20d..1934c94ffa 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -142,6 +142,7 @@ dependencies {     implementation(libs.androidx.datastore.preferences)     implementation(project(":library:image"))     implementation(project(":library:tv"))+    implementation(project(":library:wearlink"))     // APK source-stamp verification. The stamp is a second signing identity that     // survives Play App Signing re-signing, so it can be pinned per package where the     // APK signing key (held by Google) cannot be.@@ -152,7 +153,6 @@ dependencies {     // 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/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 2c993164e7..7c40eb78bd 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -52,6 +52,7 @@ class MainActivity : MaActivity() {     override fun onCreateBeforeContent() {         // STANDARD includes GTS R1-R4 (needed for Play Store -> play.google.com / android.clients.google.com)         // + ISRG X1/X2 (F-Droid) + DigiCert G2/G3 (GitHub). Covers all appstore hosts without full system ~140 roots.+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         NetworkClient.init(this, TrustBundle.STANDARD)         UpdateCheckWorker.schedule(this)         // Listing artwork (iconUrl) loads over HTTP(S) through the shared image
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.ktindex 93539d848e..64b8b53344 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/domain/WearSyncProtocol.kt@@ -9,24 +9,23 @@ 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+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: 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],+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the small state documents: [CATALOG_PATH] phone ->+ *   watch and [WATCH_STATE_PATH] watch -> phone. Delivery needs a live+ *   session; each side persists what it receives and republishes on+ *   reconnect, reconciling the two sides when they meet again.+ * - Messages carry 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.+ * - A stream ([apkChannelPath]) carries the APK itself, verified against+ *   the preceding offer's size+SHA-256 before PackageInstaller sees it.  *  * Install honesty: nothing here can install silently. The watch verifies the  * stream against [ApkOffer.sha256], then a person on the watch taps Install@@ -34,41 +33,41 @@ import kotlinx.serialization.json.Json  * 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. */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "appstore_wear_store" -    /** DataClient path (phone -> watch): the [WearCatalog] JSON snapshot. */+    /** Data-item path (phone -> watch): the [WearCatalog] JSON snapshot. */     const val CATALOG_PATH = "/appstore/catalog" -    /** DataClient path (watch -> phone): the [WatchState] JSON snapshot. */+    /** Data-item path (watch -> phone): the [WatchState] JSON snapshot. */     const val WATCH_STATE_PATH = "/appstore/watch-state" -    /** MessageClient path (phone -> watch): an [ApkOffer] precedes every channel. */+    /** Message path (phone -> watch): an [ApkOffer] precedes every stream. */     const val OFFER_PATH = "/appstore/apk-offer" -    /** MessageClient path (watch -> phone): an [InstallResult] after the OS answers. */+    /** Message 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]. */+    /** Message 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+     * Message 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. */+    /** Stream 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. */+    /** Stream 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. */+    /** The package a stream path streams, or null when [path] is not an APK stream. */     fun packageFromChannelPath(path: String): String? =         path.takeIf { it.startsWith(APK_CHANNEL_PREFIX) }             ?.removePrefix(APK_CHANNEL_PREFIX)@@ -93,7 +92,7 @@ data class WearCatalogApp( data class WearCatalog(val apps: List<WearCatalogApp> = emptyList())  /**- * Metadata announced over MessageClient immediately before an APK channel opens.+ * Metadata announced by message immediately before an APK stream opens.  * The watch refuses bytes that do not match [sizeBytes]/[sha256] — the channel  * itself carries no metadata, so this offer is the integrity contract.  */
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.ktindex 01c249d6d7..db6ab48709 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/sync/WearSyncManager.kt@@ -1,17 +1,6 @@ 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@@ -26,13 +15,15 @@ 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 com.vayunmathur.library.wearlink.FileStreamSource+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState 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@@ -40,103 +31,81 @@ 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.+ * Phone side of the wear sync over WearLink (RFCOMM, :library:wearlink):+ * presence is a completed cert-bound handshake, catalog/watch-state are+ * data items, offers/results are messages and APK bytes are a stream.  *- * 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.+ * "No Bluetooth permission / Bluetooth off / no watch / watch without the+ * wear store" is a normal state ([watchConnected] = false), never a crash.+ * Delivery is app-lifecycle-bound: unlike the old Play-services listener,+ * nothing wakes this process when the watch speaks first.  */ 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 listener = object : WearLinkListener {+        override fun onMessage(path: String, body: ByteArray) {+            if (path != WearSyncProtocol.INSTALL_RESULT_PATH) return+            val result = runCatching {+                WearSyncProtocol.json.decodeFromString<InstallResult>(body.decodeToString())+            }.getOrNull() ?: return+            applyEvent(+                result.packageName,+                PhoneWearEvent.ResultReceived(result),+                message = result.message.takeIf { it.isNotBlank() },+            )+        }++        override fun onData(path: String, body: ByteArray) {+            if (path != WearSyncProtocol.WATCH_STATE_PATH) return+            val watchState = runCatching {+                WearSyncProtocol.json.decodeFromString<WatchState>(body.decodeToString())+            }.getOrNull() ?: return+            reconcile(watchState)+        }+    }++    private val node = WearLinkNode(context, WearSyncProtocol.CAPABILITY, listener)+     private val _watchConnected = MutableStateFlow(false) -    /** True only when a reachable node advertises the wear store's capability. */+    /** True only when a WearLink handshake with the wear store completed. */     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)+        scope.launch {+            node.state.collect { state ->+                val connected = state is WearLinkState.Connected+                _watchConnected.value = connected+                if (!connected) {+                    _states.update { current ->+                        current.mapValues { (_, s) ->+                            PhoneWearMachine.reduce(s, PhoneWearEvent.WatchGone)+                        }+                    }+                }+            }         }-    }--    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() },-        )+        node.start()     }      /** Publish the watch-eligible catalog snapshot so the watch can list it standalone. */@@ -155,33 +124,27 @@ class WearSyncManager(                 },         )         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}") }+            val sent = node.putData(+                WearSyncProtocol.CATALOG_PATH,+                WearSyncProtocol.json.encodeToString(catalog).encodeToByteArray(),+            )+            if (!sent) Log.status(TAG, "catalog publish not delivered (no live WearLink session)")         }     } -    /** 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.+     * the [ApkOffer], then stream the raw bytes. The watch does the verifying;+     * this side reports SENDING -> ON_WATCH/FAILED honestly.      */     fun sendToWatch(app: UnifiedApp) {-        val nodeId = watchNodeId-        if (nodeId == null) {+        if (!node.isConnected) {             applyEvent(-                app.packageName, PhoneWearEvent.WatchGone, "no watch with the Wear OS App Store is connected",+                app.packageName, PhoneWearEvent.WatchGone,+                "no watch with the Wear OS App Store is connected",             )             return         }@@ -200,23 +163,18 @@ class WearSyncManager(                     sizeBytes = file.length(),                     sha256 = ApkHash.sha256Hex(file),                 )-                Wearable.getMessageClient(context).sendMessage(-                    nodeId, WearSyncProtocol.OFFER_PATH,+                val offered = node.sendMessage(+                    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() }-                }+                )+                if (!offered) throw IOException("watch is not connected")+                val streamed = node.sendStream(+                    WearSyncProtocol.apkChannelPath(app.packageName),+                    FileStreamSource(file, offer.sha256),+                )+                if (!streamed) throw IOException("APK transfer failed")                 applyEvent(app.packageName, PhoneWearEvent.SendFinished(true))-                requestWatchState(nodeId)+                node.sendMessage(WearSyncProtocol.REQUEST_STATE_PATH, byteArrayOf())             } catch (expected: Exception) {                 Log.error(TAG, "send ${app.packageName} failed", expected)                 applyEvent(@@ -228,20 +186,14 @@ class WearSyncManager(         }     } -    /**-     * 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.-     */+    /** Ask the watch to surface its Install action. The wearer still taps + confirms. */     fun requestInstall(packageName: String) {-        val nodeId = watchNodeId ?: return+        if (!node.isConnected) 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}") }+            node.sendMessage(+                WearSyncProtocol.REQUEST_INSTALL_PATH, packageName.encodeToByteArray(),+            )         }     } @@ -293,7 +245,6 @@ class WearSyncManager(                 )             }         }-        // Packages the watch knows but this side has never tracked still reconcile.         _states.update { current ->             var next = current             for (entry in watchState.apps) {@@ -313,40 +264,6 @@ class WearSyncManager(     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,@@ -361,7 +278,6 @@ class WearSyncManager(         }     } -    /** 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/wear/AGENTS.md
diff --git a/appstore/wear/AGENTS.md b/appstore/wear/AGENTS.mdindex 99b065f379..2fca7d65ee 100644--- a/appstore/wear/AGENTS.md+++ b/appstore/wear/AGENTS.md@@ -8,11 +8,11 @@ - 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+Wear OS companion of the phone App Store (`:appstore`). This module+deliberately uses `applicationId = "com.vayunmathur.appstore"` (the phone+app's) with the shared dev/release signing from the convention plugins:+WearLink's handshake token requires the same signing certificate on both+sides, so changing either breaks phone<->watch sync. Bootstrap is a one-time ADB sideload of this APK onto the watch.  ## Protocol@@ -20,10 +20,12 @@ one-time ADB sideload of this APK onto the watch. (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+- Catalog + watch-state sync: WearLink data items (`/appstore/catalog`, `/appstore/watch-state`)+- Offers / install requests / results: WearLink messages+- APK bytes: WearLink stream (`/appstore/apk/<package>`), verified size+SHA-256   against the preceding offer before PackageInstaller ever sees them+- Transport: :library:wearlink (RFCOMM, no Play services); delivery is+  app-lifecycle-bound — no system listener wakes a dead process  ## Install honesty A normal Wear OS app **cannot silently install**. Verified APKs wait in
appstore/wear/build.gradle.kts
diff --git a/appstore/wear/build.gradle.kts b/appstore/wear/build.gradle.ktsindex acec432974..6cf5bba2d0 100644--- a/appstore/wear/build.gradle.kts+++ b/appstore/wear/build.gradle.kts@@ -25,8 +25,8 @@ android { 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)+    implementation(project(":library:wearlink"))     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.xmlindex 34a4e1360a..32a3593ec6 100644--- a/appstore/wear/src/main/AndroidManifest.xml+++ b/appstore/wear/src/main/AndroidManifest.xml@@ -38,26 +38,9 @@             </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>+        <!-- WearLink (RFCOMM) delivery is bound to the app process: the+             node starts with the activity above. No system listener service+             (that was a Play-services mechanism) wakes a dead process. -->          <receiver             android:name=".platform.InstallResultReceiver"
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.ktindex 3119689f69..f2e3544cc4 100644--- 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.kt@@ -1,8 +1,6 @@ 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@@ -12,6 +10,7 @@ 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.appstore.wear.sync.WearLinkBridge import com.vayunmathur.library.log.Log import java.io.File import kotlinx.coroutines.flow.MutableStateFlow@@ -42,8 +41,6 @@ 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@@ -118,7 +115,7 @@ class WearStore private constructor(private val context: Context) {             ?.sorted()             ?: emptyList() -    /** Replace the catalog snapshot (DataClient push from the phone). */+    /** Replace the catalog snapshot (WearLink data item from the phone). */     fun setCatalog(catalog: WearCatalog) {         _catalog.value = catalog         runCatching { catalogFile.writeText(WearSyncProtocol.json.encodeToString(catalog)) }@@ -156,13 +153,10 @@ class WearStore private constructor(private val context: Context) {         _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() {+    /** This watch's truth, for the phone's per-app sync reconciliation. */+    fun watchState(): WatchState {         val packages = (_catalog.value.apps.map { it.packageName } + downloadedPackages()).distinct()-        val state = WatchState(+        return WatchState(             packages.map { pkg ->                 WatchAppEntry(                     packageName = pkg,@@ -173,13 +167,14 @@ class WearStore private constructor(private val context: Context) {                 )             },         )-        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}") }+    }++    /**+     * Publish [watchState] to the phone ([WearSyncProtocol.WATCH_STATE_PATH])+     * over WearLink; a no-op delivery-wise when no session is live.+     */+    fun publishWatchState() {+        WearLinkBridge.publishWatchState(context)     }      private fun downloadedVersionOf(packageName: String): Long =
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.ktindex 1e81cacc17..079dde4bbe 100644--- 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.kt@@ -9,24 +9,23 @@ 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+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: 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],+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the small state documents: [CATALOG_PATH] phone ->+ *   watch and [WATCH_STATE_PATH] watch -> phone. Delivery needs a live+ *   session; each side persists what it receives and republishes on+ *   reconnect, reconciling the two sides when they meet again.+ * - Messages carry 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.+ * - A stream ([apkChannelPath]) carries the APK itself, verified against+ *   the preceding offer's size+SHA-256 before PackageInstaller sees it.  *  * Install honesty: nothing here can install silently. The watch verifies the  * stream against [ApkOffer.sha256], then a person on the watch taps Install@@ -34,41 +33,41 @@ import kotlinx.serialization.json.Json  * 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. */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "appstore_wear_store" -    /** DataClient path (phone -> watch): the [WearCatalog] JSON snapshot. */+    /** Data-item path (phone -> watch): the [WearCatalog] JSON snapshot. */     const val CATALOG_PATH = "/appstore/catalog" -    /** DataClient path (watch -> phone): the [WatchState] JSON snapshot. */+    /** Data-item path (watch -> phone): the [WatchState] JSON snapshot. */     const val WATCH_STATE_PATH = "/appstore/watch-state" -    /** MessageClient path (phone -> watch): an [ApkOffer] precedes every channel. */+    /** Message path (phone -> watch): an [ApkOffer] precedes every stream. */     const val OFFER_PATH = "/appstore/apk-offer" -    /** MessageClient path (watch -> phone): an [InstallResult] after the OS answers. */+    /** Message 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]. */+    /** Message 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+     * Message 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. */+    /** Stream 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. */+    /** Stream 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. */+    /** The package a stream path streams, or null when [path] is not an APK stream. */     fun packageFromChannelPath(path: String): String? =         path.takeIf { it.startsWith(APK_CHANNEL_PREFIX) }             ?.removePrefix(APK_CHANNEL_PREFIX)@@ -93,7 +92,7 @@ data class WearCatalogApp( data class WearCatalog(val apps: List<WearCatalogApp> = emptyList())  /**- * Metadata announced over MessageClient immediately before an APK channel opens.+ * Metadata announced by message immediately before an APK stream opens.  * The watch refuses bytes that do not match [sizeBytes]/[sha256] — the channel  * itself carries no metadata, so this offer is the integrity contract.  */
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.ktindex 1599e2f7a7..59fe4b5a6f 100644--- 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.kt@@ -5,13 +5,10 @@ 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.@@ -76,16 +73,6 @@ class InstallResultReceiver : BroadcastReceiver() {     }      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}") }+        com.vayunmathur.appstore.wear.sync.WearLinkBridge.reportResult(context, result)     } }
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.ktdeleted file mode 100644index cebe73ff50..0000000000--- a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/service/WearDataListenerService.kt+++ /dev/null@@ -1,172 +0,0 @@-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/sync/WearLinkBridge.kt
diff --git a/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/sync/WearLinkBridge.kt b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..6a10790911--- /dev/null+++ b/appstore/wear/src/main/java/com/vayunmathur/appstore/wear/sync/WearLinkBridge.kt@@ -0,0 +1,192 @@+package com.vayunmathur.appstore.wear.sync++import android.content.Context+import android.content.Intent+import com.vayunmathur.appstore.wear.data.WearStore+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 com.vayunmathur.library.wearlink.StreamSink+import com.vayunmathur.library.wearlink.StreamHeader+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import java.io.File+import java.io.FileInputStream+import java.io.FileOutputStream+import java.io.InputStream+import java.io.OutputStream+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink: catalog data items, APK offers, APK streams and+ * install requests from the phone. Replaces the old Play-services listener+ * service — delivery is now bound to this process being alive (the activity+ * starts the node; there is no system wakeup for a dead process).+ *+ * APK bytes only land in app-private storage after the stream verifies+ * against its [ApkOffer] (size, then SHA-256, enforced by the WearLink+ * stream layer against the header the phone sent from the same file).+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"++    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    /** The live node, created (and started) on first use. */+    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearSyncProtocol.CATALOG_PATH) return+                runCatching {+                    WearSyncProtocol.json.decodeFromString<WearCatalog>(body.decodeToString())+                }.onSuccess { WearStore.get(context).setCatalog(it) }+                    .onFailure { Log.status(TAG, "bad catalog push: ${it.message}") }+            }++            override fun onMessage(path: String, body: ByteArray) {+                val store = WearStore.get(context)+                when (path) {+                    WearSyncProtocol.OFFER_PATH -> runCatching {+                        WearSyncProtocol.json.decodeFromString<ApkOffer>(body.decodeToString())+                    }.onSuccess { store.noteOffer(it) }+                        .onFailure { Log.status(TAG, "bad apk offer: ${it.message}") }++                    WearSyncProtocol.REQUEST_STATE_PATH -> publishWatchState(context)++                    WearSyncProtocol.REQUEST_INSTALL_PATH -> {+                        store.noteInstallRequested(body.decodeToString())+                        publishWatchState(context)+                        runCatching {+                            context.startActivity(+                                Intent(context, WearMainActivity::class.java)+                                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+                            )+                        }+                    }+                }+            }++            override fun onStreamOpen(path: String, header: StreamHeader): StreamSink? {+                val packageName = WearSyncProtocol.packageFromChannelPath(path) ?: return null+                val store = WearStore.get(context)+                val offer = store.offerFor(packageName) ?: run {+                    Log.error(TAG, "stream for $packageName without an offer; refusing")+                    reportFailure(context, packageName, 0L, "no download offer from the phone")+                    return null+                }+                if (header.totalSize != offer.sizeBytes || !header.sha256.equals(offer.sha256, ignoreCase = true)) {+                    reportFailure(+                        context, packageName, offer.versionCode,+                        "stream header does not match the phone's offer",+                    )+                    return null+                }+                store.applyEvent(packageName, WatchAppEvent.ReceiveStarted)+                return ApkStreamSink(context, store, packageName, offer)+            }+        }+        return WearLinkNode(context, WearSyncProtocol.CAPABILITY, listener).also { it.start() }+    }++    /** Publish this watch's state data item through the live node, if any. */+    fun publishWatchState(context: Context) {+        val store = WearStore.get(context)+        scope.launch {+            val sent = get(context).putData(+                WearSyncProtocol.WATCH_STATE_PATH,+                WearSyncProtocol.json.encodeToString(store.watchState()).encodeToByteArray(),+            )+            if (!sent) Log.status(TAG, "watch state not delivered (no live session)")+        }+    }++    /** Send an install result message to the phone, if a session is live. */+    fun reportResult(context: Context, result: InstallResult) {+        scope.launch {+            get(context).sendMessage(+                WearSyncProtocol.INSTALL_RESULT_PATH,+                WearSyncProtocol.json.encodeToString(result).encodeToByteArray(),+            )+        }+    }++    private fun reportFailure(+        context: Context,+        packageName: String,+        versionCode: Long,+        message: String,+    ) {+        reportResult(context, InstallResult(packageName, versionCode, false, message))+    }++    /**+     * Writes a stream into `<pkg>.partial`, resuming a retained partial+     * (its bytes are re-hashed by the WearLink receiver), and on a verified+     * close renames it into place. Unverified bytes are deleted, never+     * handed to PackageInstaller.+     */+    private class ApkStreamSink(+        private val context: Context,+        private val store: WearStore,+        private val packageName: String,+        private val offer: ApkOffer,+    ) : StreamSink {+        private val target: File = store.apkFile(packageName)+        private val partial: File = File(target.parentFile, "$packageName.partial")+        private var output: OutputStream? = null++        override val resumeOffset: Long =+            if (partial.exists() && partial.length() in 1 until offer.sizeBytes) {+                partial.length()+            } else {+                0L+            }++        override fun prefixStream(): InputStream? =+            if (resumeOffset > 0) FileInputStream(partial) else null++        override fun write(bytes: ByteArray, offset: Long) {+            val out = output ?: FileOutputStream(partial, resumeOffset > 0).also { output = it }+            out.write(bytes)+        }++        override fun close(verified: Boolean) {+            runCatching { output?.close() }+            output = null+            if (verified) {+                if (partial.renameTo(target)) {+                    store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = true))+                } else {+                    store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = false))+                }+            } else {+                partial.delete()+                store.applyEvent(packageName, WatchAppEvent.ReceiveFinished(verified = false))+                WearLinkBridge.reportFailure(+                    context, packageName, offer.versionCode,+                    "download did not match the size/hash the phone announced",+                )+            }+            store.clearOffer(packageName)+            WearLinkBridge.publishWatchState(context)+        }+    }+}
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.ktindex db0d556676..a00b43bbd8 100644--- 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.kt@@ -36,7 +36,9 @@ class WearMainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         val store = WearStore.get(this)+        com.vayunmathur.appstore.wear.sync.WearLinkBridge.get(this)         store.publishWatchState()         setContent {             MaterialTheme {
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.xmldeleted file mode 100644index 3904a1f876..0000000000--- a/appstore/wear/src/main/res/values/wear_capabilities.xml+++ /dev/null@@ -1,9 +0,0 @@-<?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>
calendar-wear/AGENTS.md
diff --git a/calendar-wear/AGENTS.md b/calendar-wear/AGENTS.mdindex 147b7c0558..b66b8672c3 100644--- a/calendar-wear/AGENTS.md+++ b/calendar-wear/AGENTS.md@@ -8,11 +8,11 @@ - Entry file: ui/WearMainActivity.kt  ## Why this module exists (read before changing identity)-Wear OS companion of the phone Calendar (`:calendar`). The Wearable Data-Layer only connects apps sharing a **package name and signing certificate**,-so this module deliberately uses `applicationId = "com.vayunmathur.calendar"`-(the phone app's) with the shared dev/release signing from the convention-plugins. Changing either breaks phone<->watch sync silently. Bootstrap is a+Wear OS companion of the phone Calendar (`:calendar`). This module+deliberately uses `applicationId = "com.vayunmathur.calendar"` (the phone+app's) with the shared dev/release signing from the convention plugins:+WearLink's handshake token requires the same signing certificate on both+sides, so changing either breaks phone<->watch sync. Bootstrap is a one-time ADB sideload of this APK onto the watch.  ## Protocol@@ -20,8 +20,9 @@ one-time ADB sideload of this APK onto the watch. depend on another app module). Change both copies together; each side's `WearCalendarProtocolTest` pins the same golden JSON. -- Snapshot + watch-state sync: DataClient (`/calendar/snapshot`, `/calendar/watch-state`)-- Sync request: MessageClient (`/calendar/request-sync`), watch -> phone only+- Snapshot + watch-state sync: WearLink data items (`/calendar/snapshot`, `/calendar/watch-state`)+- Sync request: WearLink message (`/calendar/request-sync`), watch -> phone only+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound  ## What the watch can and cannot do Read-only. It renders today's agenda, upcoming events and event detail from
calendar-wear/build.gradle.kts
diff --git a/calendar-wear/build.gradle.kts b/calendar-wear/build.gradle.ktsindex b12bbbfa7a..de8de9163a 100644--- a/calendar-wear/build.gradle.kts+++ b/calendar-wear/build.gradle.kts@@ -24,8 +24,8 @@ android { dependencies {     // Watch side of the Wear OS sync (see domain/WearCalendarProtocol.kt, the     // copy of the phone protocol it must stay in step with).-    implementation(libs.play.services.wearable)     implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))     testImplementation(libs.kotlin.test)     testImplementation(libs.kotlin.test.junit) }
calendar-wear/src/main/AndroidManifest.xml
diff --git a/calendar-wear/src/main/AndroidManifest.xml b/calendar-wear/src/main/AndroidManifest.xmlindex 3dbf77358f..7ccb8c3001 100644--- a/calendar-wear/src/main/AndroidManifest.xml+++ b/calendar-wear/src/main/AndroidManifest.xml@@ -35,15 +35,6 @@             </intent-filter>         </activity> -        <!-- Receives snapshot updates from the phone, including while the-             UI is not running. -->-        <service-            android:name=".service.WearCalendarListenerService"-            android:exported="true">-            <intent-filter>-                <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />-                <data android:scheme="wear" android:host="*" android:pathPrefix="/calendar/snapshot" />-            </intent-filter>-        </service>+        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->     </application> </manifest>
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.ktindex 7cf3134cee..2fd11b25a4 100644--- a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt@@ -1,11 +1,10 @@ package com.vayunmathur.calendar.wear.data  import android.content.Context-import com.google.android.gms.wearable.PutDataMapRequest-import com.google.android.gms.wearable.Wearable import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol import com.vayunmathur.calendar.wear.domain.WearCalendarSnapshot import com.vayunmathur.calendar.wear.domain.WearWatchState+import com.vayunmathur.calendar.wear.sync.WearLinkBridge import com.vayunmathur.library.log.Log import java.io.File import kotlinx.coroutines.flow.MutableStateFlow@@ -23,8 +22,6 @@ class WearCalendarStore private constructor(private val context: Context) {     /** Holds singleton access. */     companion object {         private const val TAG = "WearCalendarStore"-        private const val KEY_JSON = "json"-        private const val KEY_SENT_AT = "sent_at"          @Volatile         private var instance: WearCalendarStore? = null@@ -42,7 +39,7 @@ class WearCalendarStore private constructor(private val context: Context) {     /** Last snapshot from the phone; empty until the first sync. */     val snapshot: StateFlow<WearCalendarSnapshot> = _snapshot.asStateFlow() -    /** Replace the stored snapshot (DataClient push from the phone) and tell the phone it landed. */+    /** Replace the stored snapshot (WearLink data item from the phone) and tell the phone it landed. */     fun setSnapshot(snapshot: WearCalendarSnapshot) {         _snapshot.value = snapshot         runCatching { snapshotFile.writeText(WearCalendarProtocol.json.encodeToString(snapshot)) }@@ -52,18 +49,7 @@ class WearCalendarStore private constructor(private val context: Context) {      /** Publish what this watch is rendering from, so the phone can show last-sync truth. */     fun publishWatchState() {-        val current = _snapshot.value-        val state = WearWatchState(-            appliedGeneratedAtMillis = current.generatedAtMillis,-            eventCount = current.events.size,-        )-        runCatching {-            val request = PutDataMapRequest.create(WearCalendarProtocol.WATCH_STATE_PATH).apply {-                dataMap.putString(KEY_JSON, WearCalendarProtocol.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}") }+        WearLinkBridge.publishWatchState(context, _snapshot.value)     }      private fun loadSnapshot(): WearCalendarSnapshot = runCatching {
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.ktindex 25628e4e01..696c85c282 100644--- a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt@@ -6,37 +6,35 @@ 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+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: 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]+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the snapshot: [SNAPSHOT_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. Delivery needs a live session;+ *   each side persists what it receives and republishes on reconnect.+ * - Messages carry 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. */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "calendar_wear_companion" -    /** DataClient path (phone -> watch): the [WearCalendarSnapshot] JSON. */+    /** Data-item path (phone -> watch): the [WearCalendarSnapshot] JSON. */     const val SNAPSHOT_PATH = "/calendar/snapshot" -    /** DataClient path (watch -> phone): the [WearWatchState] JSON. */+    /** Data-item 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. */+    /** Message 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. */@@ -46,9 +44,9 @@ object WearCalendarProtocol {     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.+     * Largest snapshot JSON, in UTF-8 bytes. Deliberately kept near the old+     * 100 KB DataItem ceiling: a bounded snapshot is what the watch can+     * store/render, and WearLink chunks it transparently either way.      */     const val MAX_JSON_BYTES = 90_000 
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.ktdeleted file mode 100644index e2d91869a4..0000000000--- a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt+++ /dev/null@@ -1,38 +0,0 @@-package com.vayunmathur.calendar.wear.service--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.WearableListenerService-import com.vayunmathur.calendar.wear.data.WearCalendarStore-import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol-import com.vayunmathur.calendar.wear.domain.WearCalendarSnapshot-import com.vayunmathur.library.log.Log--/** Receives the phone's snapshot DataItem, including while the UI is not running. */-class WearCalendarListenerService : WearableListenerService() {--    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.SNAPSHOT_PATH) continue-            val raw = runCatching {-                DataMapItem.fromDataItem(item).dataMap.getString(KEY_JSON)-            }.getOrNull() ?: continue-            val snapshot = runCatching {-                WearCalendarProtocol.json.decodeFromString<WearCalendarSnapshot>(raw)-            }.getOrNull()-            if (snapshot == null) {-                Log.status(TAG, "ignoring malformed snapshot")-                continue-            }-            WearCalendarStore.get(this).setSnapshot(snapshot)-        }-    }--    private companion object {-        const val TAG = "WearCalendarListener"-        const val KEY_JSON = "json"-    }-}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearLinkBridge.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearLinkBridge.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..01d84e5a8f--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearLinkBridge.kt@@ -0,0 +1,72 @@+package com.vayunmathur.calendar.wear.sync++import android.content.Context+import com.vayunmathur.calendar.wear.data.WearCalendarStore+import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol+import com.vayunmathur.calendar.wear.domain.WearCalendarSnapshot+import com.vayunmathur.calendar.wear.domain.WearWatchState+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Calendar: snapshot data items land in+ * [WearCalendarStore], watch state goes back as a data item, and+ * request-sync is a message. Replaces the Play-services listener service;+ * delivery is bound to this process being alive.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearCalendarProtocol.SNAPSHOT_PATH) return+                val snapshot = runCatching {+                    WearCalendarProtocol.json.decodeFromString<WearCalendarSnapshot>(+                        body.decodeToString(),+                    )+                }.getOrNull()+                if (snapshot == null) {+                    Log.status(TAG, "ignoring malformed snapshot")+                    return+                }+                WearCalendarStore.get(context).setSnapshot(snapshot)+            }+        }+        return WearLinkNode(context, WearCalendarProtocol.CAPABILITY, listener).also { it.start() }+    }++    fun publishWatchState(context: Context, snapshot: WearCalendarSnapshot) {+        val state = WearWatchState(+            appliedGeneratedAtMillis = snapshot.generatedAtMillis,+            eventCount = snapshot.events.size,+        )+        scope.launch {+            get(context).putData(+                WearCalendarProtocol.WATCH_STATE_PATH,+                WearCalendarProtocol.json.encodeToString(state).encodeToByteArray(),+            )+        }+    }++    /** Ask the phone for a fresh snapshot; false when no session is live. */+    suspend fun requestSync(context: Context): Boolean =+        get(context).sendMessage(WearCalendarProtocol.REQUEST_SYNC_PATH, ByteArray(0))+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.ktindex 07b1807515..ddc22d2425 100644--- a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt@@ -1,36 +1,10 @@ package com.vayunmathur.calendar.wear.sync  import android.content.Context-import com.google.android.gms.wearable.Wearable-import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol-import com.vayunmathur.library.log.Log-import kotlin.coroutines.resume-import kotlin.coroutines.resumeWithException-import kotlinx.coroutines.suspendCancellableCoroutine-import com.google.android.gms.tasks.Task--/** 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) }-}  /**- * Asks every connected phone node for a fresh snapshot. Returns false when no- * phone is reachable — the watch keeps rendering its last synced copy, and- * the UI says exactly that instead of pretending a sync happened.+ * Asks the phone for a fresh snapshot over WearLink. Returns false when no+ * phone session is live — the watch keeps rendering its last synced copy,+ * and the UI says exactly that instead of pretending a sync happened.  */-suspend fun requestWearSync(context: Context): Boolean = runCatching {-    val nodes = Wearable.getNodeClient(context).connectedNodes.awaitTask()-    if (nodes.isEmpty()) return false-    var sent = false-    for (node in nodes) {-        runCatching {-            Wearable.getMessageClient(context)-                .sendMessage(node.id, WearCalendarProtocol.REQUEST_SYNC_PATH, ByteArray(0))-                .awaitTask()-            sent = true-        }.onFailure { Log.status("WearSyncRequest", "request to ${node.id} failed: ${it.message}") }-    }-    sent-}.getOrDefault(false)+suspend fun requestWearSync(context: Context): Boolean = WearLinkBridge.requestSync(context)
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.ktindex 2126a993fa..73c38b49b3 100644--- a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt@@ -18,7 +18,9 @@ class WearMainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         val store = WearCalendarStore.get(this)+        com.vayunmathur.calendar.wear.sync.WearLinkBridge.get(this)         store.publishWatchState()         setContent {             MaterialTheme {
calendar-wear/src/main/res/values/wear_capabilities.xml
diff --git a/calendar-wear/src/main/res/values/wear_capabilities.xml b/calendar-wear/src/main/res/values/wear_capabilities.xmldeleted file mode 100644index 6faaa91373..0000000000--- a/calendar-wear/src/main/res/values/wear_capabilities.xml+++ /dev/null@@ -1,9 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<!-- Capability the phone's CapabilityClient looks for: advertising it is-     what makes the phone show this watch as present at all. Must match-     WearCalendarProtocol.CAPABILITY in domain/WearCalendarProtocol.kt. -->-<resources>-    <string-array name="android_wear_capabilities">-        <item>calendar_wear_companion</item>-    </string-array>-</resources>
calendar/build.gradle.kts
diff --git a/calendar/build.gradle.kts b/calendar/build.gradle.ktsindex 6ebf4a44be..d6284da243 100644--- a/calendar/build.gradle.kts+++ b/calendar/build.gradle.kts@@ -17,10 +17,10 @@ android {  dependencies {     implementation(project(":library:widgets"))+    implementation(project(":library:wearlink"))     // 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 dce6c61e38..5700f4cd24 100644--- a/calendar/src/main/AndroidManifest.xml+++ b/calendar/src/main/AndroidManifest.xml@@ -139,15 +139,7 @@                 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>+        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->         <receiver             android:name=".platform.ReminderReceiver"             android:enabled="true"
calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt
diff --git a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.ktindex cc14b63d3c..9e67e176ee 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/MainActivity.kt@@ -42,6 +42,7 @@ class MainActivity : MaActivity() {     private val pendingDate = mutableStateOf<LocalDate?>(null)      override fun onCreateBeforeContent() {+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         updateWidgetPreviews(CalendarGlanceWidgetReceiver::class)         handleIntent(intent)     }
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.ktindex b1c49d4921..6171379335 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/domain/WearCalendarProtocol.kt@@ -6,37 +6,35 @@ 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+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: 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]+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Presence is a completed handshake for [CAPABILITY] (the appId).+ * - Data items carry the snapshot: [SNAPSHOT_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. Delivery needs a live session;+ *   each side persists what it receives and republishes on reconnect.+ * - Messages carry 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. */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "calendar_wear_companion" -    /** DataClient path (phone -> watch): the [WearCalendarSnapshot] JSON. */+    /** Data-item path (phone -> watch): the [WearCalendarSnapshot] JSON. */     const val SNAPSHOT_PATH = "/calendar/snapshot" -    /** DataClient path (watch -> phone): the [WearWatchState] JSON. */+    /** Data-item 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. */+    /** Message 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. */@@ -46,9 +44,9 @@ object WearCalendarProtocol {     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.+     * Largest snapshot JSON, in UTF-8 bytes. Deliberately kept near the old+     * 100 KB DataItem ceiling: a bounded snapshot is what the watch can+     * store/render, and WearLink chunks it transparently either way.      */     const val MAX_JSON_BYTES = 90_000 
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.ktdeleted file mode 100644index 09ac70d15c..0000000000--- a/calendar/src/main/java/com/vayunmathur/calendar/service/WearCalendarListenerService.kt+++ /dev/null@@ -1,27 +0,0 @@-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.ktindex 879908f6d7..b29ad14c3f 100644--- a/calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.kt+++ b/calendar/src/main/java/com/vayunmathur/calendar/sync/WearCalendarSync.kt@@ -1,26 +1,19 @@ 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.WearCalendarSnapshot 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 com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job@@ -31,7 +24,6 @@ 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@@ -39,13 +31,6 @@ 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(@@ -58,30 +43,24 @@ data class WearSyncState( )  /**- * Phone side of the wear sync: capability discovery, snapshot publish, and- * watch-state intake.+ * Phone side of the wear sync over WearLink (RFCOMM, :library:wearlink):+ * presence is a completed handshake, the snapshot is a data item, and the+ * watch's request-sync is a message handled here while this process lives.  *- * 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.+ * "No Bluetooth permission / no watch / watch without the companion" is a+ * normal state ([WearSyncState.companionPresent] = false), never a crash.+ * There is no Play-services listener service any more: a sync request+ * arriving while the phone app is dead waits until it next runs.  */-class WearCalendarSync private constructor(context: Context) :-    CapabilityClient.OnCapabilityChangedListener,-    DataClient.OnDataChangedListener {+class WearCalendarSync private constructor(context: Context) { -    /** 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). */+        /** The process-wide sync (ViewModel must agree on one). */         fun get(context: Context): WearCalendarSync = instance ?: synchronized(this) {             instance ?: WearCalendarSync(context.applicationContext).also { instance = it }         }@@ -91,45 +70,45 @@ class WearCalendarSync private constructor(context: Context) :     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 val listener = object : WearLinkListener {+        override fun onData(path: String, body: ByteArray) {+            if (path != WearCalendarProtocol.WATCH_STATE_PATH) return+            val watchState = runCatching {+                WearCalendarProtocol.json.decodeFromString<WearWatchState>(body.decodeToString())+            }.getOrNull() ?: return+            _state.update {+                it.copy(+                    lastWatchAppliedAtMillis = watchState.appliedGeneratedAtMillis+                        .takeIf { applied -> applied > 0L },+                )+            }+        }++        override fun onMessage(path: String, body: ByteArray) {+            if (path != WearCalendarProtocol.REQUEST_SYNC_PATH) return+            scope.launch { publishSnapshot() }+        }+    }++    private val node = WearLinkNode(appContext, WearCalendarProtocol.CAPABILITY, listener)+     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 })+        scope.launch {+            node.state.collect { linkState ->+                val present = linkState is WearLinkState.Connected+                val wasPresent = _state.value.companionPresent+                _state.update { it.copy(companionPresent = wearCompanionPresent(if (present) listOf("peer") else emptyList())) }+                if (present && !wasPresent) syncNow()             }         }+        node.start()     }      /** Calendar data changed: republish shortly, coalescing bursts (imports, bulk edits). */@@ -147,41 +126,26 @@ class WearCalendarSync private constructor(context: Context) :         scope.launch { publishSnapshot() }     } -    /** Build the bounded snapshot from the provider and publish it on DataClient. */+    /** Build the bounded snapshot from the provider and publish it as a data item. */     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()+        val sent = node.putData(+            WearCalendarProtocol.SNAPSHOT_PATH,+            WearCalendarProtocol.json.encodeToString(snapshot).encodeToByteArray(),+        )+        if (sent) {             _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()+        } else {+            Log.status(TAG, "publish snapshot not delivered (no live WearLink session)")+        }     } -    private fun buildSnapshot(): com.vayunmathur.calendar.domain.WearCalendarSnapshot? =+    private fun buildSnapshot(): WearCalendarSnapshot? =         runCatching {             val now = Clock.System.now()             val zone = TimeZone.currentSystemDefault()
contacts-wear/AGENTS.md
diff --git a/contacts-wear/AGENTS.md b/contacts-wear/AGENTS.mdindex 72eedc5c27..155506e5c1 100644--- a/contacts-wear/AGENTS.md+++ b/contacts-wear/AGENTS.md@@ -5,7 +5,7 @@  - Gradle: :contacts-wear / dir: contacts-wear/ - applicationId: `com.vayunmathur.contacts` — MUST stay equal to `:contacts`;-  Wearable Data Layer requires same package + same signing on phone and watch.+  WearLink's handshake requires same signing on phone and watch (same package kept). - Package: `com.vayunmathur.contacts.wear` (domain/data/sync/ui/platform) - Protocol: `domain/WearContactsProtocol.kt` is a deliberate copy of the phone   file in `contacts/domain/`; change both together (golden-JSON tests pin it).
contacts-wear/build.gradle.kts
diff --git a/contacts-wear/build.gradle.kts b/contacts-wear/build.gradle.ktsindex af0dd930be..70d7f49c63 100644--- a/contacts-wear/build.gradle.kts+++ b/contacts-wear/build.gradle.kts@@ -28,8 +28,8 @@ android { }  dependencies {-    implementation(libs.play.services.wearable)     implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))     implementation(libs.androidx.navigation3.runtime)     implementation(libs.androidx.navigation3.ui)     testImplementation(libs.kotlin.test)
contacts-wear/src/main/AndroidManifest.xml
diff --git a/contacts-wear/src/main/AndroidManifest.xml b/contacts-wear/src/main/AndroidManifest.xmlindex 563b04321b..b741198992 100644--- a/contacts-wear/src/main/AndroidManifest.xml+++ b/contacts-wear/src/main/AndroidManifest.xml@@ -31,24 +31,6 @@             </intent-filter>         </activity> -        <!-- Snapshot chunks/manifest arrive here even when the UI is closed. -->-        <service-            android:name=".sync.WearContactsListenerService"-            android:exported="true">-            <intent-filter>-                <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />-                <data-                    android:host="*"-                    android:pathPrefix="/contacts/snapshot/"-                    android:scheme="wear" />-            </intent-filter>-            <intent-filter>-                <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />-                <data-                    android:host="*"-                    android:pathPrefix="/contacts/"-                    android:scheme="wear" />-            </intent-filter>-        </service>+        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->     </application> </manifest>
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/MainActivity.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/MainActivity.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/MainActivity.ktindex 67a7882ea4..df6ec83fc8 100644--- a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/MainActivity.kt+++ b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/MainActivity.kt@@ -26,7 +26,9 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)-        store = WearContactsStore(applicationContext)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        store = com.vayunmathur.contacts.wear.sync.WearLinkBridge.store(applicationContext)+        com.vayunmathur.contacts.wear.sync.WearLinkBridge.get(applicationContext)         capabilities = WearDeviceCapabilitiesProbe.probeHandlers(this)         setContent {             val snapshot by store.snapshot.collectAsState()
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.ktindex 3f5a2ca394..5f60ff07f7 100644--- a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.kt+++ b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/domain/WearContactsProtocol.kt@@ -6,8 +6,7 @@ import kotlinx.serialization.json.Json /**  * Phone <-> watch contacts protocol.  *- * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only- * connects apps sharing package name + signing certificate, but Gradle cannot let+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let  * one application module depend on another, so `:contacts-wear`  * (applicationId `com.vayunmathur.contacts`, same debug/release signing as the  * phone app) carries a byte-identical copy under@@ -19,27 +18,28 @@ import kotlinx.serialization.json.Json  * contacts (favourites first, then A-Z), at most 3 phones + 3 emails each, with  * every field truncated. The manifest says how many contacts exist vs how many  * were sent, so the watch can show "1,000 of 4,213 contacts" instead of- * pretending the rest do not exist. Each chunk is one DataItem whose JSON stays- * well under the Data Layer's 100 KB per-item ceiling; chunks arrive in any- * order and are only applied once the manifest's chunk count is complete.+ * pretending the rest do not exist. Each chunk is one WearLink data item+ * (transport-chunked again underneath by :library:wearlink); chunks arrive+ * in any order and are only applied once the manifest's chunk count is+ * complete.  */ object WearContactsProtocol {-    /** Capability the wear app advertises (res `android_wear_capabilities`). */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "contacts_wear_companion" -    /** DataClient manifest path for the current snapshot generation. */+    /** Data-item manifest path for the current snapshot generation. */     const val MANIFEST_PATH = "/contacts/snapshot/manifest" -    /** DataClient prefix for chunk paths: [chunkPath] appends the chunk index. */+    /** Data-item prefix for chunk paths: [chunkPath] appends the chunk index. */     const val CHUNK_PREFIX = "/contacts/snapshot/chunk/" -    /** DataClient path (watch -> phone): the watch's received-state snapshot. */+    /** Data-item path (watch -> phone): the watch's received-state snapshot. */     const val WATCH_STATE_PATH = "/contacts/watch-state" -    /** MessageClient path (watch -> phone): republish the snapshot. */+    /** Message path (watch -> phone): republish the snapshot. */     const val REQUEST_SNAPSHOT_PATH = "/contacts/request-snapshot" -    /** MessageClient path (watch -> phone): start this call/message on the phone. */+    /** Message path (watch -> phone): start this call/message on the phone. */     const val HANDOFF_PATH = "/contacts/handoff"      /** Hard cap on contacts ever sent to the watch. */@@ -54,7 +54,7 @@ object WearContactsProtocol {     const val MAX_PHONE_CHARS = 40     const val MAX_EMAIL_CHARS = 80 -    /** Target ceiling for one chunk's JSON bytes (DataItem limit is 100 KB). */+    /** Target ceiling for one chunk's JSON bytes (kept near the old 100 KB item cap). */     const val MAX_CHUNK_BYTES = 50_000      /** Chunk path for chunk [index] of the current generation. */@@ -81,7 +81,7 @@ data class WearContact(     val isFavorite: Boolean = false, ) -/** One DataItem's payload: chunk [index] of generation [generation]. */+/** One data item's payload: chunk [index] of generation [generation]. */ @Serializable data class WearContactsChunk(     val generation: Long,@@ -89,7 +89,7 @@ data class WearContactsChunk(     val contacts: List<WearContact> = emptyList(), ) -/** The manifest DataItem: what a complete snapshot looks like. */+/** The manifest data item: what a complete snapshot looks like. */ @Serializable data class WearContactsManifest(     val generation: Long,@@ -293,7 +293,7 @@ object WearActionPolicy {  /** Phone-side presence of the watch companion, as the phone UI reports it. */ enum class WearPresence {-    /** No reachable node advertises the wear capability (or no Data Layer). */+    /** No reachable node advertises the wear capability (or no WearLink session). */     NO_WATCH,      /** A watch advertises the capability but has not published state yet. */
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/platform/WearDeviceCapabilities.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/platform/WearDeviceCapabilities.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/platform/WearDeviceCapabilities.ktindex 54580d879d..1bd4ff11ee 100644--- a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/platform/WearDeviceCapabilities.kt+++ b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/platform/WearDeviceCapabilities.kt@@ -4,11 +4,7 @@ import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri-import com.google.android.gms.tasks.Task-import com.google.android.gms.wearable.Wearable-import kotlin.coroutines.resume-import kotlin.coroutines.resumeWithException-import kotlinx.coroutines.suspendCancellableCoroutine+import com.vayunmathur.contacts.wear.sync.WearLinkBridge  /** What this watch hardware/software can actually do, probed honestly at runtime. */ data class WearDeviceCapabilities(@@ -22,10 +18,6 @@ data class WearDeviceCapabilities(     val canCallOnWatch: Boolean get() = hasTelephony && hasDialer } -private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->-    addOnSuccessListener { cont.resume(it) }-    addOnFailureListener { cont.resumeWithException(it) }-}  object WearDeviceCapabilitiesProbe { @@ -40,12 +32,10 @@ object WearDeviceCapabilitiesProbe {         )     } -    /** Full probe including whether a phone node is currently reachable. */+    /** Full probe including whether a WearLink phone session is currently live. */     suspend fun probe(context: Context): WearDeviceCapabilities {         val base = probeHandlers(context)-        val reachable = runCatching {-            Wearable.getNodeClient(context).connectedNodes.awaitTask().isNotEmpty()-        }.getOrDefault(false)+        val reachable = runCatching { WearLinkBridge.isConnected(context) }.getOrDefault(false)         return base.copy(phoneReachable = reachable)     } 
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearContactsListenerService.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearContactsListenerService.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearContactsListenerService.ktdeleted file mode 100644index 032fda68dd..0000000000--- a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearContactsListenerService.kt+++ /dev/null@@ -1,65 +0,0 @@-package com.vayunmathur.contacts.wear.sync--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.WearableListenerService-import com.vayunmathur.contacts.wear.data.WearContactsStore-import com.vayunmathur.contacts.wear.domain.WearContactsChunk-import com.vayunmathur.contacts.wear.domain.WearContactsManifest-import com.vayunmathur.contacts.wear.domain.WearContactsProtocol-import com.vayunmathur.library.log.Log-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.launch--/**- * Receives the phone's chunked snapshot while the UI is closed, stores the- * completed snapshot locally, then publishes watch state back so the phone can- * show "watch has N contacts". Incomplete generations change nothing.- */-class WearContactsListenerService : WearableListenerService() {--    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)--    override fun onDataChanged(dataEvents: DataEventBuffer) {-        val store = WearContactsStore(applicationContext)-        var completed = false-        for (event in dataEvents) {-            if (event.type != DataEvent.TYPE_CHANGED) continue-            val path = event.dataItem.uri.path ?: continue-            val json = runCatching {-                DataMapItem.fromDataItem(event.dataItem).dataMap.getString(KEY_JSON)-            }.getOrNull() ?: continue-            runCatching {-                when {-                    path == WearContactsProtocol.MANIFEST_PATH -> {-                        val before = store.snapshot.value.contacts.size-                        store.onManifest(decodeManifest(json))-                        completed = completed || store.snapshot.value.contacts.size != before ||-                            store.snapshot.value.manifest != null-                    }-                    WearContactsProtocol.chunkIndexFromPath(path) != null ->-                        store.onChunk(decodeChunk(json))-                    else -> Unit-                }-            }.onFailure { Log.status(TAG, "snapshot item ignored: ${it.message}") }-        }-        val snapshot = store.snapshot.value-        if (snapshot.manifest != null) {-            scope.launch { WearWatchStatePublisher.publish(applicationContext, snapshot) }-        }-    }--    private fun decodeManifest(json: String): WearContactsManifest =-        WearContactsProtocol.json.decodeFromString(json)--    private fun decodeChunk(json: String): WearContactsChunk =-        WearContactsProtocol.json.decodeFromString(json)--    companion object {-        private const val TAG = "WearContactsListener"-        private const val KEY_JSON = "json"-    }-}
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearLinkBridge.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearLinkBridge.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..b675b0ae2a--- /dev/null+++ b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearLinkBridge.kt@@ -0,0 +1,77 @@+package com.vayunmathur.contacts.wear.sync++import android.content.Context+import com.vayunmathur.contacts.wear.data.WearContactsStore+import com.vayunmathur.contacts.wear.domain.WearContactsChunk+import com.vayunmathur.contacts.wear.domain.WearContactsManifest+import com.vayunmathur.contacts.wear.domain.WearContactsProtocol+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch++/**+ * Watch side of WearLink for Contacts: manifest/chunk data items feed+ * [WearContactsStore]'s reassembler, and a completed snapshot publishes+ * watch state back. Replaces the Play-services listener service; delivery+ * is bound to this process being alive.+ */+object WearLinkBridge {+    private const val TAG = "WearLinkBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    // One store shared with the UI so reassembly state is not split.+    @Volatile+    private var store: WearContactsStore? = null++    fun store(context: Context): WearContactsStore {+        val appContext = context.applicationContext+        return store ?: synchronized(this) {+            store ?: WearContactsStore(appContext).also { store = it }+        }+    }++    fun get(context: Context): WearLinkNode {+        val appContext = context.applicationContext+        return node ?: synchronized(this) {+            node ?: create(appContext).also { node = it }+        }+    }++    private fun create(context: Context): WearLinkNode {+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                val watchStore = store(context)+                runCatching {+                    when {+                        path == WearContactsProtocol.MANIFEST_PATH ->+                            watchStore.onManifest(decodeManifest(body))+                        WearContactsProtocol.chunkIndexFromPath(path) != null ->+                            watchStore.onChunk(decodeChunk(body))+                        else -> return+                    }+                }.onFailure { Log.status(TAG, "snapshot item ignored: ${it.message}") }+                val snapshot = watchStore.snapshot.value+                if (snapshot.manifest != null) {+                    scope.launch { WearWatchStatePublisher.publish(context, snapshot) }+                }+            }+        }+        return WearLinkNode(context, WearContactsProtocol.CAPABILITY, listener).also { it.start() }+    }++    /** Live-session check for capability probing (no system node query any more). */+    fun isConnected(context: Context): Boolean = get(context).isConnected++    private fun decodeManifest(body: ByteArray): WearContactsManifest =+        WearContactsProtocol.json.decodeFromString(body.decodeToString())++    private fun decodeChunk(body: ByteArray): WearContactsChunk =+        WearContactsProtocol.json.decodeFromString(body.decodeToString())+}
contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearWatchStatePublisher.kt
diff --git a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearWatchStatePublisher.kt b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearWatchStatePublisher.ktindex 9a1f284182..098978fc6c 100644--- a/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearWatchStatePublisher.kt+++ b/contacts-wear/src/main/java/com/vayunmathur/contacts/wear/sync/WearWatchStatePublisher.kt@@ -1,48 +1,30 @@ package com.vayunmathur.contacts.wear.sync  import android.content.Context-import com.google.android.gms.wearable.PutDataMapRequest-import com.google.android.gms.wearable.Wearable import com.vayunmathur.contacts.wear.data.WearSnapshot import com.vayunmathur.contacts.wear.domain.WearContactsProtocol import com.vayunmathur.contacts.wear.domain.WearHandoffRequest import com.vayunmathur.contacts.wear.domain.WearWatchState import com.vayunmathur.library.log.Log-import com.google.android.gms.tasks.Task-import kotlin.coroutines.resume-import kotlin.coroutines.resumeWithException-import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.serialization.encodeToString -/** Await a Play services [Task] without a coroutines-play-services dependency. */-private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->-    addOnSuccessListener { cont.resume(it) }-    addOnFailureListener { cont.resumeWithException(it) }-}--/** Watch -> phone transport: received-state DataItem + ephemeral messages. */+/** Watch -> phone transport over WearLink: received-state data item + messages. */ object WearWatchStatePublisher {      private const val TAG = "WearWatchState"-    private const val KEY_JSON = "json"-    private const val KEY_SENT_AT = "sent_at"      /** Publish how many contacts this watch holds, so the phone status is truthful. */     suspend fun publish(context: Context, snapshot: WearSnapshot) {-        runCatching {-            val state = WearWatchState(-                contactCount = snapshot.contacts.size,-                generation = snapshot.manifest?.generation ?: 0L,-                receivedAtMillis = System.currentTimeMillis(),-            )-            val request = PutDataMapRequest.create(WearContactsProtocol.WATCH_STATE_PATH)-                .apply {-                    dataMap.putString(KEY_JSON, WearContactsProtocol.json.encodeToString(state))-                    dataMap.putLong(KEY_SENT_AT, state.receivedAtMillis)-                }-                .asPutDataRequest().setUrgent()-            Wearable.getDataClient(context).putDataItem(request).awaitTask()-        }.onFailure { Log.status(TAG, "watch-state publish failed: ${it.message}") }+        val state = WearWatchState(+            contactCount = snapshot.contacts.size,+            generation = snapshot.manifest?.generation ?: 0L,+            receivedAtMillis = System.currentTimeMillis(),+        )+        val sent = WearLinkBridge.get(context).putData(+            WearContactsProtocol.WATCH_STATE_PATH,+            WearContactsProtocol.json.encodeToString(state).encodeToByteArray(),+        )+        if (!sent) Log.status(TAG, "watch-state publish not delivered (no live session)")     }      /** Ask the phone to republish the snapshot (e.g. first launch with an empty book). */@@ -60,10 +42,7 @@ object WearWatchStatePublisher {     }      private suspend fun sendToPhone(context: Context, path: String, payload: ByteArray) {-        runCatching {-            val nodes = Wearable.getNodeClient(context).connectedNodes.awaitTask()-            val messages = Wearable.getMessageClient(context)-            for (node in nodes) messages.sendMessage(node.id, path, payload).awaitTask()-        }.onFailure { Log.status(TAG, "message $path failed: ${it.message}") }+        val sent = WearLinkBridge.get(context).sendMessage(path, payload)+        if (!sent) Log.status(TAG, "message $path not delivered (no live session)")     } }
contacts-wear/src/main/res/values/wear.xml
diff --git a/contacts-wear/src/main/res/values/wear.xml b/contacts-wear/src/main/res/values/wear.xmldeleted file mode 100644index b36ab61638..0000000000--- a/contacts-wear/src/main/res/values/wear.xml+++ /dev/null@@ -1,7 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<resources>-    <!-- Capability the phone looks for (WearContactsProtocol.CAPABILITY). -->-    <string-array name="android_wear_capabilities">-        <item>contacts_wear_companion</item>-    </string-array>-</resources>
contacts/build.gradle.kts
diff --git a/contacts/build.gradle.kts b/contacts/build.gradle.ktsindex bab1087d80..da812d4130 100644--- a/contacts/build.gradle.kts+++ b/contacts/build.gradle.kts@@ -22,7 +22,7 @@ android { dependencies {     // VCF export/import now uses java.io BufferedReader/Writer – no okio needed     implementation(libs.libphonenumber)+    implementation(project(":library:wearlink"))     implementation(libs.androidx.work.runtime.ktx)     // Wear OS companion (:contacts-wear, same applicationId + signing): Data Layer sync.-    implementation(libs.play.services.wearable) }
contacts/src/main/AndroidManifest.xml
diff --git a/contacts/src/main/AndroidManifest.xml b/contacts/src/main/AndroidManifest.xmlindex 7f13d36a87..7c46ec99f8 100644--- a/contacts/src/main/AndroidManifest.xml+++ b/contacts/src/main/AndroidManifest.xml@@ -195,18 +195,7 @@             android:permission="com.vayunmathur.contacts.permissions.ACCESS_CONTACTS">         </activity> -        <!-- Wear companion handoff/snapshot requests (:contacts-wear, same package+signing). -->-        <service-            android:name=".sync.WearContactsListenerService"-            android:exported="true">-            <intent-filter>-                <action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />-                <data-                    android:host="*"-                    android:pathPrefix="/contacts/"-                    android:scheme="wear" />-            </intent-filter>-        </service>+        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->          <service android:name=".auth.AuthenticatorService" android:exported="false">             <intent-filter>
contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.ktindex 9fd09a1405..444bb72332 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/MainActivity.kt@@ -86,6 +86,7 @@ class MainActivity : MaActivity() {     }      override fun onCreateBeforeContent() {+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         handleIntent(intent)     } 
contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.kt b/contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.ktindex 24456289b0..69cc409b78 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/domain/WearContactsProtocol.kt@@ -6,8 +6,7 @@ import kotlinx.serialization.json.Json /**  * Phone <-> watch contacts protocol.  *- * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only- * connects apps sharing package name + signing certificate, but Gradle cannot let+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let  * one application module depend on another, so `:contacts-wear`  * (applicationId `com.vayunmathur.contacts`, same debug/release signing as the  * phone app) carries a byte-identical copy under@@ -19,27 +18,28 @@ import kotlinx.serialization.json.Json  * contacts (favourites first, then A-Z), at most 3 phones + 3 emails each, with  * every field truncated. The manifest says how many contacts exist vs how many  * were sent, so the watch can show "1,000 of 4,213 contacts" instead of- * pretending the rest do not exist. Each chunk is one DataItem whose JSON stays- * well under the Data Layer's 100 KB per-item ceiling; chunks arrive in any- * order and are only applied once the manifest's chunk count is complete.+ * pretending the rest do not exist. Each chunk is one WearLink data item+ * (transport-chunked again underneath by :library:wearlink); chunks arrive+ * in any order and are only applied once the manifest's chunk count is+ * complete.  */ object WearContactsProtocol {-    /** Capability the wear app advertises (res `android_wear_capabilities`). */+    /** WearLink appId the phone requires in the peer handshake. */     const val CAPABILITY = "contacts_wear_companion" -    /** DataClient manifest path for the current snapshot generation. */+    /** Data-item manifest path for the current snapshot generation. */     const val MANIFEST_PATH = "/contacts/snapshot/manifest" -    /** DataClient prefix for chunk paths: [chunkPath] appends the chunk index. */+    /** Data-item prefix for chunk paths: [chunkPath] appends the chunk index. */     const val CHUNK_PREFIX = "/contacts/snapshot/chunk/" -    /** DataClient path (watch -> phone): the watch's received-state snapshot. */+    /** Data-item path (watch -> phone): the watch's received-state snapshot. */     const val WATCH_STATE_PATH = "/contacts/watch-state" -    /** MessageClient path (watch -> phone): republish the snapshot. */+    /** Message path (watch -> phone): republish the snapshot. */     const val REQUEST_SNAPSHOT_PATH = "/contacts/request-snapshot" -    /** MessageClient path (watch -> phone): start this call/message on the phone. */+    /** Message path (watch -> phone): start this call/message on the phone. */     const val HANDOFF_PATH = "/contacts/handoff"      /** Hard cap on contacts ever sent to the watch. */@@ -54,7 +54,7 @@ object WearContactsProtocol {     const val MAX_PHONE_CHARS = 40     const val MAX_EMAIL_CHARS = 80 -    /** Target ceiling for one chunk's JSON bytes (DataItem limit is 100 KB). */+    /** Target ceiling for one chunk's JSON bytes (kept near the old 100 KB item cap). */     const val MAX_CHUNK_BYTES = 50_000      /** Chunk path for chunk [index] of the current generation. */@@ -81,7 +81,7 @@ data class WearContact(     val isFavorite: Boolean = false, ) -/** One DataItem's payload: chunk [index] of generation [generation]. */+/** One data item's payload: chunk [index] of generation [generation]. */ @Serializable data class WearContactsChunk(     val generation: Long,@@ -89,7 +89,7 @@ data class WearContactsChunk(     val contacts: List<WearContact> = emptyList(), ) -/** The manifest DataItem: what a complete snapshot looks like. */+/** The manifest data item: what a complete snapshot looks like. */ @Serializable data class WearContactsManifest(     val generation: Long,@@ -293,7 +293,7 @@ object WearActionPolicy {  /** Phone-side presence of the watch companion, as the phone UI reports it. */ enum class WearPresence {-    /** No reachable node advertises the wear capability (or no Data Layer). */+    /** No reachable node advertises the wear capability (or no WearLink session). */     NO_WATCH,      /** A watch advertises the capability but has not published state yet. */
contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsListenerService.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsListenerService.kt b/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsListenerService.ktdeleted file mode 100644index 98c77735e3..0000000000--- a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsListenerService.kt+++ /dev/null@@ -1,62 +0,0 @@-package com.vayunmathur.contacts.sync--import android.content.Intent-import android.net.Uri-import com.google.android.gms.wearable.MessageEvent-import com.google.android.gms.wearable.WearableListenerService-import com.vayunmathur.contacts.domain.WearContactsProtocol-import com.vayunmathur.contacts.domain.WearHandoffRequest-import com.vayunmathur.library.log.Log-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.launch--/**- * Phone side of the watch handoff, alive even when the app UI is not: the watch- * asks for a fresh snapshot, or asks the phone to start a call/message it cannot- * start itself. Handoffs open the phone's dialler/messaging composer — the- * person on the phone still taps call/send; nothing is placed silently.- */-class WearContactsListenerService : WearableListenerService() {--    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)--    override fun onMessageReceived(messageEvent: MessageEvent) {-        when (messageEvent.path) {-            WearContactsProtocol.REQUEST_SNAPSHOT_PATH -> republish()-            WearContactsProtocol.HANDOFF_PATH -> handleHandoff(messageEvent.data)-        }-    }--    private fun republish() {-        scope.launch {-            runCatching {-                WearContactsSync(applicationContext, scope)-                    .publishWearContacts(loadWearContacts(applicationContext))-            }.onFailure { Log.status(TAG, "republish failed: ${it.message}") }-        }-    }--    private fun handleHandoff(data: ByteArray) {-        val request = runCatching {-            WearContactsProtocol.json.decodeFromString<WearHandoffRequest>(-                data.decodeToString(),-            )-        }.getOrNull() ?: return-        val intent = when (request.kind) {-            WearHandoffRequest.KIND_CALL ->-                Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", request.value, null))-            WearHandoffRequest.KIND_MESSAGE ->-                Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", request.value, null))-            else -> return-        }-        runCatching {-            startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))-        }.onFailure { Log.status(TAG, "handoff failed: ${it.message}") }-    }--    companion object {-        private const val TAG = "WearContactsListener"-    }-}
contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt
diff --git a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt b/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.ktindex d0f7fd14a2..0eaf6bad7a 100644--- a/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt+++ b/contacts/src/main/java/com/vayunmathur/contacts/sync/WearContactsSync.kt@@ -1,41 +1,29 @@ package com.vayunmathur.contacts.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 android.content.Intent+import android.net.Uri import com.vayunmathur.contacts.data.Contact import com.vayunmathur.contacts.domain.WearContactsManifest import com.vayunmathur.contacts.domain.WearContactsProtocol+import com.vayunmathur.contacts.domain.WearHandoffRequest import com.vayunmathur.contacts.domain.WearPresence import com.vayunmathur.contacts.domain.WearPresencePolicy import com.vayunmathur.contacts.domain.WearSnapshotBuilder import com.vayunmathur.contacts.domain.WearWatchState import com.vayunmathur.contacts.domain.WearContact import com.vayunmathur.library.log.Log-import kotlin.coroutines.resume-import kotlin.coroutines.resumeWithException+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch-import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.serialization.encodeToString -/** Await a Play services [Task] without a coroutines-play-services dependency. */-private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->-    addOnSuccessListener { cont.resume(it) }-    addOnFailureListener { cont.resumeWithException(it) }-}- /** Maps the provider model onto the watch row: names/phones/emails only, no photos. */ fun Contact.toWearContact(): WearContact = WearContact(     id = id,@@ -47,7 +35,7 @@ fun Contact.toWearContact(): WearContact = WearContact(     isFavorite = isFavorite, ) -/** Loads the full book (provider + SIM) for a republish, e.g. from the listener service. */+/** Loads the full book (provider + SIM) for a republish, e.g. after a watch request. */ fun loadWearContacts(context: Context): List<WearContact> {     val device = runCatching { Contact.getAllContacts(context) }.getOrDefault(emptyList())     val sim = runCatching {@@ -58,81 +46,74 @@ fun loadWearContacts(context: Context): List<WearContact> { }  /**- * Phone side of the contacts wear sync: capability discovery, chunked snapshot- * publish, and the watch-state status the Settings screen shows.+ * Phone side of the contacts wear sync over WearLink (RFCOMM,+ * :library:wearlink): presence is a completed handshake, the snapshot is a+ * chunked data item (generation/manifest discipline retained in the payload+ * protocol), watch state is a data item, and request/handoff are messages+ * handled here while this process lives.  *- * Every Wearable call is wrapped so that "no Play services / no watch / watch- * without Contacts" is a normal state ([WearPresence.NO_WATCH]), never a crash.- * The Data Layer only connects the two apps because they share the package name- * `com.vayunmathur.contacts` and a signing certificate — dev builds on both- * sides use the debug key, release builds on both sides use the same release key.+ * "No Bluetooth permission / no watch / watch without Contacts" is a normal+ * state ([WearPresence.NO_WATCH]), never a crash. There is no Play-services+ * listener service any more: watch-originated requests arriving while the+ * phone app is dead wait until it next runs and reconnects.  */ class WearContactsSync(     private val context: Context,     private val scope: CoroutineScope,-) : CapabilityClient.OnCapabilityChangedListener, DataClient.OnDataChangedListener {-+) {     companion obje

Diff truncated.