Modern Apps git

← Modern-Apps.git

wearlink: make the watch listen and the phone dial its paired watch

Commit
7b71fa9b77c7c804ef7a416e6c41000b61aafc34
Author
Vayun Mathur <[email protected]>
When
2026-12-06 16:50 UTC (24 minutes ago)
Parents
c5e750e
The conduit ran symmetric RFCOMM: both the phone and watch Watch
apps listened and dialled every bonded device in rotation, with a
handshake instance-id tie-break when two dials met. On a phone with
several bonded devices the watch link kept rotating between them.

Roles are now fixed and asymmetric. The watch role owns one accept
loop on the MAWL service UUID, retried with the shared backoff, and
never dials. The phone role never listens; it dials only its paired
watch, selected by PairedWatchSelector from the bonded set filtered
by SDP proof (cached UUIDs, then fetchUuidsWithSdp) that a device
offers the WearLink service UUID, caches the proven address in
SharedPreferences, and re-verifies it by SDP before reuse, dropping
the cache when the proven address fails. Each side holds one
connection; a second candidate never displaces the live session.

The cert-bound handshake now carries the sender role: the initiator
must be the phone and the acceptor the watch, and
HandshakeVerifier rejects a mismatched or absent role, so
phone-to-phone and watch-to-watch sessions cannot form. The
instance-id tie-break and blind bonded-set dialling are removed.

Everything above the transport is unchanged: WearLinkNode's
message/data/stream API, appId routing, the conduit router,
latest-wins store, sync triggers, open-on-phone and the media
bridge all run over the same interfaces. No manifest or permission
changes: only :watch and :watch:wear hold Bluetooth permissions,
as before, and neither side gained a prompt.

Backoff: both loops use WearLinkBackoff, 1 s doubling to a 30 s
ceiling and reset on a live session (the watch listener previously
retried on a fixed 1 s delay). SDP fetches time out at 5 s and fall
back to the cached SDP record.

Verified: :library:wearlink:lint, :library:wearlink:testDevUnitTest,
:watch:lint, :watch:lintVitalRelease, :watch:testDevUnitTest,
:watch:wear:lintVitalRelease and :watch:wear:assembleDev pass.
:watch:wear:lint and :watch:wear:testDebugUnitTest fail on the
unmodified base with the same debug-variant mismatch against
:library:log, so those two are pre-existing.

Diff

