Modern Apps git

← Modern-Apps.git

wear: communicate full-navigation companion

Commit
344c7cb0232559471270f89951d0b06f3d090845
Author
Vayun Mathur <[email protected]>
When
2026-11-25 01:22 UTC (11 days ago)
Parents
0db2493
New :communicate-wear (phone app's package/signing):
watch mirrors the merged conversation list, thread
view (paged, capped, offline-cached), call log, and
voicemail indicators. Ops execute on the phone -
quick reply (canned + dictated), mark read, mark
voicemail read, decline call (no fake answer-on-watch:
no guaranteed watch audio route, stated). Disappearing
messages cross as excluded markers, never plaintext;
decryption stays phone-side; media is labels only,
never bytes. Omissions (dialer, accounts, media,
settings) are listed in-app and in AGENTS.

Verified: wear assemble + tests; phone suite 1457
green (incl. disappearing-exclusion asserted absent
from encoded JSON).

Diff

communicate-wear/AGENTS.md
diff --git a/communicate-wear/AGENTS.md b/communicate-wear/AGENTS.mdnew file mode 100644index 0000000000..e61f9f121d--- /dev/null+++ b/communicate-wear/AGENTS.md@@ -0,0 +1,52 @@+# AGENTS.md — communicate-wear/ (':communicate-wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `communicate-wear/` + `communicate/` (the phone side of the same feature).++- Gradle: :communicate-wear / dir: communicate-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Communicate (`:communicate`). This module+deliberately uses `applicationId = "com.vayunmathur.communicate"` (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+`domain/WearCommunicateProtocol.kt` is a copy of the phone's file (Gradle+cannot depend on another app module). Change both copies together; each+side's `WearCommunicateProtocolTest` pins the same golden JSON.++- Snapshot: WearLink data item (`/communicate/snapshot`, phone -> watch);+  watch state back (`/communicate/watch-state`)+- Thread pages: message request (`/communicate/request-thread`) ->+  message page (`/communicate/thread-page`), cached on the watch+- Alerts: messages (`/communicate/new-message`, `/communicate/incoming-call`)+- Watch ops: message (`/communicate/op`) + phone verdict+  (`/communicate/op-result`); ops stay pending until a success verdict+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Page mapping (mirrors the phone, stated in the protocol file too)+- Phone Messages -> watch conversation list (all merged lines)+- Phone Conversation -> watch thread view (paged, cached offline)+- Phone CallLogs -> watch call log (read-only)+- Phone voicemail -> watch voicemail indicators (no audio/URIs/headers)+- Omitted: Dialer, Accounts/registration, calling setup, Call screen,+  voicemail playback, media viewing, full settings, archive/mute (the+  phone UI offers neither), and answer-on-watch (no guaranteed watch+  audio route — decline only)++## Privacy+Disappearing-flagged content never crosses in body/snippet form (empty ++`contentExcluded` marker). E2EE plaintext is decrypted on the phone and+only capped text crosses the cert-bound link; no keys, serviceData, media+URLs or attachment bytes ever cross (media is a label only).++## Verify (this module only)+```+./gradlew :communicate-wear:assembleDev+./gradlew :communicate-wear:testDebugUnitTest+```
communicate-wear/build.gradle.kts
diff --git a/communicate-wear/build.gradle.kts b/communicate-wear/build.gradle.ktsnew file mode 100644index 0000000000..e88fec3045--- /dev/null+++ b/communicate-wear/build.gradle.kts@@ -0,0 +1,39 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "call"+}++// Version shared with the phone app (root version.txt), read directly because+// common-conventions-wear inlines 1/"1.0" until a wear consumer wires the shared reader.+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+    // The WearLink handshake only connects apps that share a package name and+    // signing certificate, so this module MUST ship as the phone app's package:+    // same applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The namespace only names this module's own R/resources.+    namespace = "com.vayunmathur.communicate.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.communicate"+        // Convention defaults to 30, but :library:log (pulled in by the wear+        // convention) requires 31, so the watch floor is 31.+        minSdk = 31+        versionCode = wearVersionCode+        versionName = wearVersionName+    }+}++dependencies {+    // Watch side of the Wear OS sync (see domain/WearCommunicateProtocol.kt, the+    // copy of the phone protocol it must stay in step with).+    implementation(libs.kotlinx.coroutines.android)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
communicate-wear/src/main/AndroidManifest.xml
diff --git a/communicate-wear/src/main/AndroidManifest.xml b/communicate-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7ccb8c3001--- /dev/null+++ b/communicate-wear/src/main/AndroidManifest.xml@@ -0,0 +1,40 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <!-- Wear OS form factor. Declaring the watch hardware makes this build+         installable on Wear OS; the touchscreen is not required there. -->+    <uses-feature+        android:name="android.hardware.type.watch"+        android:required="true" />+    <uses-feature+        android:name="android.hardware.touchscreen"+        android:required="false" />++    <uses-permission android:name="android.permission.WAKE_LOCK" />++    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">++        <!-- Paired with the phone app, not a standalone watch app. -->+        <meta-data+            android:name="com.google.android.wearable.standalone"+            android:value="false" />++        <activity+            android:name=".ui.WearMainActivity"+            android:exported="true"+            android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>++        <!-- WearLink delivery is app-lifecycle-bound; no system listener service. -->+    </application>+</manifest>
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/data/WearCommunicateStore.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/data/WearCommunicateStore.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/data/WearCommunicateStore.ktnew file mode 100644index 0000000000..aad0714ea0--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/data/WearCommunicateStore.kt@@ -0,0 +1,199 @@+package com.vayunmathur.communicate.wear.data++import android.content.Context+import com.vayunmathur.communicate.wear.domain.WearCommOp+import com.vayunmathur.communicate.wear.domain.WearCommunicateSnapshot+import com.vayunmathur.communicate.wear.domain.WearIncomingCall+import com.vayunmathur.communicate.wear.domain.WearMessage+import com.vayunmathur.communicate.wear.domain.WearNewMessageAlert+import com.vayunmathur.communicate.wear.domain.WearCommunicateProtocol+import com.vayunmathur.communicate.wear.domain.WearOpKind+import com.vayunmathur.communicate.wear.domain.WearOpResult+import com.vayunmathur.communicate.wear.domain.WearThread+import com.vayunmathur.communicate.wear.domain.WearThreadPage+import com.vayunmathur.communicate.wear.domain.WearVoicemail+import com.vayunmathur.communicate.wear.domain.mergeWearThreadPage+import com.vayunmathur.communicate.wear.domain.pendingAfterResult+import com.vayunmathur.library.log.Log+import java.io.File+import java.util.UUID+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString++/** Cached pages for one thread, persisted so threads read fully offline. */+@Serializable+data class WearThreadCache(+    val messages: List<WearMessage> = emptyList(),+    val hasMore: Boolean = false,+    val oldestTimestampMillis: Long = 0L,+)++/**+ * The watch's local truth: the last phone snapshot, paged thread caches,+ * and pending ops, persisted as JSON in app-private storage. An op stays+ * pending (persisted, resent on reconnect) until the phone's op-result+ * says it succeeded — the UI never claims the phone did something before+ * that verdict.+ */+class WearCommunicateStore private constructor(private val context: Context) {++    companion object {+        private const val TAG = "WearCommunicateStore"++        @Volatile+        private var instance: WearCommunicateStore? = null++        fun get(context: Context): WearCommunicateStore = instance ?: synchronized(this) {+            instance ?: WearCommunicateStore(context.applicationContext).also { instance = it }+        }+    }++    private val snapshotFile = File(context.filesDir, "wear-communicate-snapshot.json")+    private val pagesFile = File(context.filesDir, "wear-communicate-pages.json")+    private val pendingFile = File(context.filesDir, "wear-communicate-pending.json")++    private val _snapshot = MutableStateFlow(loadSnapshot())+    val snapshot: StateFlow<WearCommunicateSnapshot> = _snapshot.asStateFlow()++    private val _pages = MutableStateFlow(loadPages())+    val pages: StateFlow<Map<String, WearThreadCache>> = _pages.asStateFlow()++    private val _pendingOps = MutableStateFlow(loadPending())+    val pendingOps: StateFlow<List<WearCommOp>> = _pendingOps.asStateFlow()++    private val _incomingCall = MutableStateFlow<WearIncomingCall?>(null)+    val incomingCall: StateFlow<WearIncomingCall?> = _incomingCall.asStateFlow()++    private val _lastAlert = MutableStateFlow<WearNewMessageAlert?>(null)+    val lastAlert: StateFlow<WearNewMessageAlert?> = _lastAlert.asStateFlow()++    val appliedGeneratedAtMillis: Long get() = _snapshot.value.generatedAtMillis++    fun setSnapshot(snapshot: WearCommunicateSnapshot) {+        _snapshot.value = snapshot+        persist(snapshotFile, WearCommunicateProtocol.json.encodeToString(snapshot))+        com.vayunmathur.communicate.wear.sync.WearLinkBridge.publishWatchState(context)+    }++    /** Merges one arrived page into the thread cache (evicting the least recent threads). */+    fun setThreadPage(page: WearThreadPage) {+        val current = _pages.value.toMutableMap()+        val existing = current[page.threadKey] ?: WearThreadCache()+        current[page.threadKey] = WearThreadCache(+            messages = mergeWearThreadPage(existing.messages, page),+            hasMore = page.hasMore,+            oldestTimestampMillis = page.oldestTimestampMillis,+        )+        // Bound the cache: keep the most recently paged threads.+        val capped = if (current.size <= WearCommunicateProtocol.MAX_CACHED_THREADS) {+            current+        } else {+            current.entries.toList().takeLast(WearCommunicateProtocol.MAX_CACHED_THREADS)+                .associate { it.key to it.value }+        }+        _pages.value = capped+        persist(pagesFile, WearCommunicateProtocol.json.encodeToString(capped))+    }++    fun setIncomingCall(call: WearIncomingCall?) {+        _incomingCall.value = call+    }++    fun setAlert(alert: WearNewMessageAlert) {+        _lastAlert.value = alert+    }++    fun clearAlert() {+        _lastAlert.value = null+    }++    /** Applies a phone verdict: success drops the op, failure keeps it pending. */+    fun applyOpResult(result: WearOpResult) {+        val updated = pendingAfterResult(_pendingOps.value, result)+        if (updated != _pendingOps.value) {+            _pendingOps.value = updated+            persistPending()+        }+        if (result.kind == WearOpKind.DeclineCall && result.success) _incomingCall.value = null+    }++    fun queueReply(thread: WearThread, body: String): WearCommOp? {+        val trimmed = body.trim()+        if (trimmed.isEmpty()) return null+        return queue(+            WearCommOp(+                opId = UUID.randomUUID().toString(),+                kind = WearOpKind.QuickReply,+                threadKey = thread.key,+                line = thread.line,+                threadId = thread.threadId,+                remoteId = thread.remoteId,+                address = thread.address,+                subscriptionId = thread.subscriptionId,+                participants = thread.participants,+                body = trimmed.take(WearCommunicateProtocol.MAX_REPLY_CHARS),+            ),+        )+    }++    fun queueMarkRead(thread: WearThread): WearCommOp = queue(+        WearCommOp(+            opId = UUID.randomUUID().toString(),+            kind = WearOpKind.MarkRead,+            threadKey = thread.key,+            line = thread.line,+            threadId = thread.threadId,+            remoteId = thread.remoteId,+            address = thread.address,+        ),+    )++    fun queueMarkVoicemailRead(voicemail: WearVoicemail): WearCommOp = queue(+        WearCommOp(+            opId = UUID.randomUUID().toString(),+            kind = WearOpKind.MarkVoicemailRead,+            line = voicemail.line,+            targetKey = voicemail.key,+        ),+    )++    fun queueDeclineCall(call: WearIncomingCall): WearCommOp = queue(+        WearCommOp(+            opId = UUID.randomUUID().toString(),+            kind = WearOpKind.DeclineCall,+            line = call.line,+            targetKey = call.callKey,+        ),+    )++    private fun queue(op: WearCommOp): WearCommOp {+        _pendingOps.value = _pendingOps.value + op+        persistPending()+        com.vayunmathur.communicate.wear.sync.WearLinkBridge.flushPending(context)+        return op+    }++    private fun loadSnapshot(): WearCommunicateSnapshot = runCatching {+        WearCommunicateProtocol.json.decodeFromString<WearCommunicateSnapshot>(snapshotFile.readText())+    }.getOrDefault(WearCommunicateSnapshot())++    private fun loadPages(): Map<String, WearThreadCache> = runCatching {+        WearCommunicateProtocol.json.decodeFromString<Map<String, WearThreadCache>>(pagesFile.readText())+    }.getOrDefault(emptyMap())++    private fun loadPending(): List<WearCommOp> = runCatching {+        WearCommunicateProtocol.json.decodeFromString<List<WearCommOp>>(pendingFile.readText())+    }.getOrDefault(emptyList())++    private fun persistPending() {+        persist(pendingFile, WearCommunicateProtocol.json.encodeToString(_pendingOps.value))+    }++    private fun persist(file: File, text: String) {+        runCatching { file.writeText(text) }+            .onFailure { Log.status(TAG, "persist ${file.name} failed: ${it.message}") }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocol.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocol.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocol.ktnew file mode 100644index 0000000000..f3c46c057a--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocol.kt@@ -0,0 +1,421 @@+package com.vayunmathur.communicate.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Wear OS Communicate companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module+ * (`:communicate-wear`, applicationId `com.vayunmathur.communicate`) carries+ * a copy of this file under `com.vayunmathur.communicate.wear.domain`.+ * Change both copies together; each side's unit tests pin the same golden+ * JSON so a one-sided edit fails loudly.+ *+ * The watch mirrors the phone app's navigation, not a glance card:+ * conversation list (all lines the phone merges: SIM / Google Voice /+ * WhatsApp / Signal / RCS), one thread (paged), call log, and voicemail+ * indicators. All repository work and all decryption stay on the phone;+ * the watch only receives bounded snapshots/pages, caches them for offline+ * reading, and sends ops the phone executes.+ *+ * Page mapping (phone [com.vayunmathur.communicate.Route] -> watch):+ * - `Messages` -> conversation list. Mirrored.+ * - `Conversation(threadId, ...)` -> thread view. Mirrored, paged.+ * - `CallLogs` -> call log. Mirrored (read-only; no watch calling).+ * - Voicemail (inside the phone dialer flow) -> voicemail indicators:+ *   caller, time, duration, read state and a capped transcript. Audio+ *   playback, content URIs and GV audio auth headers NEVER cross.+ * - `Dialer` -> OMITTED: no watch telephony/audio route is guaranteed, so+ *   the watch never offers dialling or answer-on-watch.+ * - `Accounts`, registration wizards, `RcsStatus`/`RcsVerify`,+ *   `RcsGroupMembers`, `Call` -> OMITTED: calling setup, line registration,+ *   safety-number verification, group management, media viewing and full+ *   settings do not fit a wrist and stay phone-only.+ * - Archive/mute -> OMITTED: the phone UI offers neither (only the+ *   underlying WhatsApp/Signal DBs know the flags), so the watch offers+ *   no op the phone UI does not.+ *+ * Privacy choices (stated, not implied):+ * - Disappearing messages: a thread/message flagged disappearing is+ *   EXCLUDED in content — snippet and body cross as empty, media is not+ *   even counted, and only a `contentExcluded` marker remains so the+ *   watch can say why. Persisting their plaintext in a watch cache would+ *   defeat the feature. The phone detects this today for WhatsApp+ *   conversations (`ephemeralExpiration > 0`); other lines surface no+ *   unified flag, so their flag is false until they do.+ * - E2EE lines (WhatsApp/Signal/RCS-MLS): the phone is the endpoint and+ *   decrypts; capped plaintext then crosses the cert-bound WearLink+ *   session to the owner's same-signed watch, like the phone's own+ *   notification text. No keys, no serviceData JSON, no media URLs, no+ *   attachment bytes ever cross — media is a label ("Photo") only.+ *   Revoked messages cross with an empty body.+ * - New-message alerts are small messages: display name + capped snippet+ *   only when not disappearing (empty snippet then), never a full page.+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Data items: [SNAPSHOT_PATH] phone -> watch, [WATCH_STATE_PATH] back.+ * - Messages: [OP_PATH] watch -> phone, [OP_RESULT_PATH] phone -> watch,+ *   [REQUEST_SYNC_PATH] / [REQUEST_THREAD_PATH] watch -> phone,+ *   [THREAD_PAGE_PATH] / [NEW_MESSAGE_PATH] / [INCOMING_CALL_PATH]+ *   phone -> watch. Delivery needs a live session; nothing wakes a dead+ *   phone process, and the watch resends pending ops on reconnect.+ */+object WearCommunicateProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "communicate_wear_companion"++    const val SNAPSHOT_PATH = "/communicate/snapshot"+    const val WATCH_STATE_PATH = "/communicate/watch-state"+    const val OP_PATH = "/communicate/op"+    const val OP_RESULT_PATH = "/communicate/op-result"+    const val REQUEST_SYNC_PATH = "/communicate/request-sync"+    const val REQUEST_THREAD_PATH = "/communicate/request-thread"+    const val THREAD_PAGE_PATH = "/communicate/thread-page"+    const val NEW_MESSAGE_PATH = "/communicate/new-message"+    const val INCOMING_CALL_PATH = "/communicate/incoming-call"++    const val MAX_THREADS = 50+    const val MAX_CALLS = 50+    const val MAX_VOICEMAILS = 30+    const val MAX_JSON_BYTES = 90_000+    const val MAX_TITLE_CHARS = 80+    const val MAX_SNIPPET_CHARS = 120+    const val MAX_BODY_CHARS = 1_000+    const val MAX_TRANSCRIPT_CHARS = 200+    const val MAX_PAGE_MESSAGES = 20+    const val MAX_CACHED_MESSAGES_PER_THREAD = 100+    const val MAX_CACHED_THREADS = 10+    const val MAX_REPLY_CHARS = 1_000+    const val MAX_ALERT_SNIPPET_CHARS = 80++    /** Canned quick replies; free text (dictation/IME) is also accepted. */+    val CANNED_REPLIES = listOf(+        "On my way",+        "Call you later",+        "Can't talk right now",+        "OK",+        "Thanks",+    )++    val json: Json = Json { ignoreUnknownKeys = true }+}++/** Line names mirror the phone's `CommunicateLine` enum names exactly. */+@Serializable+enum class WearCommLine { Sim, GoogleVoice, WhatsApp, Signal, Rcs }++/** One conversation in the merged list, trimmed to watch size. */+@Serializable+data class WearThread(+    /** Stable watch key: `"<line>:<remoteId or threadId>"`. */+    val key: String,+    val threadId: Long = 0L,+    val line: WearCommLine = WearCommLine.Sim,+    val address: String = "",+    val remoteId: String? = null,+    val subscriptionId: Int? = null,+    val displayName: String = "",+    /** Capped snippet; empty when [contentExcluded]. */+    val snippet: String = "",+    val timestampMillis: Long = 0L,+    val unreadCount: Int = 0,+    val isGroup: Boolean = false,+    val groupTitle: String? = null,+    val participants: List<String> = emptyList(),+    /** True when the phone flagged disappearing messages for this thread. */+    val disappearing: Boolean = false,+    /** True when content was withheld (disappearing); snippet/body are empty. */+    val contentExcluded: Boolean = false,+)++/** One message in a thread page. Media is a label only; no URL/bytes cross. */+@Serializable+data class WearMessage(+    val messageKey: String,+    val threadKey: String = "",+    /** Capped body; empty when [contentExcluded] or revoked. */+    val body: String = "",+    val timestampMillis: Long = 0L,+    val outgoing: Boolean = false,+    val read: Boolean = true,+    val senderLabel: String? = null,+    /** Display label for an attachment ("Photo", "Video", "File"), or null. */+    val mediaLabel: String? = null,+    val status: String = "None",+    val disappearing: Boolean = false,+    val contentExcluded: Boolean = false,+    val bodyTruncated: Boolean = false,+)++/** One unified call-log row (read-only on the watch). */+@Serializable+data class WearCallEntry(+    val key: String,+    val displayName: String = "",+    val phoneNumber: String = "",+    /** Phone `CommunicateCallType` name. */+    val type: String = "Unknown",+    val timestampMillis: Long = 0L,+    val durationSeconds: Long = 0L,+    val line: WearCommLine = WearCommLine.Sim,+)++/** One voicemail indicator. No audio URI, no auth headers, no playback. */+@Serializable+data class WearVoicemail(+    val key: String,+    val phoneNumber: String = "",+    val timestampMillis: Long = 0L,+    val durationSeconds: Long = 0L,+    /** Capped transcript when the phone has one; never an audio reference. */+    val transcript: String = "",+    val isRead: Boolean = true,+    val line: WearCommLine = WearCommLine.Sim,+)++/** Bounded phone snapshot for the watch ([WearCommunicateProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearCommunicateSnapshot(+    val generatedAtMillis: Long = 0L,+    val threads: List<WearThread> = emptyList(),+    val calls: List<WearCallEntry> = emptyList(),+    val voicemails: List<WearVoicemail> = emptyList(),+    val voicemailUnreadCount: Int = 0,+    val truncated: Boolean = false,+)++/** One paged slice of a thread, oldest-to-newest inside the page. */+@Serializable+data class WearThreadPage(+    val threadKey: String = "",+    val messages: List<WearMessage> = emptyList(),+    /** True when older messages remain on the phone. */+    val hasMore: Boolean = false,+    /** Cursor for the next older page: oldest timestamp in this page. */+    val oldestTimestampMillis: Long = 0L,+    val generatedAtMillis: Long = 0L,+)++/** Watch request for one thread page ([WearCommunicateProtocol.REQUEST_THREAD_PATH]). */+@Serializable+data class WearThreadRequest(+    val threadKey: String,+    /** Page older than this timestamp; 0 means the latest page. */+    val beforeTimestampMillis: Long = 0L,+)++/** Small new-message alert ([WearCommunicateProtocol.NEW_MESSAGE_PATH]). */+@Serializable+data class WearNewMessageAlert(+    val threadKey: String = "",+    val displayName: String = "",+    val line: WearCommLine = WearCommLine.Sim,+    /** Capped snippet; always empty for disappearing threads. */+    val snippet: String = "",+    val timestampMillis: Long = 0L,+    val unreadCount: Int = 0,+    val contentExcluded: Boolean = false,+)++/**+ * Incoming-call alert ([WearCommunicateProtocol.INCOMING_CALL_PATH]).+ * Carries no answer capability on purpose: watch audio routing is not+ * guaranteed, so the only watch call action is decline (see [WearOpKind]).+ */+@Serializable+data class WearIncomingCall(+    val callKey: String = "",+    val displayName: String = "",+    val line: WearCommLine = WearCommLine.Sim,+    val isVideo: Boolean = false,+    val timestampMillis: Long = 0L,+)++/** Watch-originated actions the phone executes. Archive/mute are absent: the phone UI offers neither. */+@Serializable+enum class WearOpKind { QuickReply, MarkRead, MarkVoicemailRead, DeclineCall }++/** One watch-originated action ([WearCommunicateProtocol.OP_PATH]). */+@Serializable+data class WearCommOp(+    /** Watch-generated id; the phone echoes it in [WearOpResult]. */+    val opId: String,+    val kind: WearOpKind,+    val threadKey: String = "",+    val line: WearCommLine = WearCommLine.Sim,+    val threadId: Long = 0L,+    val remoteId: String? = null,+    val address: String = "",+    val subscriptionId: Int? = null,+    val participants: List<String> = emptyList(),+    /** Reply text for [WearOpKind.QuickReply]; empty otherwise. */+    val body: String = "",+    /** Voicemail/call key for [WearOpKind.MarkVoicemailRead] / [WearOpKind.DeclineCall]. */+    val targetKey: String = "",+)++/** Phone verdict for one op ([WearCommunicateProtocol.OP_RESULT_PATH]). */+@Serializable+data class WearOpResult(+    val opId: String = "",+    val kind: WearOpKind = WearOpKind.MarkRead,+    val success: Boolean = false,+)++/** What the watch last applied ([WearCommunicateProtocol.WATCH_STATE_PATH]). */+@Serializable+data class WearCommWatchState(+    val appliedGeneratedAtMillis: Long = 0L,+    val threadCount: Int = 0,+    val pendingOps: Int = 0,+)++/** Stable thread key: remote id when the line has one, else the phone thread id. */+fun wearThreadKey(line: WearCommLine, remoteId: String?, threadId: Long): String =+    "$line:${remoteId?.takeIf { it.isNotBlank() } ?: threadId}"++/** Content that may cross to the watch: nothing for disappearing/revoked, else capped. */+fun sanitizeWearText(text: String, disappearing: Boolean, cap: Int): String =+    if (disappearing) "" else text.take(cap)++/** Applies the disappearing/revoked exclusion and caps to one message. */+fun sanitizeWearMessage(message: WearMessage): WearMessage {+    if (message.disappearing) {+        return message.copy(body = "", mediaLabel = null, contentExcluded = true, bodyTruncated = false)+    }+    return message.copy(+        body = message.body.take(WearCommunicateProtocol.MAX_BODY_CHARS),+        bodyTruncated = message.bodyTruncated ||+            message.body.length > WearCommunicateProtocol.MAX_BODY_CHARS,+    )+}++/** Applies the exclusion and caps to one thread row (snippet is content). */+fun sanitizeWearThread(thread: WearThread): WearThread = thread.copy(+    displayName = thread.displayName.take(WearCommunicateProtocol.MAX_TITLE_CHARS),+    snippet = sanitizeWearText(+        thread.snippet,+        thread.disappearing,+        WearCommunicateProtocol.MAX_SNIPPET_CHARS,+    ),+    contentExcluded = thread.contentExcluded || thread.disappearing,+    participants = thread.participants.take(10),+)++/**+ * Builds the bounded snapshot: newest first per section, field caps and+ * exclusion applied, then count caps, then the byte cap enforced by+ * dropping the oldest voicemails, then calls, then threads (the+ * conversation list — the watch's home — survives longest).+ */+fun buildWearCommunicateSnapshot(+    threads: List<WearThread>,+    calls: List<WearCallEntry>,+    voicemails: List<WearVoicemail>,+    generatedAtMillis: Long,+): WearCommunicateSnapshot {+    var keptThreads = threads.map(::sanitizeWearThread)+        .sortedWith(compareByDescending<WearThread> { it.timestampMillis }.thenBy { it.key })+        .take(WearCommunicateProtocol.MAX_THREADS)+    var keptCalls = calls+        .sortedWith(compareByDescending<WearCallEntry> { it.timestampMillis }.thenBy { it.key })+        .take(WearCommunicateProtocol.MAX_CALLS)+    var keptVoicemails = voicemails.map {+        it.copy(transcript = it.transcript.take(WearCommunicateProtocol.MAX_TRANSCRIPT_CHARS))+    }.sortedWith(compareByDescending<WearVoicemail> { it.timestampMillis }.thenBy { it.key })+        .take(WearCommunicateProtocol.MAX_VOICEMAILS)+    var truncated = keptThreads.size < threads.size || keptCalls.size < calls.size ||+        keptVoicemails.size < voicemails.size+    fun snapshot() = WearCommunicateSnapshot(+        generatedAtMillis = generatedAtMillis,+        threads = keptThreads,+        calls = keptCalls,+        voicemails = keptVoicemails,+        voicemailUnreadCount = keptVoicemails.count { !it.isRead },+        truncated = truncated,+    )+    var result = snapshot()+    fun overBytes() =+        WearCommunicateProtocol.json.encodeToString(result).encodeToByteArray().size >+            WearCommunicateProtocol.MAX_JSON_BYTES+    while (overBytes() && keptVoicemails.isNotEmpty()) {+        keptVoicemails = keptVoicemails.dropLast(1); truncated = true; result = snapshot()+    }+    while (overBytes() && keptCalls.isNotEmpty()) {+        keptCalls = keptCalls.dropLast(1); truncated = true; result = snapshot()+    }+    while (overBytes() && keptThreads.isNotEmpty()) {+        keptThreads = keptThreads.dropLast(1); truncated = true; result = snapshot()+    }+    return result+}++/**+ * One page of a thread: the [pageSize] newest messages strictly older+ * than [beforeTimestampMillis] (0 = latest page), returned+ * oldest-to-newest. Exclusion/caps are applied before paging so an+ * excluded message still occupies its slot (its position is not a leak).+ */+fun buildWearThreadPage(+    threadKey: String,+    messages: List<WearMessage>,+    beforeTimestampMillis: Long = 0L,+    generatedAtMillis: Long = 0L,+    pageSize: Int = WearCommunicateProtocol.MAX_PAGE_MESSAGES,+): WearThreadPage {+    val clean = messages.map(::sanitizeWearMessage)+        .sortedWith(compareBy<WearMessage> { it.timestampMillis }.thenBy { it.messageKey })+    val eligible = if (beforeTimestampMillis <= 0L) clean+        else clean.filter { it.timestampMillis < beforeTimestampMillis }+    val page = eligible.takeLast(pageSize.coerceAtLeast(1))+    return WearThreadPage(+        threadKey = threadKey,+        messages = page,+        hasMore = eligible.size > page.size,+        oldestTimestampMillis = page.firstOrNull()?.timestampMillis ?: 0L,+        generatedAtMillis = generatedAtMillis,+    )+}++/**+ * Merges a newly arrived [page] into a cached thread view: dedupes by+ * messageKey, keeps chronological order, caps to the most recent+ * [WearCommunicateProtocol.MAX_CACHED_MESSAGES_PER_THREAD] plus any older+ * paged-in messages up to the same cap (oldest dropped first).+ */+fun mergeWearThreadPage(cached: List<WearMessage>, page: WearThreadPage): List<WearMessage> {+    val byKey = (cached + page.messages).associateBy { it.messageKey }+    return byKey.values+        .sortedWith(compareBy<WearMessage> { it.timestampMillis }.thenBy { it.messageKey })+        .takeLast(WearCommunicateProtocol.MAX_CACHED_MESSAGES_PER_THREAD)+}++/** Small alert for [thread] after a change; snippet withheld when excluded. */+fun buildWearNewMessageAlert(thread: WearThread, timestampMillis: Long): WearNewMessageAlert =+    WearNewMessageAlert(+        threadKey = thread.key,+        displayName = thread.displayName.take(WearCommunicateProtocol.MAX_TITLE_CHARS),+        line = thread.line,+        snippet = sanitizeWearText(+            thread.snippet,+            thread.disappearing,+            WearCommunicateProtocol.MAX_ALERT_SNIPPET_CHARS,+        ),+        timestampMillis = timestampMillis,+        unreadCount = thread.unreadCount,+        contentExcluded = thread.disappearing || thread.contentExcluded,+    )++/** A reply the phone may execute: non-blank after trim, capped. Null when invalid. */+fun validWearReply(op: WearCommOp): String? {+    if (op.kind != WearOpKind.QuickReply) return null+    val body = op.body.trim().take(WearCommunicateProtocol.MAX_REPLY_CHARS)+    return body.takeIf { it.isNotEmpty() && op.threadKey.isNotBlank() }+}++/** Pending ops after a phone [result]: a success drops its op; a failure keeps it for resend. */+fun pendingAfterResult(pending: List<WearCommOp>, result: WearOpResult): List<WearCommOp> =+    if (result.success) pending.filter { it.opId != result.opId } else pending
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/sync/WearLinkBridge.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/sync/WearLinkBridge.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..f20aee0bc7--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/sync/WearLinkBridge.kt@@ -0,0 +1,141 @@+package com.vayunmathur.communicate.wear.sync++import android.content.Context+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.domain.WearCommWatchState+import com.vayunmathur.communicate.wear.domain.WearCommunicateProtocol+import com.vayunmathur.communicate.wear.domain.WearCommunicateSnapshot+import com.vayunmathur.communicate.wear.domain.WearIncomingCall+import com.vayunmathur.communicate.wear.domain.WearNewMessageAlert+import com.vayunmathur.communicate.wear.domain.WearOpResult+import com.vayunmathur.communicate.wear.domain.WearThreadPage+import com.vayunmathur.communicate.wear.domain.WearThreadRequest+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Watch side of WearLink for Communicate: snapshot data items and thread+ * pages land in [WearCommunicateStore], alerts surface as store state,+ * pending ops and page/sync requests are messages. Delivery is bound to+ * this process being alive; pending ops resend on reconnect and leave+ * only on a phone success verdict.+ */+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 store = WearCommunicateStore.get(context)+        val listener = object : WearLinkListener {+            override fun onData(path: String, body: ByteArray) {+                if (path != WearCommunicateProtocol.SNAPSHOT_PATH) return+                val snapshot = runCatching {+                    WearCommunicateProtocol.json.decodeFromString<WearCommunicateSnapshot>(+                        body.decodeToString(),+                    )+                }.getOrNull()+                if (snapshot == null) {+                    Log.status(TAG, "ignoring malformed snapshot")+                    return+                }+                store.setSnapshot(snapshot)+            }++            override fun onMessage(path: String, body: ByteArray) {+                val text = body.decodeToString()+                when (path) {+                    WearCommunicateProtocol.THREAD_PAGE_PATH -> runCatching {+                        WearCommunicateProtocol.json.decodeFromString<WearThreadPage>(text)+                    }.getOrNull()?.let { store.setThreadPage(it) }+                    WearCommunicateProtocol.NEW_MESSAGE_PATH -> runCatching {+                        WearCommunicateProtocol.json.decodeFromString<WearNewMessageAlert>(text)+                    }.getOrNull()?.let { store.setAlert(it) }+                    WearCommunicateProtocol.INCOMING_CALL_PATH -> runCatching {+                        WearCommunicateProtocol.json.decodeFromString<WearIncomingCall>(text)+                    }.getOrNull()?.let { store.setIncomingCall(it) }+                    WearCommunicateProtocol.OP_RESULT_PATH -> runCatching {+                        WearCommunicateProtocol.json.decodeFromString<WearOpResult>(text)+                    }.getOrNull()?.let { store.applyOpResult(it) }+                }+            }+        }+        val created = WearLinkNode(context, WearCommunicateProtocol.CAPABILITY, listener)+        scope.launch {+            var wasConnected = false+            created.state.collect { linkState ->+                val connected = linkState is WearLinkState.Connected+                if (connected && !wasConnected) {+                    flushPending(context)+                    publishWatchState(context)+                }+                wasConnected = connected+            }+        }+        created.start()+        return created+    }++    /** Sends every pending op; ops stay queued until the phone verdict. */+    fun flushPending(context: Context) {+        val ops = WearCommunicateStore.get(context).pendingOps.value+        if (ops.isEmpty()) return+        scope.launch {+            val link = get(context)+            for (op in ops) {+                link.sendMessage(+                    WearCommunicateProtocol.OP_PATH,+                    WearCommunicateProtocol.json.encodeToString(op).encodeToByteArray(),+                    requireAck = true,+                )+            }+        }+    }++    fun publishWatchState(context: Context) {+        val store = WearCommunicateStore.get(context)+        val state = WearCommWatchState(+            appliedGeneratedAtMillis = store.appliedGeneratedAtMillis,+            threadCount = store.snapshot.value.threads.size,+            pendingOps = store.pendingOps.value.size,+        )+        scope.launch {+            get(context).putData(+                WearCommunicateProtocol.WATCH_STATE_PATH,+                WearCommunicateProtocol.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(WearCommunicateProtocol.REQUEST_SYNC_PATH, ByteArray(0))++    /** Ask the phone for one thread page (latest when [beforeTimestampMillis] is 0). */+    suspend fun requestThreadPage(+        context: Context,+        threadKey: String,+        beforeTimestampMillis: Long = 0L,+    ): Boolean = get(context).sendMessage(+        WearCommunicateProtocol.REQUEST_THREAD_PATH,+        WearCommunicateProtocol.json.encodeToString(+            WearThreadRequest(threadKey, beforeTimestampMillis),+        ).encodeToByteArray(),+    )+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearCallLogScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearCallLogScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearCallLogScreen.ktnew file mode 100644index 0000000000..27aa4cc641--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearCallLogScreen.kt@@ -0,0 +1,78 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore++/** Unified call log, read-only: calling back and dialling stay on the phone. */+@Composable+fun WearCallLogScreen(+    store: WearCommunicateStore,+    onBack: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()++    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.wear_calls),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (snapshot.calls.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(snapshot.calls, key = { it.key }) { call ->+                Chip(+                    onClick = {},+                    label = { Text(call.displayName.ifBlank { call.phoneNumber }, maxLines = 1) },+                    secondaryLabel = {+                        Text("${call.line} · ${call.type} · ${call.durationSeconds}s", maxLines = 1)+                    },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Text(+                stringResource(R.string.wear_call_on_phone),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearConversationListScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearConversationListScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearConversationListScreen.ktnew file mode 100644index 0000000000..34fa5bab13--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearConversationListScreen.kt@@ -0,0 +1,193 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/** Merged conversation list (all lines), most recent first, from the local snapshot (offline-safe). */+@Composable+fun WearConversationListScreen(+    store: WearCommunicateStore,+    onOpenThread: (String) -> Unit,+    onOpenCalls: () -> Unit,+    onOpenVoicemail: () -> Unit,+    onOpenPhoneOnly: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()+    val pending by store.pendingOps.collectAsState()+    val alert by store.lastAlert.collectAsState()+    val context = LocalContext.current+    val scope = rememberCoroutineScope()+    var syncNote by remember { mutableStateOf<String?>(null) }+    val requestedText = stringResource(R.string.wear_sync_requested)+    val noPhoneText = stringResource(R.string.wear_no_phone)++    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.app_name),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        alert?.let { newMessage ->+            item {+                Chip(+                    onClick = {+                        store.clearAlert()+                        onOpenThread(newMessage.threadKey)+                    },+                    label = {+                        Text(+                            "${stringResource(R.string.wear_new_message)}: ${newMessage.displayName}",+                            maxLines = 1,+                        )+                    },+                    secondaryLabel = {+                        if (newMessage.snippet.isNotBlank()) {+                            Text(newMessage.snippet, maxLines = 1)+                        }+                    },+                    colors = ChipDefaults.primaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        if (pending.isNotEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_pending, pending.size),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        syncNote?.let { note ->+            item {+                Text(+                    note,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        item {+            Chip(+                onClick = onOpenCalls,+                label = { Text(stringResource(R.string.wear_calls), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onOpenVoicemail,+                label = { Text(stringResource(R.string.wear_voicemail), maxLines = 1) },+                secondaryLabel = {+                    if (snapshot.voicemailUnreadCount > 0) {+                        Text(+                            stringResource(R.string.wear_unread, snapshot.voicemailUnreadCount),+                            maxLines = 1,+                        )+                    }+                },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        if (snapshot.threads.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(snapshot.threads, key = { it.key }) { thread ->+                Chip(+                    onClick = { onOpenThread(thread.key) },+                    label = {+                        Text(+                            thread.displayName.ifBlank { thread.address },+                            maxLines = 1,+                        )+                    },+                    secondaryLabel = {+                        val detail = when {+                            thread.contentExcluded ->+                                stringResource(R.string.wear_content_excluded)+                            thread.unreadCount > 0 -> "${thread.line} · " ++                                stringResource(R.string.wear_unread, thread.unreadCount) ++                                " · ${thread.snippet}"+                            else -> "${thread.line} · ${thread.snippet}"+                        }+                        Text(detail, maxLines = 1)+                    },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        if (snapshot.truncated) {+            item {+                Text(+                    stringResource(R.string.wear_truncated),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        item {+            Chip(+                onClick = onOpenPhoneOnly,+                label = { Text(stringResource(R.string.wear_phone_only), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    scope.launch {+                        syncNote = if (WearLinkBridge.requestSync(context)) {+                            requestedText+                        } else {+                            noPhoneText+                        }+                    }+                },+                label = { Text(stringResource(R.string.wear_request_sync), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearIncomingCallScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearIncomingCallScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearIncomingCallScreen.ktnew file mode 100644index 0000000000..272ad68520--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearIncomingCallScreen.kt@@ -0,0 +1,76 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.domain.WearIncomingCall++/**+ * Incoming-call alert. Decline only: answering on the watch is not offered+ * because watch audio routing is not guaranteed for these lines, so no+ * Answer control is shown at all.+ */+@Composable+fun WearIncomingCallScreen(+    store: WearCommunicateStore,+    call: WearIncomingCall,+    onDone: () -> Unit,+) {+    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.wear_incoming_call),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            Text(+                call.displayName.ifBlank { call.line.name },+                style = MaterialTheme.typography.body1,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Text(+                stringResource(R.string.wear_answer_on_phone),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    store.queueDeclineCall(call)+                    onDone()+                },+                label = { Text(stringResource(R.string.wear_decline), maxLines = 1) },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onDone,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearMainActivity.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearMainActivity.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..43495d839f--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearMainActivity.kt@@ -0,0 +1,78 @@+package com.vayunmathur.communicate.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.sync.WearLinkBridge++/**+ * Watch Communicate entry: mirrors the phone's pages (conversation list,+ * thread, call log, voicemail indicators) from the locally stored+ * snapshot/pages so it works standalone. Watch actions queue as ops the+ * phone executes; nothing here claims a phone write before its verdict.+ * An incoming-call alert overlays any route with Decline only — there is+ * no answer-on-watch because watch audio routing is not guaranteed.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val store = WearCommunicateStore.get(this)+        WearLinkBridge.get(this)+        WearLinkBridge.publishWatchState(this)+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.ConversationList) }+                val incoming by store.incomingCall.collectAsState()+                val call = incoming+                if (call != null) {+                    WearIncomingCallScreen(+                        store = store,+                        call = call,+                        onDone = { store.setIncomingCall(null) },+                    )+                } else {+                    when (val current = route) {+                        WearRoute.ConversationList -> WearConversationListScreen(+                            store = store,+                            onOpenThread = { route = WearRoute.Thread(it) },+                            onOpenCalls = { route = WearRoute.CallLog },+                            onOpenVoicemail = { route = WearRoute.Voicemail },+                            onOpenPhoneOnly = { route = WearRoute.PhoneOnly },+                        )+                        is WearRoute.Thread -> WearThreadScreen(+                            store = store,+                            threadKey = current.threadKey,+                            onReply = { route = WearRoute.Reply(it) },+                            onBack = { route = WearRoute.ConversationList },+                        )+                        is WearRoute.Reply -> WearReplyScreen(+                            store = store,+                            threadKey = current.threadKey,+                            onDone = { route = WearRoute.Thread(current.threadKey) },+                        )+                        WearRoute.CallLog -> WearCallLogScreen(+                            store = store,+                            onBack = { route = WearRoute.ConversationList },+                        )+                        WearRoute.Voicemail -> WearVoicemailScreen(+                            store = store,+                            onBack = { route = WearRoute.ConversationList },+                        )+                        WearRoute.PhoneOnly -> WearPhoneOnlyScreen(+                            onBack = { route = WearRoute.ConversationList },+                        )+                    }+                }+            }+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearPhoneOnlyScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearPhoneOnlyScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearPhoneOnlyScreen.ktnew file mode 100644index 0000000000..4a8c3c9439--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearPhoneOnlyScreen.kt@@ -0,0 +1,47 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R++/** What the watch deliberately does not mirror, and why, in one place. */+@Composable+fun WearPhoneOnlyScreen(onBack: () -> Unit) {+    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.wear_phone_only),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        item {+            Text(+                stringResource(R.string.wear_phone_only_body),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearReplyScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearReplyScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearReplyScreen.ktnew file mode 100644index 0000000000..b139c89d3a--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearReplyScreen.kt@@ -0,0 +1,90 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.SolidColor+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.domain.WearCommunicateProtocol++/**+ * Quick reply: canned replies plus a free-text field (the watch IME's+ * microphone is the dictation path). Sending queues a QuickReply op; the+ * phone executes it and its verdict clears the pending state.+ */+@Composable+fun WearReplyScreen(+    store: WearCommunicateStore,+    threadKey: String,+    onDone: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()+    val thread = snapshot.threads.firstOrNull { it.key == threadKey }+    var draft by remember(threadKey) { mutableStateOf("") }+    val textStyle = TextStyle(color = MaterialTheme.colors.onSurface)++    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.wear_reply_hint),+                style = MaterialTheme.typography.caption1,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            BasicTextField(+                value = draft,+                onValueChange = { draft = it },+                textStyle = textStyle,+                cursorBrush = SolidColor(MaterialTheme.colors.onSurface),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = {+                    if (thread != null && store.queueReply(thread, draft) != null) onDone()+                },+                label = { Text(stringResource(R.string.wear_send), maxLines = 1) },+                colors = ChipDefaults.primaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        items(WearCommunicateProtocol.CANNED_REPLIES) { canned ->+            Chip(+                onClick = {+                    if (thread != null && store.queueReply(thread, canned) != null) onDone()+                },+                label = { Text(canned, maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+        item {+            Chip(+                onClick = onDone,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearRoute.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearRoute.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..3ab888bf5b--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearRoute.kt@@ -0,0 +1,22 @@+package com.vayunmathur.communicate.wear.ui++/** Watch navigation destinations: detail routes carry the thread key, never selection state. */+sealed interface WearRoute {+    /** Merged conversation list (phone Messages). */+    data object ConversationList : WearRoute++    /** One thread (phone Conversation), identified by its stable watch key. */+    data class Thread(val threadKey: String) : WearRoute++    /** Quick reply for one thread (canned + dictated/free text). */+    data class Reply(val threadKey: String) : WearRoute++    /** Unified call log (phone CallLogs). */+    data object CallLog : WearRoute++    /** Voicemail indicators (phone voicemail list). */+    data object Voicemail : WearRoute++    /** Features that stay on the phone, with the reason stated. */+    data object PhoneOnly : WearRoute+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearThreadScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearThreadScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearThreadScreen.ktnew file mode 100644index 0000000000..c0439898ae--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearThreadScreen.kt@@ -0,0 +1,157 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore+import com.vayunmathur.communicate.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * One thread from its cached pages (offline-safe). Opening it asks the+ * phone for the latest page and queues mark-read; "Load older" pages+ * backwards with the cache's cursor. Excluded (disappearing) content is+ * labelled, never shown.+ */+@Composable+fun WearThreadScreen(+    store: WearCommunicateStore,+    threadKey: String,+    onReply: (String) -> Unit,+    onBack: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()+    val pages by store.pages.collectAsState()+    val thread = snapshot.threads.firstOrNull { it.key == threadKey }+    val cache = pages[threadKey]+    val context = LocalContext.current+    val scope = rememberCoroutineScope()++    LaunchedEffect(threadKey) {+        WearLinkBridge.requestThreadPage(context, threadKey)+    }++    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                thread?.displayName?.ifBlank { thread.address }.orEmpty()+                    .ifBlank { stringResource(R.string.app_name) },+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (thread == null) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            if (thread.contentExcluded) {+                item {+                    Text(+                        stringResource(R.string.wear_content_excluded),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            if (cache?.hasMore == true) {+                item {+                    Chip(+                        onClick = {+                            scope.launch {+                                WearLinkBridge.requestThreadPage(+                                    context, threadKey, cache.oldestTimestampMillis,+                                )+                            }+                        },+                        label = { Text(stringResource(R.string.wear_load_older), maxLines = 1) },+                        colors = ChipDefaults.secondaryChipColors(),+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                    )+                }+            }+            if (cache == null || cache.messages.isEmpty()) {+                item {+                    Text(+                        stringResource(R.string.wear_no_phone),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                    )+                }+            } else {+                items(cache.messages, key = { it.messageKey }) { message ->+                    val text = when {+                        message.contentExcluded ->+                            stringResource(R.string.wear_content_excluded)+                        message.mediaLabel != null && message.body.isBlank() ->+                            "${message.mediaLabel} · ${stringResource(R.string.wear_media_on_phone)}"+                        message.body.isBlank() -> "·"+                        else -> message.body ++                            if (message.bodyTruncated) {+                                " ${stringResource(R.string.wear_body_truncated)}"+                            } else {+                                ""+                            }+                    }+                    Text(+                        (if (message.outgoing) "You: " else "") + text,+                        style = MaterialTheme.typography.body2,+                        modifier = Modifier.fillMaxWidth()+                            .padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            item {+                Chip(+                    onClick = { onReply(thread.key) },+                    label = { Text(stringResource(R.string.wear_reply), maxLines = 1) },+                    colors = ChipDefaults.primaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+            if (thread.unreadCount > 0) {+                item {+                    Chip(+                        onClick = { store.queueMarkRead(thread) },+                        label = { Text(stringResource(R.string.wear_mark_read), maxLines = 1) },+                        colors = ChipDefaults.secondaryChipColors(),+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                    )+                }+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearVoicemailScreen.kt
diff --git a/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearVoicemailScreen.kt b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearVoicemailScreen.ktnew file mode 100644index 0000000000..562c871937--- /dev/null+++ b/communicate-wear/src/main/java/com/vayunmathur/communicate/wear/ui/WearVoicemailScreen.kt@@ -0,0 +1,91 @@+package com.vayunmathur.communicate.wear.ui++import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.wear.compose.foundation.lazy.ScalingLazyColumn+import androidx.wear.compose.foundation.lazy.items+import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.MaterialTheme+import androidx.wear.compose.material.Text+import com.vayunmathur.communicate.wear.R+import com.vayunmathur.communicate.wear.data.WearCommunicateStore++/**+ * Voicemail indicators only: caller, duration, read state and a capped+ * transcript when the phone has one. No audio crosses, so there is no+ * playback here; mark-read is executed on the phone.+ */+@Composable+fun WearVoicemailScreen(+    store: WearCommunicateStore,+    onBack: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()++    ScalingLazyColumn(state = rememberScalingLazyListState()) {+        item {+            Text(+                stringResource(R.string.wear_voicemail),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        if (snapshot.voicemails.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            items(snapshot.voicemails, key = { it.key }) { voicemail ->+                Chip(+                    onClick = {+                        if (!voicemail.isRead) store.queueMarkVoicemailRead(voicemail)+                    },+                    label = { Text(voicemail.phoneNumber, maxLines = 1) },+                    secondaryLabel = {+                        val state = if (voicemail.isRead) "" else " · unread"+                        val text = "${voicemail.line} · ${voicemail.durationSeconds}s$state" ++                            if (voicemail.transcript.isNotBlank()) {+                                " · ${voicemail.transcript}"+                            } else {+                                ""+                            }+                        Text(text, maxLines = 1)+                    },+                    colors = ChipDefaults.secondaryChipColors(),+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+                )+            }+        }+        item {+            Text(+                stringResource(R.string.wear_listen_on_phone),+                style = MaterialTheme.typography.body2,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+            )+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
communicate-wear/src/main/res/values/colors.xml
diff --git a/communicate-wear/src/main/res/values/colors.xml b/communicate-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..bfc7025d71--- /dev/null+++ b/communicate-wear/src/main/res/values/colors.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Background for the generated adaptive launcher icon (see LauncherIconGen). -->+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
communicate-wear/src/main/res/values/strings.xml
diff --git a/communicate-wear/src/main/res/values/strings.xml b/communicate-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..69c554288c--- /dev/null+++ b/communicate-wear/src/main/res/values/strings.xml@@ -0,0 +1,30 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Communicate</string>+    <string name="wear_empty">No conversations synced yet. Open Communicate on your phone to sync this watch.</string>+    <string name="wear_calls">Calls</string>+    <string name="wear_voicemail">Voicemail</string>+    <string name="wear_request_sync">Sync now</string>+    <string name="wear_sync_requested">Asked your phone for a fresh copy</string>+    <string name="wear_no_phone">Phone not reachable — showing the last synced copy</string>+    <string name="wear_pending">Waiting for your phone to confirm %1$d action(s)</string>+    <string name="wear_truncated">Showing the most recent items; the rest stays on your phone</string>+    <string name="wear_back">Back</string>+    <string name="wear_reply">Reply</string>+    <string name="wear_mark_read">Mark read</string>+    <string name="wear_load_older">Load older messages</string>+    <string name="wear_content_excluded">Content not shown here — disappearing messages stay on your phone</string>+    <string name="wear_body_truncated">… (full text on your phone)</string>+    <string name="wear_media_on_phone">View on your phone</string>+    <string name="wear_reply_hint">Reply (tap the mic to dictate)</string>+    <string name="wear_send">Send</string>+    <string name="wear_unread">%1$d unread</string>+    <string name="wear_listen_on_phone">Listen on your phone</string>+    <string name="wear_call_on_phone">Call back from your phone</string>+    <string name="wear_incoming_call">Incoming call</string>+    <string name="wear_decline">Decline</string>+    <string name="wear_answer_on_phone">Answer on your phone — answering here is not offered</string>+    <string name="wear_new_message">New message</string>+    <string name="wear_phone_only">Phone-only features</string>+    <string name="wear_phone_only_body">Dialler, accounts and sign-in, calling setup, voicemail playback, photos and videos, and full settings stay on your phone.</string>+</resources>
communicate-wear/src/test/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocolTest.kt
diff --git a/communicate-wear/src/test/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocolTest.kt b/communicate-wear/src/test/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocolTest.ktnew file mode 100644index 0000000000..600ad352e0--- /dev/null+++ b/communicate-wear/src/test/java/com/vayunmathur/communicate/wear/domain/WearCommunicateProtocolTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.communicate.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearCommunicateProtocolTest {++    private fun thread(+        key: String = "WhatsApp:abc",+        snippet: String = "Hi there",+        timestamp: Long = 900L,+        disappearing: Boolean = false,+    ) = WearThread(+        key = key, threadId = 7L, line = WearCommLine.WhatsApp, address = "+1555",+        displayName = "Alice", snippet = snippet, timestampMillis = timestamp,+        unreadCount = 2, disappearing = disappearing,+    )++    private fun message(id: String, ts: Long, body: String = "msg $id", disappearing: Boolean = false) =+        WearMessage(+            messageKey = id, threadKey = "WhatsApp:abc", body = body,+            timestampMillis = ts, disappearing = disappearing,+        )++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearCommunicateSnapshot(+            generatedAtMillis = 1_000L,+            threads = listOf(thread()),+        )+        assertEquals(+            """{"generatedAtMillis":1000,"threads":[{"key":"WhatsApp:abc","threadId":7,""" ++                """"line":"WhatsApp","address":"+1555","displayName":"Alice","snippet":"Hi there",""" ++                """"timestampMillis":900,"unreadCount":2}]}""",+            WearCommunicateProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun goldenOpJson() {+        val op = WearCommOp(+            opId = "op1", kind = WearOpKind.QuickReply, threadKey = "WhatsApp:abc",+            line = WearCommLine.WhatsApp, body = "OK",+        )+        assertEquals(+            """{"opId":"op1","kind":"QuickReply","threadKey":"WhatsApp:abc","line":"WhatsApp","body":"OK"}""",+            WearCommunicateProtocol.json.encodeToString(op),+        )+    }++    @Test+    fun snapshotRoundTrip() {+        val snapshot = buildWearCommunicateSnapshot(+            threads = listOf(thread()),+            calls = listOf(+                WearCallEntry(key = "Sim:1", phoneNumber = "+1555", type = "Missed", timestampMillis = 5L),+            ),+            voicemails = listOf(+                WearVoicemail(key = "Sim:2", phoneNumber = "+1555", timestampMillis = 4L, isRead = false),+            ),+            generatedAtMillis = 10L,+        )+        assertEquals(+            snapshot,+            WearCommunicateProtocol.json.decodeFromString<WearCommunicateSnapshot>(+                WearCommunicateProtocol.json.encodeToString(snapshot),+            ),+        )+        assertEquals(1, snapshot.voicemailUnreadCount)+    }++    @Test+    fun buildCapsCountsFieldsAndBytes() {+        val threads = (1..(WearCommunicateProtocol.MAX_THREADS + 20)).map {+            thread(key = "Sim:$it", snippet = "s".repeat(500), timestamp = it.toLong())+        }+        val snapshot = buildWearCommunicateSnapshot(threads, emptyList(), emptyList(), 0L)+        assertTrue(snapshot.notesSize() <= WearCommunicateProtocol.MAX_THREADS)+        assertTrue(snapshot.truncated)+        assertTrue(snapshot.threads.all {+            it.snippet.length == WearCommunicateProtocol.MAX_SNIPPET_CHARS+        })+        val bytes = WearCommunicateProtocol.json.encodeToString(snapshot).encodeToByteArray().size+        assertTrue(bytes <= WearCommunicateProtocol.MAX_JSON_BYTES, "snapshot $bytes over cap")+        assertEquals("Sim:${WearCommunicateProtocol.MAX_THREADS + 20}", snapshot.threads.first().key)+    }++    private fun WearCommunicateSnapshot.notesSize() = threads.size++    @Test+    fun disappearingThreadExcludesSnippetEverywhere() {+        val snapshot = buildWearCommunicateSnapshot(+            threads = listOf(thread(snippet = "secret text", disappearing = true)),+            calls = emptyList(), voicemails = emptyList(), generatedAtMillis = 0L,+        )+        assertEquals("", snapshot.threads.single().snippet)+        assertTrue(snapshot.threads.single().contentExcluded)+        val alert = buildWearNewMessageAlert(snapshot.threads.single(), 1_000L)+        assertEquals("", alert.snippet)+        assertTrue(alert.contentExcluded)+        val encoded = WearCommunicateProtocol.json.encodeToString(snapshot)+        assertFalse(encoded.contains("secret text"), "disappearing snippet leaked: $encoded")+    }++    @Test+    fun disappearingMessageExcludesBodyAndMedia() {+        val page = buildWearThreadPage(+            threadKey = "WhatsApp:abc",+            messages = listOf(+                message("m1", 100L, body = "secret body", disappearing = true)+                    .copy(mediaLabel = "Photo"),+            ),+        )+        val only = page.messages.single()+        assertEquals("", only.body)+        assertEquals(null, only.mediaLabel)+        assertTrue(only.contentExcluded)+        assertFalse(WearCommunicateProtocol.json.encodeToString(page).contains("secret body"))+    }++    @Test+    fun pagingLatestThenOlderWithCursor() {+        val messages = (1..45).map { message("m$it", it * 10L) }+        val latest = buildWearThreadPage("WhatsApp:abc", messages)+        assertEquals(WearCommunicateProtocol.MAX_PAGE_MESSAGES, latest.messages.size)+        assertEquals("m26", latest.messages.first().messageKey)+        assertEquals("m45", latest.messages.last().messageKey)+        assertTrue(latest.hasMore)+        val older = buildWearThreadPage(+            "WhatsApp:abc", messages,+            beforeTimestampMillis = latest.oldestTimestampMillis,+        )+        assertEquals("m6", older.messages.first().messageKey)+        assertEquals("m25", older.messages.last().messageKey)+        assertTrue(older.hasMore)+        val oldest = buildWearThreadPage(+            "WhatsApp:abc", messages,+            beforeTimestampMillis = older.oldestTimestampMillis,+        )+        assertEquals(5, oldest.messages.size)+        assertFalse(oldest.hasMore)+    }++    @Test+    fun mergeDedupesAndCaps() {+        val first = buildWearThreadPage(+            "WhatsApp:abc", (1..20).map { message("m$it", it.toLong()) },+        )+        val merged = mergeWearThreadPage(first.messages, first)+        assertEquals(20, merged.size)+        val big = mergeWearThreadPage(+            merged, buildWearThreadPage("WhatsApp:abc", (21..200).map { message("m$it", it.toLong()) }),+        )+        assertTrue(big.size <= WearCommunicateProtocol.MAX_CACHED_MESSAGES_PER_THREAD)+        assertEquals("m200", big.last().messageKey)+    }++    @Test+    fun replyValidationAndResultHandling() {+        val good = WearCommOp(+            opId = "a", kind = WearOpKind.QuickReply, threadKey = "Sim:1", body = "  On my way  ",+        )+        assertEquals("On my way", validWearReply(good))+        assertEquals(null, validWearReply(good.copy(body = "   ")))+        assertEquals(null, validWearReply(good.copy(kind = WearOpKind.MarkRead)))+        val pending = listOf(good, good.copy(opId = "b"))+        assertEquals(+            listOf(pending[1]),+            pendingAfterResult(pending, WearOpResult("a", WearOpKind.QuickReply, success = true)),+        )+        assertEquals(+            pending,+            pendingAfterResult(pending, WearOpResult("a", WearOpKind.QuickReply, success = false)),+        )+    }++    @Test+    fun threadKeyPrefersRemoteId() {+        assertEquals("Signal:conv1", wearThreadKey(WearCommLine.Signal, "conv1", 42L))+        assertEquals("Sim:42", wearThreadKey(WearCommLine.Sim, null, 42L))+        assertEquals("Sim:42", wearThreadKey(WearCommLine.Sim, "", 42L))+    }+}
communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.ktindex 4d9fdb8499..7357415c07 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -21,9 +21,11 @@ class MainActivity : MaActivity() {      override fun onCreateBeforeContent() {         pendingDeepLink = DeepLinks.parse(intent)-        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)         // Wear companion sync lives and dies with this process (WearLink has         // no system wakeup); the watch reads its cached snapshot offline.+        // No permission request here: launch must not ask for any permission+        // at startup, so WearLink simply reports PermissionMissing until+        // BLUETOOTH_CONNECT is granted through system settings.         com.vayunmathur.communicate.data.WearCommunicateSync.get(this).start()     } 
music-wear/AGENTS.md
diff --git a/music-wear/AGENTS.md b/music-wear/AGENTS.mdnew file mode 100644index 0000000000..3df5b2a4b7--- /dev/null+++ b/music-wear/AGENTS.md@@ -0,0 +1,42 @@+# AGENTS.md — music-wear/ (':music:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `music-wear/` + `music/` (the phone side of the same feature).++- Gradle: :music:wear / dir: music-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, sync+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Music (`:music`). This module deliberately+uses `applicationId = "com.vayunmathur.music"` (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+`domain/WearMusicProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearMusicProtocolTest` pins the same golden JSON.++- Page snapshots: WearLink data item (`/music/page`, phone -> watch),+  requested by message (`/music/page-request`, watch -> phone)+- Now-playing: WearLink data item (`/music/playback`, phone -> watch)+- Watch state: WearLink data item (`/music/watch-state`, watch -> phone)+- Playback/library ops: WearLink message (`/music/op`, watch -> phone)+- Search: WearLink message (`/music/search-request`, watch -> phone)+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Execution model (stated, not implied)+The phone owns the catalog and is the ONLY audio player. The watch stores+no music files and no whole catalog: it caches only visited page snapshots+and the latest playback state, and renders them offline. Every playback+action is an op executed by the phone's playback service; the watch UI+reflects the phone-reported state and never claims an unconfirmed result.++## Verify (this module only)+```+./gradlew :music:wear:assembleDev+./gradlew :music:wear:testDebugUnitTest+```
music-wear/build.gradle.kts
diff --git a/music-wear/build.gradle.kts b/music-wear/build.gradle.ktsnew file mode 100644index 0000000000..1e06c2f6a5--- /dev/null+++ b/music-wear/build.gradle.kts@@ -0,0 +1,31 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "music_note"+}++// Version shared with the phone app (root version.txt).+val wearVersionLines = file("../version.txt").readLines()+val wearVersionCode = wearVersionLines[0].trim().toInt()+val wearVersionName = wearVersionLines[1].trim()++android {+    // WearLink handshake requires same package + signing as the phone app.+    namespace = "com.vayunmathur.music.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.music"+        minSdk = 31+        versionCode = wearVersionCode+        versionName = wearVersionName+    }+}++dependencies {+    implementation(libs.kotlinx.coroutines.android)+    implementation(libs.kotlinx.serialization.json)+    implementation(project(":library:wearlink"))+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
music-wear/src/main/AndroidManifest.xml
diff --git a/music-wear/src/main/AndroidManifest.xml b/music-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..611334d9b3--- /dev/null+++ b/music-wear/src/main/AndroidManifest.xml@@ -0,0 +1,21 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">+    <uses-feature android:name="android.hardware.type.watch" android:required="true" />+    <uses-feature android:name="android.hardware.touchscreen" android:required="false" />+    <uses-permission android:name="android.permission.WAKE_LOCK" />+    <application+        android:allowBackup="false"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@android:style/Theme.Material.NoActionBar">+        <meta-data android:name="com.google.android.wearable.standalone" android:value="false" />+        <activity android:name=".ui.WearMainActivity" android:exported="true" android:taskAffinity="">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>+</manifest>
music-wear/src/main/java/com/vayunmathur/music/wear/data/WearMusicStore.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/data/WearMusicStore.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/data/WearMusicStore.ktnew file mode 100644index 0000000000..0feb9bfaae--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/data/WearMusicStore.kt@@ -0,0 +1,122 @@+package com.vayunmathur.music.wear.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.music.wear.domain.WearMusicOp+import com.vayunmathur.music.wear.domain.WearMusicProtocol+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageSnapshot+import com.vayunmathur.music.wear.domain.WearPlaybackState+import com.vayunmathur.music.wear.domain.WearWatchState+import com.vayunmathur.music.wear.sync.WearLinkBridge+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: visited page snapshots + latest playback state,+ * persisted as JSON in app-private storage so the UI renders offline+ * (phone absent, process cold-started) from pages already visited. The+ * whole catalog is never stored — only pages the user opened.+ */+class WearMusicStore private constructor(private val context: Context) {++    companion object {+        private const val TAG = "WearMusicStore"++        @Volatile+        private var instance: WearMusicStore? = null++        /** The process-wide store (bridge and UI must agree on one). */+        fun get(context: Context): WearMusicStore = instance ?: synchronized(this) {+            instance ?: WearMusicStore(context.applicationContext).also { instance = it }+        }+    }++    private val pagesFile = File(context.filesDir, "wear-music-pages.json")+    private val playbackFile = File(context.filesDir, "wear-music-playback.json")+    private val opsFile = File(context.filesDir, "wear-music-pending-ops.json")++    private val _pages = MutableStateFlow(loadPages())++    /** Visited pages keyed by [WearPageId]; first-page snapshots replace, later pages append-merge. */+    val pages: StateFlow<Map<WearPageId, WearPageSnapshot>> = _pages.asStateFlow()++    private val _playback = MutableStateFlow(loadPlayback())++    /** Latest phone-reported playback state; the watch renders, never owns, playback. */+    val playback: StateFlow<WearPlaybackState> = _playback.asStateFlow()++    private val _pendingOps = MutableStateFlow(loadOps())++    /** Ops sent (or queued offline); cleared only when phone state reflects them. */+    val pendingOps: StateFlow<List<WearMusicOp>> = _pendingOps.asStateFlow()++    /** Merge one page snapshot: a fresh first page replaces its page; a cursor page extends it. */+    fun setPage(snapshot: WearPageSnapshot) {+        val current = _pages.value.toMutableMap()+        val existing = current[snapshot.page]+        current[snapshot.page] = if (existing == null || snapshot.page == existing.page && snapshot.nextCursor.isNotEmpty() && existing.nextCursor.isEmpty()) {+            snapshot+        } else if (existing != null && snapshot.generation >= existing.generation) {+            existing.copy(+                tracks = existing.tracks + snapshot.tracks,+                albums = existing.albums + snapshot.albums,+                artists = existing.artists + snapshot.artists,+                playlists = existing.playlists + snapshot.playlists,+                nextCursor = snapshot.nextCursor,+                generation = snapshot.generation,+            )+        } else {+            snapshot+        }+        _pages.value = current+        persist(pagesFile, WearMusicProtocol.json.encodeToString(current.values.toList()))+        publishWatchState()+    }++    /** Replace playback state (phone data item) and drop ops it reflects (any state newer than queue time). */+    fun setPlayback(state: WearPlaybackState) {+        _playback.value = state+        persist(playbackFile, WearMusicProtocol.json.encodeToString(state))+    }++    /** Queue an op for the phone; persisted so an offline tap is not lost, resent on reconnect. */+    fun enqueueOp(op: WearMusicOp) {+        _pendingOps.value = _pendingOps.value + op+        persist(opsFile, WearMusicProtocol.json.encodeToString(_pendingOps.value))+        WearLinkBridge.sendOp(context, op)+        publishWatchState()+    }++    /** Publish what this watch holds, so the phone can show last-sync truth. */+    fun publishWatchState() {+        WearLinkBridge.publishWatchState(+            context,+            WearWatchState(+                appliedGeneration = _pages.value.values.maxOfOrNull { it.generation } ?: 0L,+                cachedPages = _pages.value.size,+                pendingOps = _pendingOps.value.size,+            ),+        )+    }++    private fun persist(file: File, text: String) {+        runCatching { file.writeText(text) }.onFailure { Log.status(TAG, "persist failed: ${it.message}") }+    }++    private fun loadPages(): Map<WearPageId, WearPageSnapshot> = runCatching {+        WearMusicProtocol.json.decodeFromString<List<WearPageSnapshot>>(pagesFile.readText())+            .associateBy { it.page }+    }.getOrDefault(emptyMap())++    private fun loadPlayback(): WearPlaybackState = runCatching {+        WearMusicProtocol.json.decodeFromString<WearPlaybackState>(playbackFile.readText())+    }.getOrDefault(WearPlaybackState())++    private fun loadOps(): List<WearMusicOp> = runCatching {+        WearMusicProtocol.json.decodeFromString<List<WearMusicOp>>(opsFile.readText())+    }.getOrDefault(emptyList())+}
music-wear/src/main/java/com/vayunmathur/music/wear/domain/WearMusicProtocol.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/domain/WearMusicProtocol.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/domain/WearMusicProtocol.ktnew file mode 100644index 0000000000..ea786237fa--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/domain/WearMusicProtocol.kt@@ -0,0 +1,198 @@+package com.vayunmathur.music.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Wear OS Music companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:music:wear`,+ * applicationId `com.vayunmathur.music`) carries a copy under+ * `com.vayunmathur.music.wear.domain`. Change both copies together; each+ * side's `WearMusicProtocolTest` pins the same golden JSON.+ *+ * Design (owner direction): the phone owns the catalog and ALL audio+ * playback. The watch never stores music files and never warehouses the+ * whole catalog. Instead the phone serves bounded page snapshots keyed by+ * [WearPageKey] with cursor pagination; the watch caches visited pages for+ * offline browsing. Now-playing is a small [WearPlaybackState] streamed as+ * a data item. Every playback action is a [WearMusicOp] sent to the phone,+ * which executes it in its playback service; the watch UI only reflects the+ * resulting [WearPlaybackState]. No audio plays on the watch itself.+ */+object WearMusicProtocol {+    /** WearLink appId the phone requires in the peer handshake. */+    const val CAPABILITY = "music_wear_companion"++    /** Data-item path (phone -> watch): one [WearPageSnapshot] JSON. */+    const val PAGE_PATH = "/music/page"++    /** Data-item path (phone -> watch): the [WearPlaybackState] JSON. */+    const val PLAYBACK_PATH = "/music/playback"++    /** Data-item path (watch -> phone): the [WearWatchState] JSON. */+    const val WATCH_STATE_PATH = "/music/watch-state"++    /** Message path (watch -> phone): one [WearPageRequest] JSON. */+    const val PAGE_REQUEST_PATH = "/music/page-request"++    /** Message path (watch -> phone): one [WearMusicOp] JSON. */+    const val OP_PATH = "/music/op"++    /** Message path (watch -> phone): one [WearSearchRequest] JSON. */+    const val SEARCH_REQUEST_PATH = "/music/search-request"++    /** Tracks/artists/albums per page; keeps one frame small on the watch. */+    const val PAGE_SIZE = 30++    /** Largest page/playback JSON in UTF-8 bytes. */+    const val MAX_JSON_BYTES = 45_000++    /** Largest playback queue page carried in state (full queue stays on phone). */+    const val MAX_QUEUE_ITEMS = 50++    /** Field caps. */+    const val MAX_TITLE_CHARS = 120+    const val MAX_NAME_CHARS = 120++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** Every phone page/route, mirrored 1:1 as a watch page key. */+@Serializable+enum class WearPageKey {+    HOME, ALBUMS, ARTISTS, PLAYLISTS, TRACKS,+    ALBUM_DETAIL, ARTIST_DETAIL, PLAYLIST_DETAIL,+    SEARCH, QUEUE, NOW_PLAYING, SETTINGS,+}++/** Identifies one bounded page: route + entity id + search query. */+@Serializable+data class WearPageId(+    val key: WearPageKey,+    val entityId: Long = 0L,+    val query: String = "",+)++/** Id-carrying page request (watch -> phone). [cursor] is the opaque next-page cursor, "" = first page. */+@Serializable+data class WearPageRequest(val page: WearPageId, val cursor: String = "")++/** Search request (watch -> phone): dictation/typed text lives in [WearPageRequest.page.query]. */+@Serializable+data class WearSearchRequest(val query: String, val cursor: String = "")++/** One track row, trimmed to watch size. IDs are phone library IDs. */+@Serializable+data class WearTrack(+    val id: Long,+    val title: String,+    val artist: String = "",+    val album: String = "",+    val durationMs: Long = 0L,+    val isPlaying: Boolean = false,+)++/** One album row. */+@Serializable+data class WearAlbum(val id: Long, val name: String, val artistName: String = "", val trackCount: Int = 0)++/** One artist row. */+@Serializable+data class WearArtist(val id: Long, val name: String, val albumCount: Int = 0)++/** One playlist row. */+@Serializable+data class WearPlaylist(val id: Long, val name: String, val trackCount: Int = 0)++/** One bounded page snapshot (phone -> watch). [nextCursor] empty = last page. */+@Serializable+data class WearPageSnapshot(+    val page: WearPageId,+    val generation: Long = 0L,+    val tracks: List<WearTrack> = emptyList(),+    val albums: List<WearAlbum> = emptyList(),+    val artists: List<WearArtist> = emptyList(),+    val playlists: List<WearPlaylist> = emptyList(),+    val nextCursor: String = "",+    val totalCount: Int = 0,+    val truncated: Boolean = false,+)++/** Now-playing state streamed phone -> watch; the phone service is the only player. */+@Serializable+data class WearPlaybackState(+    val trackId: Long? = null,+    val title: String = "",+    val artist: String = "",+    val album: String = "",+    val isPlaying: Boolean = false,+    val positionMs: Long = 0L,+    val durationMs: Long = 0L,+    val shuffle: Boolean = false,+    /** Mirrors media3 Player repeat constants: 0=off, 1=one, 2=all. */+    val repeatMode: Int = 0,+    val queue: List<WearTrack> = emptyList(),+    val queueIndex: Int = -1,+    val sourceName: String = "",+    val lyricsSnippet: String = "",+)++/** What the watch last applied, published at [WearMusicProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+    val appliedGeneration: Long = 0L,+    val cachedPages: Int = 0,+    val pendingOps: Int = 0,+)++/** Kinds of watch-originated ops; all execute on the phone only. */+@Serializable+enum class WearOpKind {+    PLAY_TRACKS, PLAY_SHUFFLED, TOGGLE_PLAY_PAUSE, SEEK, SKIP_NEXT, SKIP_PREVIOUS,+    TOGGLE_SHUFFLE, CYCLE_REPEAT, PLAY_ALBUM, PLAY_ARTIST, PLAY_PLAYLIST,+    ADD_TO_QUEUE, ADD_TO_PLAYLIST, CREATE_PLAYLIST,+}++/**+ * One watch-originated op ([WearMusicProtocol.OP_PATH]). The phone executes+ * it against its playback service / library; the watch never claims success+ * until the next [WearPlaybackState]/page reflects it.+ */+@Serializable+data class WearMusicOp(+    val kind: WearOpKind,+    val trackIds: List<Long> = emptyList(),+    val startIndex: Int = 0,+    val entityId: Long = 0L,+    val positionMs: Long = 0L,+    val text: String = "",+    val sourceName: String = "",+)++/** Pure playback state machine: applies an op's *result* (as reported by the phone) to prior state. */+fun reducePlayback(state: WearPlaybackState, op: WearMusicOp, reported: WearPlaybackState): WearPlaybackState = reported++/** Next repeat mode in the phone's cycle: off -> all -> one -> off. */+fun nextWearRepeatMode(mode: Int): Int = when (mode) { 0 -> 2; 2 -> 1; else -> 0 }++/**+ * Builds one bounded page from a full ordered list using an offset cursor.+ * Cursor is the decimal offset of the next item; malformed/overflow cursors+ * restart at the first page rather than crashing the watch.+ */+fun <T> paginateWearPage(items: List<T>, cursor: String, pageSize: Int = WearMusicProtocol.PAGE_SIZE): Pair<List<T>, String> {+    val offset = cursor.toIntOrNull()?.coerceIn(0, items.size) ?: 0+    val slice = items.drop(offset).take(pageSize)+    val next = if (offset + slice.size < items.size) (offset + slice.size).toString() else ""+    return slice to next+}++/** Caps one track's fields to watch size. */+fun capWearTrack(track: WearTrack): WearTrack = track.copy(+    title = track.title.take(WearMusicProtocol.MAX_TITLE_CHARS),+    artist = track.artist.take(WearMusicProtocol.MAX_NAME_CHARS),+    album = track.album.take(WearMusicProtocol.MAX_NAME_CHARS),+)
music-wear/src/main/java/com/vayunmathur/music/wear/sync/WearLinkBridge.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/sync/WearLinkBridge.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..0b95ace036--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/sync/WearLinkBridge.kt@@ -0,0 +1,114 @@+package com.vayunmathur.music.wear.sync++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearMusicOp+import com.vayunmathur.music.wear.domain.WearMusicProtocol+import com.vayunmathur.music.wear.domain.WearPageRequest+import com.vayunmathur.music.wear.domain.WearPageSnapshot+import com.vayunmathur.music.wear.domain.WearPlaybackState+import com.vayunmathur.music.wear.domain.WearSearchRequest+import com.vayunmathur.music.wear.domain.WearWatchState+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 Music: page snapshots + playback state land in+ * [WearMusicStore]; page/search requests and playback ops are messages to+ * the phone. Delivery is bound to this process being alive; pending ops are+ * resent whenever a session connects.+ */+object WearLinkBridge {+    private const val TAG = "WearMusicBridge"+    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++    @Volatile+    private var node: WearLinkNode? = null++    /** The process-wide WearLink node for the music companion, 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) {+                val text = body.decodeToString()+                when (path) {+                    WearMusicProtocol.PAGE_PATH -> runCatching {+                        WearMusicProtocol.json.decodeFromString<WearPageSnapshot>(text)+                    }.onSuccess { WearMusicStore.get(context).setPage(it) }+                        .onFailure { Log.status(TAG, "ignoring malformed page: ${it.message}") }+                    WearMusicProtocol.PLAYBACK_PATH -> runCatching {+                        WearMusicProtocol.json.decodeFromString<WearPlaybackState>(text)+                    }.onSuccess { WearMusicStore.get(context).setPlayback(it) }+                        .onFailure { Log.status(TAG, "ignoring malformed playback: ${it.message}") }+                }+            }+        }+        val created = WearLinkNode(context, WearMusicProtocol.CAPABILITY, listener)+        scope.launch {+            var wasConnected = false+            created.state.collect { linkState ->+                val connected = linkState is WearLinkState.Connected+                if (connected && !wasConnected) flushPending(context)+                wasConnected = connected+            }+        }+        created.start()+        return created+    }++    /** Ask the phone for one bounded page (first page when [WearPageRequest.cursor] is empty). */+    fun requestPage(context: Context, request: WearPageRequest) {+        scope.launch {+            get(context).sendMessage(+                WearMusicProtocol.PAGE_REQUEST_PATH,+                WearMusicProtocol.json.encodeToString(request).encodeToByteArray(),+            )+        }+    }++    /** Send a search query (typed or dictated) to the phone; results return as a SEARCH page. */+    fun requestSearch(context: Context, query: String, cursor: String = "") {+        scope.launch {+            get(context).sendMessage(+                WearMusicProtocol.SEARCH_REQUEST_PATH,+                WearMusicProtocol.json.encodeToString(WearSearchRequest(query, cursor)).encodeToByteArray(),+            )+        }+    }++    /** Send one op to the phone's playback service; the op also stays queued in the store until reflected. */+    fun sendOp(context: Context, op: WearMusicOp) {+        scope.launch {+            get(context).sendMessage(+                WearMusicProtocol.OP_PATH,+                WearMusicProtocol.json.encodeToString(op).encodeToByteArray(),+            )+        }+    }++    /** Resend every queued op on (re)connect; the phone executes, the watch only reflects state. */+    fun flushPending(context: Context) {+        for (op in WearMusicStore.get(context).pendingOps.value) sendOp(context, op)+    }++    /** Publish watch state as a data item. */+    fun publishWatchState(context: Context, state: WearWatchState) {+        scope.launch {+            get(context).putData(+                WearMusicProtocol.WATCH_STATE_PATH,+                WearMusicProtocol.json.encodeToString(state).encodeToByteArray(),+            )+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAddToPlaylistScreen.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAddToPlaylistScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAddToPlaylistScreen.ktnew file mode 100644index 0000000000..d4f765b297--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAddToPlaylistScreen.kt@@ -0,0 +1,36 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.wear.compose.material.Text+import androidx.wear.compose.material.Chip+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.ui.Modifier+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearMusicOp+import com.vayunmathur.music.wear.domain.WearOpKind+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageKey++/** Add-to-playlist sheet (phone AddToPlaylistDialog): the op executes on the phone. */+@Composable+fun WearAddToPlaylistScreen(store: WearMusicStore, musicId: Long, onRoute: (WearRoute) -> Unit) {+    val page = WearPageId(WearPageKey.PLAYLISTS)+    WearPageLoader(store, page)+    val pages by store.pages.collectAsState()+    Column {+        Text("Add to playlist")+        LazyColumn {+            items(pages[page]?.playlists.orEmpty()) { playlist ->+                Chip(label = { Text(playlist.name) }, onClick = {+                    store.enqueueOp(WearMusicOp(WearOpKind.ADD_TO_PLAYLIST, trackIds = listOf(musicId), entityId = playlist.id))+                    onRoute(WearRoute.Home)+                }, modifier = Modifier.fillMaxWidth())+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAlbumListScreen.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAlbumListScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAlbumListScreen.ktnew file mode 100644index 0000000000..58b89a86a9--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearAlbumListScreen.kt@@ -0,0 +1,31 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.wear.compose.material.Text+import androidx.wear.compose.material.Chip+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.ui.Modifier+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageKey++/** Albums tab, mirroring the phone's Albums page ordering. */+@Composable+fun WearAlbumListScreen(store: WearMusicStore, onRoute: (WearRoute) -> Unit) {+    val page = WearPageId(WearPageKey.ALBUMS)+    WearPageLoader(store, page)+    val pages by store.pages.collectAsState()+    Column {+        Text("Albums")+        LazyColumn {+            items(pages[page]?.albums.orEmpty()) { album ->+                Chip(label = { Text(album.name + " — " + album.artistName) }, onClick = { onRoute(WearRoute.AlbumDetail(album.id)) }, modifier = Modifier.fillMaxWidth())+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearArtistListScreen.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearArtistListScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearArtistListScreen.ktnew file mode 100644index 0000000000..6fdd5065c2--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearArtistListScreen.kt@@ -0,0 +1,31 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.wear.compose.material.Text+import androidx.wear.compose.material.Chip+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.ui.Modifier+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageKey++/** Artists tab, mirroring the phone's Artists page ordering. */+@Composable+fun WearArtistListScreen(store: WearMusicStore, onRoute: (WearRoute) -> Unit) {+    val page = WearPageId(WearPageKey.ARTISTS)+    WearPageLoader(store, page)+    val pages by store.pages.collectAsState()+    Column {+        Text("Artists")+        LazyColumn {+            items(pages[page]?.artists.orEmpty()) { artist ->+                Chip(label = { Text(artist.name) }, onClick = { onRoute(WearRoute.ArtistDetail(artist.id)) }, modifier = Modifier.fillMaxWidth())+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMainActivity.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMainActivity.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..97ce549c29--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMainActivity.kt@@ -0,0 +1,35 @@+package com.vayunmathur.music.wear.ui++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.wear.compose.material.MaterialTheme+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.sync.WearLinkBridge++/**+ * Watch music entry: mirrors the phone's pages (tabs, details, now playing,+ * queue, search) rendered only from cached page snapshots + streamed+ * playback state, so visited pages work offline. Playback itself always+ * happens on the phone; this UI only sends ops and reflects state.+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+        val store = WearMusicStore.get(this)+        WearLinkBridge.get(this)+        store.publishWatchState()+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.Home) }+                WearMusicRoot(store = store, route = route, onRoute = { route = it })+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMusicRoot.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMusicRoot.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMusicRoot.ktnew file mode 100644index 0000000000..cef3df7109--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearMusicRoot.kt@@ -0,0 +1,93 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.ChipDefaults+import androidx.wear.compose.material.Text+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearMusicOp+import com.vayunmathur.music.wear.domain.WearOpKind+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageKey+import com.vayunmathur.music.wear.domain.WearPageRequest+import com.vayunmathur.music.wear.sync.WearLinkBridge++/** Root switch over [WearRoute]: every phone page has exactly one watch screen here. */+@Composable+fun WearMusicRoot(store: WearMusicStore, route: WearRoute, onRoute: (WearRoute) -> Unit) {+    when (val current = route) {+        WearRoute.Home -> WearTrackListScreen(store, WearPageId(WearPageKey.HOME), "Songs", onRoute)+        WearRoute.Albums -> WearAlbumListScreen(store, onRoute)+        WearRoute.Artists -> WearArtistListScreen(store, onRoute)+        WearRoute.Playlists -> WearPlaylistListScreen(store, onRoute)+        WearRoute.NowPlaying -> WearNowPlayingScreen(store, onRoute)+        is WearRoute.AlbumDetail -> WearTrackListScreen(store, WearPageId(WearPageKey.ALBUM_DETAIL, current.albumId), "Album", onRoute)+        is WearRoute.ArtistDetail -> WearTrackListScreen(store, WearPageId(WearPageKey.ARTIST_DETAIL, current.artistId), "Artist", onRoute)+        is WearRoute.PlaylistDetail -> WearTrackListScreen(store, WearPageId(WearPageKey.PLAYLIST_DETAIL, current.playlistId), "Playlist", onRoute)+        is WearRoute.AddToPlaylist -> WearAddToPlaylistScreen(store, current.musicId, onRoute)+        WearRoute.Queue -> WearQueueScreen(store, onRoute)+        WearRoute.Search -> WearSearchScreen(store, onRoute)+        WearRoute.Settings -> WearSettingsScreen(store, onRoute)+    }+}++/** Requests the first snapshot for [page] when the watch has not visited it yet. */+@Composable+fun WearPageLoader(store: WearMusicStore, page: WearPageId) {+    val context = LocalContext.current+    val pages by store.pages.collectAsState()+    LaunchedEffect(page, pages.containsKey(page)) {+        if (!pages.containsKey(page)) WearLinkBridge.requestPage(context, WearPageRequest(page))+    }+}++/** Shared track rows: tap plays the page's queue on the phone starting at that track. */+@Composable+fun WearTrackRows(store: WearMusicStore, page: WearPageId, onRoute: (WearRoute) -> Unit) {+    val context = LocalContext.current+    val pages by store.pages.collectAsState()+    val playback by store.playback.collectAsState()+    val snapshot = pages[page]+    if (snapshot == null) {+        Text("Loading from your phone\u2026")+        return+    }+    LazyColumn {+        items(snapshot.tracks) { track ->+            Chip(+                label = { Text((if (track.id == playback.trackId) "\u25B6 " else "") + track.title) },+                secondaryLabel = { Text(track.artist) },+                onClick = {+                    store.enqueueOp(+                        WearMusicOp(+                            WearOpKind.PLAY_TRACKS,+                            trackIds = snapshot.tracks.map { it.id },+                            startIndex = snapshot.tracks.indexOf(track),+                        ),+                    )+                    onRoute(WearRoute.NowPlaying)+                },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth(),+            )+        }+        if (snapshot.nextCursor.isNotEmpty()) {+            item {+                Chip(+                    label = { Text("Load more") },+                    onClick = { WearLinkBridge.requestPage(context, WearPageRequest(page, snapshot.nextCursor)) },+                    modifier = Modifier.fillMaxWidth(),+                )+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearNowPlayingScreen.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearNowPlayingScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearNowPlayingScreen.ktnew file mode 100644index 0000000000..ea190c3714--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearNowPlayingScreen.kt@@ -0,0 +1,67 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.wear.compose.material.Button+import androidx.wear.compose.material.Chip+import androidx.wear.compose.material.Text+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearMusicOp+import com.vayunmathur.music.wear.domain.WearOpKind++/** Now-playing (phone Route.Song): transport ops go to the phone player; no audio plays here. */+@Composable+fun WearNowPlayingScreen(store: WearMusicStore, onRoute: (WearRoute) -> Unit) {+    val playback by store.playback.collectAsState()+    Column {+        Text(playback.title.ifEmpty { "Nothing playing" })+        Text(playback.artist)+        Text(+            formatMs(playback.positionMs) + " / " + formatMs(playback.durationMs),+        )+        Chip(+            label = { Text("Seek -30s") },+            onClick = {+                store.enqueueOp(WearMusicOp(WearOpKind.SEEK, positionMs = (playback.positionMs - 30_000L).coerceAtLeast(0L)))+            },+            modifier = Modifier.fillMaxWidth(),+        )+        Chip(+            label = { Text("Seek +30s") },+            onClick = {+                store.enqueueOp(WearMusicOp(WearOpKind.SEEK, positionMs = playback.positionMs + 30_000L))+            },+            modifier = Modifier.fillMaxWidth(),+        )+        Button(onClick = { store.enqueueOp(WearMusicOp(WearOpKind.SKIP_PREVIOUS)) }) { Text("Previous") }+        Button(onClick = { store.enqueueOp(WearMusicOp(WearOpKind.TOGGLE_PLAY_PAUSE)) }) {+            Text(if (playback.isPlaying) "Pause" else "Play")+        }+        Button(onClick = { store.enqueueOp(WearMusicOp(WearOpKind.SKIP_NEXT)) }) { Text("Next") }+        Chip(+            label = { Text("Shuffle: " + if (playback.shuffle) "on" else "off") },+            onClick = { store.enqueueOp(WearMusicOp(WearOpKind.TOGGLE_SHUFFLE)) },+            modifier = Modifier.fillMaxWidth(),+        )+        Chip(+            label = { Text("Repeat") },+            onClick = { store.enqueueOp(WearMusicOp(WearOpKind.CYCLE_REPEAT)) },+            modifier = Modifier.fillMaxWidth(),+        )+        Chip(+            label = { Text("Queue") },+            onClick = { onRoute(WearRoute.Queue) },+            modifier = Modifier.fillMaxWidth(),+        )+        if (playback.lyricsSnippet.isNotEmpty()) Text(playback.lyricsSnippet)+    }+}++private fun formatMs(ms: Long): String {+    val totalSeconds = ms / 1000+    return (totalSeconds / 60).toString() + ":" + (totalSeconds % 60).toString().padStart(2, '0')+}
music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearPlaylistListScreen.kt
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearPlaylistListScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearPlaylistListScreen.ktnew file mode 100644index 0000000000..2d285117e6--- /dev/null+++ b/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearPlaylistListScreen.kt@@ -0,0 +1,31 @@+package com.vayunmathur.music.wear.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.wear.compose.material.Text+import androidx.wear.compose.material.Chip+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.ui.Modifier+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import com.vayunmathur.music.wear.data.WearMusicStore+import com.vayunmathur.music.wear.domain.WearPageId+import com.vayunmathur.music.wear.domain.WearPageKey++/** Playlists tab, mirroring the phone's Playlists page ordering. */+@Composable+fun WearPlaylistListScreen(store: WearMusicStore, onRoute: (WearRoute) -> Unit) {+    val page = WearPageId(WearPageKey.PLAYLISTS)+    WearPageLoader(store, page)+    val pages by store.pages.collectAsState()+    Column {+        Text("Playlists")+        LazyColumn {+            items(pages[page]?.playlists.orEmpty()) { playlist ->+                Chip(label = { Text(playlist.name) }, onClick = { onRoute(WearRoute.PlaylistDetail(playlist.id)) }, modifier = Modifier.fillMaxWidth())+            }+        }+    }+}
music-wear/src/main/java/com/vayunmathur/music/w
diff --git a/music-wear/src/main/java/com/vayunmathur/music/wear/ui/WearQueueScreen.kt b/music-wear/src/main/java/com/vayunmathur/music/w

Diff truncated.