library/wearlink/AGENTS.md
diff --git a/library/wearlink/AGENTS.md b/library/wearlink/AGENTS.mdindex f44e4ae4d5..fd77f2db2e 100644--- a/library/wearlink/AGENTS.md+++ b/library/wearlink/AGENTS.md@@ -5,7 +5,9 @@ - Gradle: :library:wearlink / dir: library/wearlink/ - Package: `com.vayunmathur.library.wearlink` for the transport, plus one   per-app protocol subpackage (e.g. `com.vayunmathur.library.wearlink.clock`)-- Entry: `WearLinkNode.kt` (Android), `WearLinkProtocol.kt` (pure wire),+- Entry: `WearLinkNode.kt` (Android, fixed `WearLinkRole` per device),+  `WearLinkRoles.kt` (role policy, SDP-verified paired-watch selection,+  proven-address cache), `WearLinkProtocol.kt` (pure wire),   `conduit/WearLinkClientNode.kt` (Messenger client used by every app   except the Watch apps) - Wear entry shell: `WearShellActivity.kt` — every wear companion's main@@ -35,8 +37,16 @@  ## Purpose First-party replacement for the proprietary Play-services Wearable Data-Layer. RFCOMM over already-bonded Bluetooth, both sides listen + dial,-cert-bound handshake. No Play services, no BLE scan/advertise, no location.+Layer. RFCOMM over already-bonded Bluetooth with fixed asymmetric roles:+the watch listens on the MAWL RFCOMM service UUID and never dials; the+phone never listens for the conduit and dials only its paired watch — a+bonded device whose SDP record offers the WearLink service UUID+(`fetchUuidsWithSdp` on bonded devices), with the proven watch address+cached and re-verified by SDP before reuse. Each side holds one+connection and retries with the shared 1 s → 30 s exponential backoff.+The cert-bound handshake carries the sender's role (initiator = phone,+acceptor = watch) and rejects any other pairing. No Play services, no+BLE scan/advertise, no location.  Also hosts the shared phone<->wear wire protocols that were previously duplicated per app pair: each migrated protocol lives in@@ -71,7 +81,8 @@ broadcast to, and unregistered open requests — the camera op included — are never queued for stale replay; `OpenOnPhoneManifestContractTest` pins every app's receiver, permission, package and send path), and `ConduitHost`/`ConduitRuntime` used by the two-Watch apps' `ConduitService`s. Merged phone/watch pairs ship as+Watch apps' `ConduitService`s (the phone host is created with+`WearLinkRole.PHONE`, the watch host with `WearLinkRole.WATCH`). Merged phone/watch pairs ship as single APKs whose phone and watch experiences pick their side at runtime. This module declares no Bluetooth permissions; only the Watch apps (:watch, :watch:wear) do.
library/wearlink/README.md
diff --git a/library/wearlink/README.md b/library/wearlink/README.mdindex 81403dfbf8..9b9717f597 100644--- a/library/wearlink/README.md+++ b/library/wearlink/README.md@@ -17,10 +17,14 @@ with no Play services anywhere.   `createRfcommSocketToServiceRecord`, accept is   `listenUsingRfcommWithServiceRecord` (both verified against the local   android-37 SDK). Secure/bonded sockets only.-- **Both sides listen and both sides dial**, so either side can initiate.-  When both dial at once, the handshake's per-process instance ids break-  the tie: the pair initiated by the smaller instance id survives, on both-  ends, deterministically.+- **Fixed asymmetric roles.** The watch listens on the service record+  with one listener and never dials. The phone never listens for the+  conduit; it dials only its paired watch — a bonded device whose SDP+  record offers the service UUID (`fetchUuidsWithSdp` on the bonded+  set) — caches the proven address, and re-verifies it by SDP before+  reuse. No bonded device without the service is ever dialled, so the+  link cannot rotate across phones, headsets or other watches. Each+  side holds one connection; a second candidate never displaces it. - Why not BLE GATT as primary: a GATT design (watch = server advertising,   phone = central) would need BLUETOOTH_ADVERTISE/SCAN, MTU negotiation   and characteristic chunking — workable for messages, but APK-sized@@ -33,7 +37,7 @@ with no Play services anywhere.  | Data Layer | WearLink | |---|---|-| CapabilityClient | Bonded-set candidates + HELLO handshake for `appId` (the old capability string, reused verbatim). `WearLinkState` replaces node reachability. |+| CapabilityClient | SDP-verified bonded watch + HELLO handshake for `appId` (the old capability string, reused verbatim). `WearLinkState` replaces node reachability. | | MessageClient | `MESSAGE` frames: fire-and-forget, optional `MESSAGE_ACK`, or `RESPONSE`-correlated requests (ids + timeout + duplicate suppression). Same paths/payloads as before. | | DataClient (DataItem) | `DATA` frames: path-keyed document, generation + chunk index/count + total size + SHA-256; applied only when complete and verified. No 100 KB cap; replaces contacts' hand-rolled chunk paths and appstore/calendar's DataMap JSON. | | ChannelClient | `STREAM_OPEN/CHUNK/CLOSE` on the same session: total size + SHA-256 header, receiver `STREAM_ACK` carries its durable offset, sender seeks — **resumable** across reconnects when the sink kept its partial file. |@@ -47,14 +51,18 @@ transport underneath them changed. `[u32 length][u8 type][u64 id][u16 path len][path][body]`, capped at 64 KiB per frame, 256 KiB per message, 4 MiB per data item, 200 MiB per stream. Corrupt length/type fails the session closed. All IO runs on-`Dispatchers.IO` inside `WearLinkNode`; reconnects back off 1 s → 30 s.+`Dispatchers.IO` inside `WearLinkNode`; both the watch listener retry and+the phone reconnect back off 1 s → 30 s (doubling, capped). Failure is surfaced through `WearLinkState` into each app's existing phone/watch sync states (no fake "synced").  ## Trust  Bonding proves the paired device and encrypts the link; it does not prove-the peer *app*. The handshake also requires: equal `appId`, and a token+the peer *app*. The handshake also requires: equal `appId`, the+counterpart role (the phone initiates as `phone` and accepts only a+`watch` HELLO_ACK; the watch accepts only a `phone` HELLO and answers as+`watch`), and a token `SHA-256(signingCertHash ‖ peerNonce ‖ appId)` where each side derives the expected hash from its **own** PackageManager signing certificate (`GET_SIGNING_CERTIFICATES`). A differently-signed peer fails; the nonce@@ -66,11 +74,13 @@ accessible to app code).  ## Permissions -Library manifest declares only `BLUETOOTH_CONNECT` (API 31+) plus-`BLUETOOTH`/`BLUETOOTH_ADMIN` capped at API 30. No scan/advertise (we-never scan or advertise), and no location permission or-`neverForLocation` workaround. The hosting activity requests-`BLUETOOTH_CONNECT` at runtime; until granted the node reports+The library declares no Bluetooth permissions; only the two Watch apps+(:watch on the phone, :watch:wear on the watch) declare+`BLUETOOTH_CONNECT` (API 31+) plus `BLUETOOTH`/`BLUETOOTH_ADMIN` capped+at API 30. No scan/advertise permission is held anywhere (neither side+scans or advertises; the phone's SDP check runs over the bonded set),+and no location permission or `neverForLocation` workaround is used.+Until `BLUETOOTH_CONNECT` is granted the node reports `PermissionMissing` instead of crashing.  ## What degrades vs GMS (honest)
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.ktindex a2ce59cbfb..67fc2df61c 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/AndroidBluetoothTransport.kt@@ -2,17 +2,25 @@ package com.vayunmathur.library.wearlink  import android.Manifest import android.annotation.SuppressLint+import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothServerSocket as BtServerSocket import android.bluetooth.BluetoothSocket as BtSocket+import android.content.BroadcastReceiver import android.content.Context+import android.content.Intent+import android.content.IntentFilter import android.content.pm.PackageManager+import android.os.ParcelUuid import androidx.core.content.ContextCompat import java.io.InputStream import java.io.OutputStream import java.util.UUID+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import java.util.concurrent.atomic.AtomicBoolean -/**+/*  * RFCOMM transport over the platform Bluetooth stack, verified against the  * local SDK (android-37): `BluetoothManager.adapter`,  * `adapter.bondedDevices`, `device.createRfcommSocketToServiceRecord(uuid)`,@@ -21,8 +29,10 @@ import java.util.UUID  *  * The Wear OS watch is already bonded to the phone by the system companion;  * third-party apps cannot ride that system link, so this is our own RFCOMM- * service on top of the same bond. No scanning: candidates come from the- * bonded set, which is also why no BLUETOOTH_SCAN/location is ever needed.+ * service on top of the same bond. The watch listens on the service record;+ * the phone dials only a bonded device whose SDP record proves it offers+ * the service (see hasService). No discovery scan is ever started, which+ * is also why no BLUETOOTH_SCAN/location is ever needed.  */ /** Runtime-permission entry for hosting activities (API 31+ runtime model). */ object WearLinkPermissions {@@ -82,6 +92,58 @@ class AndroidBluetoothTransport(private val context: Context) : WearLinkTranspor         return BtServerWrapper(server)     } +    /**+     * SDP proof that [peer] offers [serviceUuid]: the cached SDP record+     * first, then a live `fetchUuidsWithSdp` round waited out on the+     * calling (IO) thread. False when permission is missing, the device is+     * unknown, or SDP answers without the service.+     */+    @SuppressLint("MissingPermission") // guarded by hasConnectPermission() below+    override fun hasService(peer: BondedPeer, serviceUuid: UUID): Boolean {+        if (!hasConnectPermission()) return false+        val device = runCatching { adapter?.getRemoteDevice(peer.address) }.getOrNull() ?: return false+        if (cachedUuids(device)?.contains(serviceUuid) == true) return true+        return fetchUuids(device, serviceUuid)+    }++    @SuppressLint("MissingPermission") // callers guard via hasService; runCatching handles refusal+    private fun cachedUuids(device: BluetoothDevice): List<UUID>? =+        runCatching { device.uuids?.map { it.uuid } }.getOrNull()++    @SuppressLint("MissingPermission")+    private fun fetchUuids(device: BluetoothDevice, serviceUuid: UUID): Boolean {+        val latch = CountDownLatch(1)+        val found = AtomicBoolean(false)+        val receiver = object : BroadcastReceiver() {+            override fun onReceive(ctx: Context?, intent: Intent?) {+                val safeIntent = intent ?: return+                val foundDevice = safeIntent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)+                if (foundDevice?.address != device.address) return+                @Suppress("DEPRECATION")+                val parcelUuids: Array<ParcelUuid>? =+                    safeIntent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID) as? Array<ParcelUuid>+                found.set(parcelUuids?.any { it.uuid == serviceUuid } == true)+                latch.countDown()+            }+        }+        return try {+            ContextCompat.registerReceiver(+                context, receiver, IntentFilter(BluetoothDevice.ACTION_UUID),+                ContextCompat.RECEIVER_EXPORTED,+            )+            if (!device.fetchUuidsWithSdp()) {+                cachedUuids(device)?.contains(serviceUuid) == true+            } else {+                latch.await(SDP_TIMEOUT_MS, TimeUnit.MILLISECONDS)+                found.get() || cachedUuids(device)?.contains(serviceUuid) == true+            }+        } catch (expected: Exception) {+            cachedUuids(device)?.contains(serviceUuid) == true+        } finally {+            runCatching { context.unregisterReceiver(receiver) }+        }+    }+     private class BtSocketWrapper(         private val socket: BtSocket,         override val peerLabel: String,@@ -102,4 +164,29 @@ class AndroidBluetoothTransport(private val context: Context) : WearLinkTranspor          override fun close() = runCatching { server.close() }.let { Unit }     }++    companion object {+        private const val SDP_TIMEOUT_MS = 5_000L+    }+}++/** SharedPreferences-backed [PeerAddressCache] for the phone conduit host. */+class SharedPrefsPeerAddressCache(context: Context) : PeerAddressCache {+    private val prefs = context.applicationContext+        .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)++    override fun get(): String? = prefs.getString(KEY_ADDRESS, null)++    override fun put(address: String) {+        prefs.edit().putString(KEY_ADDRESS, address).apply()+    }++    override fun clear() {+        prefs.edit().remove(KEY_ADDRESS).apply()+    }++    companion object {+        private const val PREFS_NAME = "wearlink_peer"+        private const val KEY_ADDRESS = "paired_watch_address"+    } }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.ktindex 54f836fb9f..412496bc64 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkHandshake.kt@@ -62,20 +62,23 @@ data class HelloMessage(     val version: Int,     val appId: String,     val packageName: String,-    /** Random per-process id; simultaneous-dial tie-break key. */+    /** Random per-process id, kept for peer diagnostics. */     val instanceId: String,     val nonce: ByteArray,     val token: String,+    /** Sender's conduit role; the receiver requires its counterpart role. */+    val role: WearLinkRole? = null, ) {     fun encode(): ByteArray {         val app = appId.encodeToByteArray()         val pkg = packageName.encodeToByteArray()         val inst = instanceId.encodeToByteArray()         val tok = token.encodeToByteArray()+        val rol = (role?.wire ?: "").encodeToByteArray()         val out = java.io.ByteArrayOutputStream()         out.write(version)         writeField(out, app); writeField(out, pkg); writeField(out, inst)-        writeField(out, nonce); writeField(out, tok)+        writeField(out, nonce); writeField(out, tok); writeField(out, rol)         return out.toByteArray()     } @@ -83,7 +86,7 @@ data class HelloMessage(         if (other !is HelloMessage) return false         return version == other.version && appId == other.appId &&             packageName == other.packageName && instanceId == other.instanceId &&-            nonce.contentEquals(other.nonce) && token == other.token+            nonce.contentEquals(other.nonce) && token == other.token && role == other.role     }      override fun hashCode(): Int = appId.hashCode() * 31 + nonce.contentHashCode()@@ -97,9 +100,13 @@ data class HelloMessage(             val inst = readField(input) ?: return null             val nonce = readField(input) ?: return null             val tok = readField(input) ?: return null+            // Trailing role field; absent in a pre-role hello, which the+            // verifier then rejects wherever a role is required.+            val rol = readField(input)             HelloMessage(                 version, app.decodeToString(), pkg.decodeToString(),                 inst.decodeToString(), nonce, tok.decodeToString(),+                rol?.decodeToString()?.let { WearLinkRole.fromWire(it) },             )         }.getOrNull() @@ -125,7 +132,7 @@ data class HelloMessage(     } } -/** Pure handshake verification + simultaneous-dial tie-break. */+/** Pure handshake verification. */ object HandshakeVerifier {     sealed interface Result {         data class Accepted(val peer: HelloMessage) : Result@@ -136,32 +143,30 @@ object HandshakeVerifier {      * Verify a peer HELLO against our identity. [peerNonceForToken] is the      * nonce *we* sent (for HELLO_ACK) or the peer's own nonce (for HELLO):      * HELLO token binds the sender's nonce, ACK token binds both — here the-     * caller supplies the nonce the token was computed over.+     * caller supplies the nonce the token was computed over. When+     * [expectedPeerRole] is given, the peer must declare exactly that role:+     * the phone accepts only a watch, the watch only a phone.      */     fun verify(         hello: HelloMessage,         expectedAppId: String,         ownCertHashHex: String,         tokenNonce: ByteArray,+        expectedPeerRole: WearLinkRole? = null,     ): Result {         if (hello.version != WearLinkProtocol.PROTOCOL_VERSION) {             return Result.Rejected("protocol version ${hello.version}")         }         if (hello.appId != expectedAppId) return Result.Rejected("app mismatch")+        if (expectedPeerRole != null && hello.role != expectedPeerRole) {+            return Result.Rejected(+                "role mismatch: expected $expectedPeerRole, got ${hello.role ?: "none"}",+            )+        }         val expected = WearLinkHandshake.token(ownCertHashHex, tokenNonce, expectedAppId)         val ok = MessageDigest.isEqual(             expected.encodeToByteArray(), hello.token.encodeToByteArray(),         )         return if (ok) Result.Accepted(hello) else Result.Rejected("signing token mismatch")     }--    /**-     * When both sides dialled at once there are two socket pairs. Keep the-     * pair initiated by the smaller instanceId — both ends compute the same-     * winner from the two instance ids they know (their own + the peer's).-     */-    fun keepInitiatedBySmallerInstance(-        existingInitiatorInstance: String,-        candidateInitiatorInstance: String,-    ): Boolean = candidateInitiatorInstance < existingInitiatorInstance }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.ktindex c8d0d970d1..f911290ddd 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkNode.kt@@ -70,21 +70,25 @@ class FileStreamSource(private val file: File, override val sha256: String) : St }  /**- * One peer link for one app. Owns accept + dial loops (either side may- * initiate), the handshake, framing, data-item reassembly, stream transfers- * and reconnect/backoff. Listeners become app-lifecycle-bound: unlike the- * old GMS WearableListenerService, nothing wakes a dead process when a- * message arrives — sync resumes on next start() and state documents are- * republished then. That is the honest cost of dropping Play services.+ * One peer link for one app. The watch role owns the single accept loop and+ * never dials; the phone role owns the single dial loop and never listens,+ * dialling only its SDP-verified paired watch (see [PairedWatchSelector]).+ * The node owns the handshake, framing, data-item reassembly, stream+ * transfers and reconnect/backoff. Listeners become app-lifecycle-bound:+ * unlike the old GMS WearableListenerService, nothing wakes a dead process+ * when a message arrives — sync resumes on next start() and state documents+ * are republished then. That is the honest cost of dropping Play services.  */ class WearLinkNode(     context: Context,     private val appId: String,     private val listener: WearLinkListener,+    val role: WearLinkRole,     private val transport: WearLinkTransport = AndroidBluetoothTransport(context.applicationContext),     private val certHashHex: String? = SigningTrust.localCertHashHex(context.applicationContext),     private val packageName: String = context.applicationContext.packageName,     parentScope: CoroutineScope? = null,+    private val peerCache: PeerAddressCache? = null, ) {     companion object {         private const val TAG = "WearLink"@@ -116,7 +120,6 @@ class WearLinkNode(      private inner class Session(         val socket: WearLinkSocket,-        val initiatorInstance: String,     ) {         private val writeLock = Any() @@ -153,8 +156,13 @@ class WearLinkNode(             return         }         running = true-        acceptJob = scope.launch { acceptLoop() }-        connectJob = scope.launch { connectLoop() }+        // Fixed roles: the watch only ever listens, the phone only ever dials.+        if (WearLinkRolePolicy.listens(role)) {+            acceptJob = scope.launch { acceptLoop() }+        }+        if (WearLinkRolePolicy.dials(role)) {+            connectJob = scope.launch { connectLoop() }+        }     }      fun stop() {@@ -256,12 +264,16 @@ class WearLinkNode(     // -- Connection loops ----------------------------------------------------      private suspend fun acceptLoop() {+        // Watch role only: one listener, retried with calm backoff. The+        // watch never dials, scans or rotates across devices.+        val backoff = WearLinkBackoff()         while (running) {             try {                 val server = transport.listen(WearLinkProtocol.SERVICE_UUID, WearLinkProtocol.SERVICE_NAME)                 try {                     while (running) {                         val socket = server.accept()+                        backoff.reset()                         scope.launch { handshakeAndAdopt(socket, isInitiator = false) }                     }                 } finally {@@ -269,13 +281,17 @@ class WearLinkNode(                 }             } catch (expected: Exception) {                 Log.status(TAG, "listen/accept failed: ${expected::class.simpleName}: ${expected.message}")-                if (running) delay(1_000)+                if (running) delay(backoff.nextDelayMillis())             }         }     }      private suspend fun connectLoop() {+        // Phone role only: one held connection to the paired watch. The+        // selector admits only SDP-verified bonded devices, so bonded+        // phones, headsets and other watches are never dialled in rotation.         val backoff = WearLinkBackoff()+        val selector = PairedWatchSelector(transport, peerCache, WearLinkProtocol.SERVICE_UUID)         while (running) {             if (activeSession != null) {                 backoff.reset()@@ -284,7 +300,7 @@ class WearLinkNode(             }             // Snapshot: the dial loop iterates this while connects block, so             // it must not alias a live transport-owned list.-            val peers = ArrayList(transport.bondedPeers())+            val peers = ArrayList(selector.selectPeers())             if (peers.isEmpty()) {                 _state.value = WearLinkState.NoBondedPeer                 delay(backoff.nextDelayMillis())@@ -298,10 +314,14 @@ class WearLinkNode(                     val socket = transport.connect(peer, WearLinkProtocol.SERVICE_UUID)                     connected = handshakeAndAdopt(socket, isInitiator = true)                 }.onFailure { Log.status(TAG, "connect ${peer.label} failed: ${it.message}") }-                if (connected) break+                if (connected) {+                    selector.onConnected(peer)+                    break+                }+                selector.onConnectFailure(peer)             }             if (!connected && activeSession == null) {-                _state.value = WearLinkState.Failed("no bonded peer runs $appId")+                _state.value = WearLinkState.Failed("no paired watch runs $appId")                 delay(backoff.nextDelayMillis())             }         }@@ -309,14 +329,20 @@ class WearLinkNode(      /** Run the handshake on [socket]; adopt if it wins. Returns adoption. */     private fun handshakeAndAdopt(socket: WearLinkSocket, isInitiator: Boolean): Boolean {+        if (!WearLinkRolePolicy.acceptsInitiation(role, isInitiator)) {+            Log.status(TAG, "refusing ${if (isInitiator) "dial" else "accept"} in role $role")+            runCatching { socket.close() }+            return false+        }         val cert = certHashHex ?: run { socket.close(); return false }+        val expectedPeerRole = WearLinkRolePolicy.expectedPeerRole(role)         return try {             val session: Session             if (isInitiator) {                 val nonce = WearLinkHandshake.newNonce()                 val hello = HelloMessage(                     WearLinkProtocol.PROTOCOL_VERSION, appId, packageName, instanceId,-                    nonce, WearLinkHandshake.token(cert, nonce, appId),+                    nonce, WearLinkHandshake.token(cert, nonce, appId), role,                 )                 FrameCodec.encode(WearLinkFrame(FrameType.HELLO, 0, "", hello.encode()), socket.output)                 val ackFrame = FrameCodec.decode(socket.input)@@ -324,18 +350,18 @@ class WearLinkNode(                 val ack = HelloMessage.decode(ackFrame.body)                     ?: throw java.io.IOException("bad hello ack")                 val combined = nonce + ack.nonce-                when (val result = HandshakeVerifier.verify(ack, appId, cert, combined)) {+                when (val result = HandshakeVerifier.verify(ack, appId, cert, combined, expectedPeerRole)) {                     is HandshakeVerifier.Result.Rejected ->                         throw java.io.IOException("handshake rejected: ${result.reason}")                     is HandshakeVerifier.Result.Accepted -> Unit                 }-                session = Session(socket, instanceId)+                session = Session(socket)             } else {                 val helloFrame = FrameCodec.decode(socket.input)                     ?: throw java.io.IOException("eof in handshake")                 val hello = HelloMessage.decode(helloFrame.body)                     ?: throw java.io.IOException("bad hello")-                when (val result = HandshakeVerifier.verify(hello, appId, cert, hello.nonce)) {+                when (val result = HandshakeVerifier.verify(hello, appId, cert, hello.nonce, expectedPeerRole)) {                     is HandshakeVerifier.Result.Rejected ->                         throw java.io.IOException("handshake rejected: ${result.reason}")                     is HandshakeVerifier.Result.Accepted -> Unit@@ -344,12 +370,12 @@ class WearLinkNode(                 val ack = HelloMessage(                     WearLinkProtocol.PROTOCOL_VERSION, appId, packageName, instanceId,                     ackNonce,-                    WearLinkHandshake.token(cert, hello.nonce + ackNonce, appId),+                    WearLinkHandshake.token(cert, hello.nonce + ackNonce, appId), role,                 )                 FrameCodec.encode(                     WearLinkFrame(FrameType.HELLO_ACK, 0, "", ack.encode()), socket.output,                 )-                session = Session(socket, hello.instanceId)+                session = Session(socket)             }             adopt(session, socket.peerLabel)         } catch (expected: Exception) {@@ -361,16 +387,12 @@ class WearLinkNode(      @Synchronized     private fun adopt(session: Session, peerLabel: String): Boolean {+        // One held connection: a second candidate never displaces the live+        // session, so the link cannot flap between socket pairs.         val existing = activeSession         if (existing != null && existing.open) {-            val keepCandidate = HandshakeVerifier.keepInitiatedBySmallerInstance(-                existing.initiatorInstance, session.initiatorInstance,-            )-            if (!keepCandidate) {-                session.close()-                return false-            }-            existing.close()+            session.close()+            return false         }         activeSession = session         _state.value = WearLinkState.Connected(peerLabel)
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.ktindex d8434486c7..73f21fac34 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkProtocol.kt@@ -14,9 +14,11 @@ import java.util.UUID  * it up in the bonded set, so there is no scan and no advertisement (hence  * no BLUETOOTH_SCAN/ADVERTISE and no location-permission workaround).  *- * Both sides run an accept loop on [SERVICE_UUID] and both sides dial bonded- * devices, so either side can initiate. Simultaneous dials are resolved by- * the handshake instance-id tie-break (see [WearLinkHandshake]).+ * The watch listens on [SERVICE_UUID] and never dials. The phone dials+ * only its paired watch: a bonded device whose SDP record offers+ * [SERVICE_UUID]. The handshake carries each side's role (initiator is the+ * phone, acceptor is the watch) and rejects any other pairing, so a phone+ * can never connect to a phone, nor a watch to a watch.  */ object WearLinkProtocol {     /** RFCOMM service record UUID ("MAWL" + v1). Fixed: changing it is a new protocol. */
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkRoles.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkRoles.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkRoles.ktnew file mode 100644index 0000000000..438022c0d9--- /dev/null+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkRoles.kt@@ -0,0 +1,99 @@+package com.vayunmathur.library.wearlink++import java.util.UUID++/**+ * Fixed conduit role for one device. The watch advertises the WearLink+ * RFCOMM service by listening for it; the phone is the only side that ever+ * dials, and only to its paired watch. Roles are carried in the handshake+ * so a phone can never pair with a phone, nor a watch with a watch.+ */+enum class WearLinkRole(+    val wire: String,+) {+    PHONE("phone"),+    WATCH("watch"),+    ;++    companion object {+        fun fromWire(wire: String?): WearLinkRole? = entries.firstOrNull { it.wire == wire }+    }+}++/** Which half of the link each role owns: the watch listens, the phone dials. */+object WearLinkRolePolicy {+    fun listens(role: WearLinkRole): Boolean = role == WearLinkRole.WATCH++    fun dials(role: WearLinkRole): Boolean = role == WearLinkRole.PHONE++    fun expectedPeerRole(own: WearLinkRole): WearLinkRole =+        if (own == WearLinkRole.PHONE) WearLinkRole.WATCH else WearLinkRole.PHONE++    /** True when [role] may take part in a session in the given capacity. */+    fun acceptsInitiation(+        role: WearLinkRole,+        isInitiator: Boolean,+    ): Boolean = if (isInitiator) dials(role) else listens(role)+}++/** Proven paired-watch address, remembered across restarts by the phone. */+interface PeerAddressCache {+    fun get(): String?++    fun put(address: String)++    fun clear()+}++/** In-memory [PeerAddressCache] for tests and short-lived nodes. */+class InMemoryPeerAddressCache : PeerAddressCache {+    @Volatile private var address: String? = null++    override fun get(): String? = address++    override fun put(address: String) {+        this.address = address+    }++    override fun clear() {+        address = null+    }+}++/**+ * Phone-side paired-watch selection. Candidates come only from the bonded+ * set, and a bonded device counts as the watch only when SDP proves it+ * offers the WearLink service UUID — no blind dial of every bonded device,+ * and no rotation across devices that do not run the service.+ *+ * A cached address wins only while it still passes the same SDP proof;+ * the first candidate that fails drops the cache so a stale address is+ * re-verified from the bonded set instead of being dialled forever.+ */+class PairedWatchSelector(+    private val transport: WearLinkTransport,+    private val cache: PeerAddressCache?,+    private val serviceUuid: UUID,+) {+    /** Ordered candidates: the re-verified cached watch first, else every SDP-verified bonded device. */+    fun selectPeers(): List<BondedPeer> {+        val bonded = transport.bondedPeers()+        val cachedAddress = cache?.get()+        if (cachedAddress != null) {+            val cached = bonded.firstOrNull { it.address == cachedAddress }+            if (cached != null && transport.hasService(cached, serviceUuid)) return listOf(cached)+            cache.clear()+        }+        return bonded.filter { transport.hasService(it, serviceUuid) }+    }++    /** Record [peer] as the proven watch after a completed handshake. */+    fun onConnected(peer: BondedPeer) {+        cache?.put(peer.address)+    }++    /** Forget the cached watch when the proven address stops working. */+    fun onConnectFailure(peer: BondedPeer) {+        if (cache?.get() == peer.address) cache.clear()+    }+}
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.ktindex 90468cb022..91d40c5c45 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/WearLinkTransport.kt@@ -40,4 +40,10 @@ interface WearLinkTransport {      /** Blocking-accept RFCOMM server for [serviceUuid]. */     fun listen(serviceUuid: UUID, serviceName: String): WearLinkServerSocket++    /**+     * True when SDP proves [peer] offers [serviceUuid]. The phone dials+     * only peers that pass this proof; fakes answer from their fixture set.+     */+    fun hasService(peer: BondedPeer, serviceUuid: UUID): Boolean = false }
library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt
diff --git a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.ktindex f53b711bd6..941d8e781d 100644--- a/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt+++ b/library/wearlink/src/main/java/com/vayunmathur/library/wearlink/conduit/ConduitHost.kt@@ -11,10 +11,12 @@ import android.os.Messenger import android.os.RemoteException import com.vayunmathur.library.log.Log import com.vayunmathur.library.wearlink.FileStreamSource+import com.vayunmathur.library.wearlink.SharedPrefsPeerAddressCache import com.vayunmathur.library.wearlink.StreamHeader import com.vayunmathur.library.wearlink.StreamSink import com.vayunmathur.library.wearlink.WearLinkListener import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkRole import com.vayunmathur.library.wearlink.WearLinkState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -28,7 +30,9 @@ import java.util.concurrent.atomic.AtomicLong /**  * Android host behind each Watch app's thin `ConduitService`: owns the  * single [WearLinkNode] (appId `watch_conduit`) plus a [ConduitRouter],- * and speaks [ConduitProtocol] to local clients over Messenger.+ * and speaks [ConduitProtocol] to local clients over Messenger. The host+ * is created with this device's fixed [WearLinkRole]: the watch listens+ * for the phone, the phone dials its paired watch.  *  * Trust: the service is bound under the signature permission, and on  * register the host additionally verifies that the claimed caller@@ -45,6 +49,7 @@ import java.util.concurrent.atomic.AtomicLong  */ class ConduitHost(     private val context: Context,+    private val role: WearLinkRole, ) {     private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)     private val streamIds = AtomicLong(1)@@ -148,7 +153,13 @@ class ConduitHost(             }         } -    private val node: WearLinkNode = WearLinkNode(context, ConduitProtocol.CONDUIT_APP_ID, peerListener)+    private val node: WearLinkNode = WearLinkNode(+        context,+        ConduitProtocol.CONDUIT_APP_ID,+        peerListener,+        role,+        peerCache = if (role == WearLinkRole.PHONE) SharedPrefsPeerAddressCache(context) else null,+    )      /** The link state of the single peer node, for the hosting service/UI. */     val nodeState get() = node.state
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.ktindex 5b05fa4435..d02401b52f 100644--- a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkProtocolTest.kt@@ -74,9 +74,33 @@ class WearLinkProtocolTest {     }      @Test-    fun `simultaneous dial tie break is symmetric`() {-        assertTrue(HandshakeVerifier.keepInitiatedBySmallerInstance("b", "a"))-        assertFalse(HandshakeVerifier.keepInitiatedBySmallerInstance("a", "b"))+    fun `handshake carries role and rejects mismatched roles`() {+        val cert = WearLinkHandshake.certHashHex("cert-der".encodeToByteArray())+        val nonce = ByteArray(WearLinkHandshake.NONCE_BYTES) { it.toByte() }+        fun hello(role: WearLinkRole?) = HelloMessage(+            WearLinkProtocol.PROTOCOL_VERSION, "watch_conduit",+            "com.vayunmathur.watch", "phone-1", nonce,+            WearLinkHandshake.token(cert, nonce, "watch_conduit"), role,+        )+        // Phone hello accepted where a phone is required, rejected as a watch.+        assertTrue(+            HandshakeVerifier.verify(+                hello(WearLinkRole.PHONE), "watch_conduit", cert, nonce, WearLinkRole.PHONE,+            ) is HandshakeVerifier.Result.Accepted,+        )+        assertTrue(+            HandshakeVerifier.verify(+                hello(WearLinkRole.WATCH), "watch_conduit", cert, nonce, WearLinkRole.PHONE,+            ) is HandshakeVerifier.Result.Rejected,+        )+        // A pre-role hello carries no role and is rejected where one is required.+        assertTrue(+            HandshakeVerifier.verify(+                hello(null), "watch_conduit", cert, nonce, WearLinkRole.PHONE,+            ) is HandshakeVerifier.Result.Rejected,+        )+        // Role survives the binary round-trip.+        assertEquals(hello(WearLinkRole.WATCH), HelloMessage.decode(hello(WearLinkRole.WATCH).encode()))     }      @Test
library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkRolesTest.kt
diff --git a/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkRolesTest.kt b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkRolesTest.ktnew file mode 100644index 0000000000..6daf6eec4b--- /dev/null+++ b/library/wearlink/src/test/java/com/vayunmathur/library/wearlink/WearLinkRolesTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.library.wearlink++import java.util.UUID+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class WearLinkRolesTest {+    private class FakeTransport(+        private val peers: List<BondedPeer>,+        private val withService: Set<String>,+    ) : WearLinkTransport {+        var connectCalls = 0+        var listenCalls = 0++        override fun isAvailable(): Boolean = true++        override fun bondedPeers(): List<BondedPeer> = peers++        override fun connect(+            peer: BondedPeer,+            serviceUuid: UUID,+        ): WearLinkSocket {+            connectCalls+++            throw IllegalStateException("selection must not dial")+        }++        override fun listen(+            serviceUuid: UUID,+            serviceName: String,+        ): WearLinkServerSocket {+            listenCalls+++            throw IllegalStateException("selection must not listen")+        }++        override fun hasService(+            peer: BondedPeer,+            serviceUuid: UUID,+        ): Boolean = serviceUuid == WearLinkProtocol.SERVICE_UUID && peer.address in withService+    }++    @Test+    fun `watch listens and never dials, phone dials and never listens`() {+        assertTrue(WearLinkRolePolicy.listens(WearLinkRole.WATCH))+        assertFalse(WearLinkRolePolicy.dials(WearLinkRole.WATCH))+        assertFalse(WearLinkRolePolicy.acceptsInitiation(WearLinkRole.WATCH, isInitiator = true))+        assertTrue(WearLinkRolePolicy.acceptsInitiation(WearLinkRole.WATCH, isInitiator = false))++        assertTrue(WearLinkRolePolicy.dials(WearLinkRole.PHONE))+        assertFalse(WearLinkRolePolicy.listens(WearLinkRole.PHONE))+        assertTrue(WearLinkRolePolicy.acceptsInitiation(WearLinkRole.PHONE, isInitiator = true))+        assertFalse(WearLinkRolePolicy.acceptsInitiation(WearLinkRole.PHONE, isInitiator = false))++        // Each role expects exactly its counterpart on the other end.+        assertEquals(WearLinkRole.WATCH, WearLinkRolePolicy.expectedPeerRole(WearLinkRole.PHONE))+        assertEquals(WearLinkRole.PHONE, WearLinkRolePolicy.expectedPeerRole(WearLinkRole.WATCH))+    }++    @Test+    fun `selection requires SDP service proof and never dials or listens`() {+        val phone = BondedPeer("AA:01", "other phone")+        val headset = BondedPeer("AA:02", "headset")+        val watch = BondedPeer("AA:03", "watch")+        val transport = FakeTransport(listOf(phone, headset, watch), setOf(watch.address))+        val selector = PairedWatchSelector(transport, InMemoryPeerAddressCache(), WearLinkProtocol.SERVICE_UUID)++        assertEquals(listOf(watch), selector.selectPeers())+        assertEquals(0, transport.connectCalls)+        assertEquals(0, transport.listenCalls)+    }++    @Test+    fun `cached watch is used only while SDP still proves it`() {+        val other = BondedPeer("AA:01", "other watch-like")+        val watch = BondedPeer("AA:03", "watch")+        val cache = InMemoryPeerAddressCache()+        cache.put(watch.address)++        // Cached and still proven: it is the only candidate.+        val proven =+            PairedWatchSelector(+                FakeTransport(listOf(other, watch), setOf(other.address, watch.address)),+                cache,+                WearLinkProtocol.SERVICE_UUID,+            )+        assertEquals(listOf(watch), proven.selectPeers())++        // Cached but no longer proven: cache drops, all proven devices qualify.+        val stale =+            PairedWatchSelector(+                FakeTransport(listOf(other, watch), setOf(other.address)),+                cache,+                WearLinkProtocol.SERVICE_UUID,+            )+        assertEquals(listOf(other), stale.selectPeers())+        assertEquals(null, cache.get())+    }++    @Test+    fun `proven watch is cached on connect and forgotten on failure`() {+        val watch = BondedPeer("AA:03", "watch")+        val other = BondedPeer("AA:04", "other")+        val cache = InMemoryPeerAddressCache()+        val selector =+            PairedWatchSelector(+                FakeTransport(listOf(watch), setOf(watch.address)),+                cache,+                WearLinkProtocol.SERVICE_UUID,+            )+        selector.onConnected(watch)+        assertEquals(watch.address, cache.get())+        // A failure for a different device keeps the proven cache.+        selector.onConnectFailure(other)+        assertEquals(watch.address, cache.get())+        // A failure for the cached watch itself drops it for re-verification.+        selector.onConnectFailure(watch)+        assertEquals(null, cache.get())+    }++    @Test+    fun `reconnect backoff doubles to its ceiling and resets`() {+        // The state machine both loops share: calm, bounded retries.+        val backoff = WearLinkBackoff()+        assertEquals(1_000L, backoff.nextDelayMillis())+        assertEquals(2_000L, backoff.nextDelayMillis())+        assertEquals(4_000L, backoff.nextDelayMillis())+        assertEquals(8_000L, backoff.nextDelayMillis())+        assertEquals(16_000L, backoff.nextDelayMillis())+        assertEquals(30_000L, backoff.nextDelayMillis())+        assertEquals(30_000L, backoff.nextDelayMillis())+        backoff.reset()+        assertEquals(1_000L, backoff.nextDelayMillis())+    }++    @Test+    fun `role wire values round trip`() {+        assertEquals(WearLinkRole.PHONE, WearLinkRole.fromWire("phone"))+        assertEquals(WearLinkRole.WATCH, WearLinkRole.fromWire("watch"))+        assertEquals(null, WearLinkRole.fromWire("tablet"))+        assertEquals(null, WearLinkRole.fromWire(null))+    }+}
watch-wear/AGENTS.md
diff --git a/watch-wear/AGENTS.md b/watch-wear/AGENTS.mdindex b986571ac1..843e739919 100644--- a/watch-wear/AGENTS.md+++ b/watch-wear/AGENTS.md@@ -15,7 +15,8 @@ shared dev/release signing: the WearLink handshake token and the `com.vayunmathur.watch.permissions.CONDUIT` signature permission both require the same signing certificate on both sides. It is the only watch app that holds Bluetooth permissions and the only one that owns-a real `WearLinkNode` (appId `watch_conduit`, in+a real `WearLinkNode` (appId `watch_conduit`, role `WATCH`: it listens+on the WearLink service record and never dials, in `service/ConduitService` via `ConduitHost` in `:library:wearlink`). Every other watch app reaches the phone through `WearLinkClientNode`. 
watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt
diff --git a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.ktindex 3edc270107..31a2d6eaee 100644--- a/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt+++ b/watch-wear/src/main/java/com/vayunmathur/watch/wear/service/ConduitService.kt@@ -10,6 +10,7 @@ import android.content.pm.ServiceInfo import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat+import com.vayunmathur.library.wearlink.WearLinkRole import com.vayunmathur.library.wearlink.conduit.ConduitHost  /**@@ -29,7 +30,7 @@ class ConduitService : Service() {      override fun onCreate() {         super.onCreate()-        host = ConduitHost(applicationContext)+        host = ConduitHost(applicationContext, WearLinkRole.WATCH)         MediaControlsBridge.start(applicationContext)         createChannel()     }
watch/AGENTS.md
diff --git a/watch/AGENTS.md b/watch/AGENTS.mdindex 8108897c68..cf5bbfbc55 100644--- a/watch/AGENTS.md+++ b/watch/AGENTS.md@@ -13,7 +13,9 @@ **Purpose:** Phone half of the Watch conduit — the sole phone<->watch messaging app on the phone. It is the only phone app that holds Bluetooth permissions and the only one that owns a real-`WearLinkNode` (appId `watch_conduit`, in `service/ConduitService`+`WearLinkNode` (appId `watch_conduit`, role `PHONE`: it dials its+SDP-verified paired watch and never listens for the conduit, in+`service/ConduitService` via `ConduitHost` in `:library:wearlink`). Every other app reaches the watch through `WearLinkClientNode` bound to this app's conduit service.
watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt
diff --git a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.ktindex 7ab5e807b4..4955e6f2a8 100644--- a/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt+++ b/watch/src/main/java/com/vayunmathur/watch/service/ConduitService.kt@@ -10,6 +10,7 @@ import android.content.pm.ServiceInfo import android.os.IBinder import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat+import com.vayunmathur.library.wearlink.WearLinkRole import com.vayunmathur.library.wearlink.conduit.ConduitHost import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -33,7 +34,7 @@ class ConduitService : Service() {      override fun onCreate() {         super.onCreate()-        host = ConduitHost(applicationContext)+        host = ConduitHost(applicationContext, WearLinkRole.PHONE)         // The media bridge is a conduit client of this host (appId         // mediacontrols). Start it with the host, not only from the         // transient MainActivity or the notification listener: after