wear: todo full-navigation companion; parallel wear sweeps
- Commit
0db2493aa0f74522ce11b732ef45e10f266d5d0b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-25 01:15 UTC (11 days ago)
- Parents
898be2a
New :todo-wear: the watch mirrors Todo's navigation - home catalog chips (smart views/lists/tags in phone order), per-view paginated pages (20/page, cached for offline), task detail, quick-add (phone-parsed), edit subset, confirmed delete. Phone holds the data; ops (complete/snooze/quick-add/edit/delete) apply on the phone via TodoRepository - repeating tasks roll forward, subtasks reopen - queue on the watch until a republished page reflects them. Settings/search/bulk/ list-editing explicitly omitted (recorded in AGENTS). Swept per shared-tree pattern: parallel Music and Communicate wear agents' files where they share settings/module surfaces. Verified: todo 403 tests + wear assemble/tests green incl. roll-forward and paging tests.
Diff
communicate/build.gradle.kts
diff --git a/communicate/build.gradle.kts b/communicate/build.gradle.ktsindex 281bc80a87..7812fa5957 100644--- a/communicate/build.gradle.kts+++ b/communicate/build.gradle.kts@@ -271,6 +271,8 @@ dependencies { // Google Voice virtual line: protojson RPCs + SIP-over-WSS transport go through // the repo's own Android-only HTTP/WebSocket stack (no OkHttp/Ktor). implementation(project(":library:network"))+ // Wear OS companion sync (RFCOMM, no Play services); phone side of :communicate-wear.+ implementation(project(":library:wearlink")) // Local Compose image loading for Google Voice MMS previews (remote https + content://). implementation(project(":library:image")) // RingRTC supplies both Signal's calling engine and the org.webrtc classes every line's calling
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 844c1b1334..4d9fdb8499 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/MainActivity.kt@@ -21,6 +21,10 @@ 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.+ com.vayunmathur.communicate.data.WearCommunicateSync.get(this).start() } @Composable
communicate/src/main/java/com/vayunmathur/communicate/data/WearCommunicateSync.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/WearCommunicateSync.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/WearCommunicateSync.ktnew file mode 100644index 0000000000..927ebd0c63--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/WearCommunicateSync.kt@@ -0,0 +1,401 @@+package com.vayunmathur.communicate.data++import android.content.Context+import com.vayunmathur.communicate.data.call.InAppCallPhase+import com.vayunmathur.communicate.data.call.InAppCallRegistry+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceParser+import com.vayunmathur.communicate.data.whatsapp.WhatsAppDatabase+import com.vayunmathur.communicate.data.whatsapp.WhatsAppServiceData+import com.vayunmathur.communicate.data.signal.SignalServiceData+import com.vayunmathur.communicate.domain.WearCommLine+import com.vayunmathur.communicate.domain.WearCommOp+import com.vayunmathur.communicate.domain.WearCommWatchState+import com.vayunmathur.communicate.domain.WearCommunicateProtocol+import com.vayunmathur.communicate.domain.WearCommunicateSnapshot+import com.vayunmathur.communicate.domain.WearIncomingCall+import com.vayunmathur.communicate.domain.WearMessage+import com.vayunmathur.communicate.domain.WearOpKind+import com.vayunmathur.communicate.domain.WearOpResult+import com.vayunmathur.communicate.domain.WearThread+import com.vayunmathur.communicate.domain.WearThreadRequest+import com.vayunmathur.communicate.domain.buildWearCommunicateSnapshot+import com.vayunmathur.communicate.domain.buildWearNewMessageAlert+import com.vayunmathur.communicate.domain.buildWearThreadPage+import com.vayunmathur.communicate.domain.validWearReply+import com.vayunmathur.communicate.domain.wearThreadKey+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.library.wearlink.WearLinkState+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/** Phone-side wear status; absence of a watch is a normal state, never an error. */+data class WearCommunicateSyncState(+ val companionPresent: Boolean = false,+ val lastPublishedAtMillis: Long? = null,+ val lastPublishedThreadCount: Int = 0,+ val lastWatchPendingOps: Int = 0,+)++/** Executes one validated watch op on the phone. Seam for unit tests. */+internal interface WearOpHandler {+ suspend fun quickReply(op: WearCommOp, body: String): Boolean+ suspend fun markRead(op: WearCommOp): Boolean+ suspend fun markVoicemailRead(op: WearCommOp): Boolean+ suspend fun declineCall(op: WearCommOp): Boolean+}++/**+ * Applies one watch op after protocol validation. Quick replies need a+ * non-blank capped body and a thread; mark-read needs a thread; voicemail+ * and decline need a target key. Archive/mute do not exist here because+ * the phone UI offers neither.+ */+internal suspend fun applyWearCommOp(op: WearCommOp, handler: WearOpHandler): Boolean =+ when (op.kind) {+ WearOpKind.QuickReply -> validWearReply(op)?.let { handler.quickReply(op, it) } ?: false+ WearOpKind.MarkRead -> op.threadKey.isNotBlank() && handler.markRead(op)+ WearOpKind.MarkVoicemailRead -> op.targetKey.isNotBlank() && handler.markVoicemailRead(op)+ WearOpKind.DeclineCall -> op.targetKey.isNotBlank() && handler.declineCall(op)+ }++/**+ * Phone side of the Communicate wear companion over WearLink (RFCOMM,+ * :library:wearlink): bounded snapshot data item, thread pages and small+ * alerts as messages, watch ops executed here against+ * [CommunicateRepository]. Repository access and decryption stay on the+ * phone; see [WearCommunicateProtocol] for caps and privacy choices.+ * Delivery is app-lifecycle-bound (no Play-services wakeup): the watch+ * keeps ops pending and resends on the next live session.+ */+class WearCommunicateSync private constructor(context: Context) {++ companion object {+ private const val TAG = "WearCommunicateSync"++ @Volatile+ private var instance: WearCommunicateSync? = null++ fun get(context: Context): WearCommunicateSync = instance ?: synchronized(this) {+ instance ?: WearCommunicateSync(context.applicationContext).also { instance = it }+ }+ }++ private val appContext = context.applicationContext+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ private val _state = MutableStateFlow(WearCommunicateSyncState())+ val state: StateFlow<WearCommunicateSyncState> = _state.asStateFlow()++ private var lastThreadsByKey: Map<String, WearThread> = emptyMap()+ private var lastCallKey: String? = null++ private val handler = object : WearOpHandler {+ override suspend fun quickReply(op: WearCommOp, body: String): Boolean {+ val choice: LineChoice = when (op.line) {+ WearCommLine.Sim -> LineChoice.Sim(op.subscriptionId ?: -1, "SIM")+ WearCommLine.GoogleVoice -> LineChoice.GoogleVoice+ WearCommLine.WhatsApp -> LineChoice.WhatsApp+ WearCommLine.Signal -> LineChoice.Signal+ WearCommLine.Rcs -> LineChoice.Rcs+ }+ return CommunicateRepository.sendMessage(+ appContext, choice, op.address, body,+ threadRemoteId = op.remoteId, participants = op.participants,+ )+ }++ override suspend fun markRead(op: WearCommOp): Boolean = runCatching {+ when (op.line) {+ WearCommLine.Sim ->+ CommunicateRepository.markSimThreadRead(appContext, op.threadId)+ WearCommLine.GoogleVoice -> op.remoteId?.let {+ CommunicateRepository.updateGoogleVoiceThread(+ appContext, it, GoogleVoiceParser.ThreadAction.MarkRead,+ )+ } ?: false+ WearCommLine.WhatsApp -> {+ CommunicateRepository.markWhatsAppRead(appContext, op.remoteId, op.address, null)+ true+ }+ WearCommLine.Signal -> {+ CommunicateRepository.markSignalRead(appContext, op.remoteId, op.address, null)+ true+ }+ WearCommLine.Rcs -> {+ CommunicateRepository.markRcsRead(appContext, op.remoteId, op.address)+ true+ }+ }+ }.getOrDefault(false)++ override suspend fun markVoicemailRead(op: WearCommOp): Boolean {+ val entry = CommunicateRepository.loadVoicemailsMerged(appContext)+ .firstOrNull { wearVoicemailKey(it) == op.targetKey } ?: return false+ return CommunicateRepository.markVoicemailEntryRead(appContext, entry)+ }++ override suspend fun declineCall(op: WearCommOp): Boolean {+ val call = InAppCallRegistry.state.value+ if (call.phase != InAppCallPhase.Incoming) return false+ if (wearCallKey(call.line, call.peerId) != op.targetKey) return false+ InAppCallRegistry.reject(source = "wear")+ return true+ }+ }++ private val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ if (path != WearCommunicateProtocol.WATCH_STATE_PATH) return+ val watchState = runCatching {+ WearCommunicateProtocol.json.decodeFromString<WearCommWatchState>(body.decodeToString())+ }.getOrNull() ?: return+ _state.update { it.copy(lastWatchPendingOps = watchState.pendingOps) }+ }++ override fun onMessage(path: String, body: ByteArray) {+ when (path) {+ WearCommunicateProtocol.REQUEST_SYNC_PATH -> scope.launch { publishSnapshot() }+ WearCommunicateProtocol.REQUEST_THREAD_PATH -> {+ val request = runCatching {+ WearCommunicateProtocol.json.decodeFromString<WearThreadRequest>(body.decodeToString())+ }.getOrNull() ?: return+ scope.launch { publishThreadPage(request) }+ }+ WearCommunicateProtocol.OP_PATH -> {+ val op = runCatching {+ WearCommunicateProtocol.json.decodeFromString<WearCommOp>(body.decodeToString())+ }.getOrNull()+ if (op == null) {+ Log.status(TAG, "ignoring malformed wear op")+ return+ }+ scope.launch {+ val ok = runCatching { applyWearCommOp(op, handler) }.getOrDefault(false)+ node.sendMessage(+ WearCommunicateProtocol.OP_RESULT_PATH,+ WearCommunicateProtocol.json.encodeToString(+ WearOpResult(op.opId, op.kind, ok),+ ).encodeToByteArray(),+ )+ if (ok) publishSnapshot()+ }+ }+ }+ }+ }++ private val node: WearLinkNode =+ WearLinkNode(appContext, WearCommunicateProtocol.CAPABILITY, listener)+ private var started = false++ fun start() {+ if (started) return+ started = true+ scope.launch {+ node.state.collect { linkState ->+ val present = linkState is WearLinkState.Connected+ val wasPresent = _state.value.companionPresent+ _state.update { it.copy(companionPresent = present) }+ if (present && !wasPresent) publishSnapshot()+ }+ }+ // Incoming-call alerts: only decline crosses back (no answer-on-watch).+ scope.launch {+ InAppCallRegistry.state.collect { call ->+ val key = if (call.phase == InAppCallPhase.Incoming) {+ wearCallKey(call.line, call.peerId)+ } else {+ null+ }+ if (key != null && key != lastCallKey) {+ node.sendMessage(+ WearCommunicateProtocol.INCOMING_CALL_PATH,+ WearCommunicateProtocol.json.encodeToString(+ WearIncomingCall(+ callKey = key,+ displayName = call.peerName,+ line = call.line?.toWearLine() ?: WearCommLine.Sim,+ isVideo = call.isVideo,+ timestampMillis = System.currentTimeMillis(),+ ),+ ).encodeToByteArray(),+ )+ }+ lastCallKey = key+ }+ }+ node.start()+ }++ fun syncNow() {+ scope.launch { publishSnapshot() }+ }++ /** Builds the bounded snapshot from the merged repository and publishes it. */+ suspend fun publishSnapshot() {+ val threads = CommunicateRepository.loadSmsThreadsMerged(appContext)+ val wearThreads = threads.map { thread ->+ thread.toWearThread(isDisappearing(thread))+ }+ val snapshot = buildWearCommunicateSnapshot(+ threads = wearThreads,+ calls = CommunicateRepository.loadCallLogsMerged(appContext).map { it.toWearCall() },+ voicemails = CommunicateRepository.loadVoicemailsMerged(appContext)+ .map { it.toWearVoicemail() },+ generatedAtMillis = System.currentTimeMillis(),+ )+ // Small new-message alerts for threads that advanced since the last snapshot.+ if (lastThreadsByKey.isNotEmpty()) {+ for (thread in snapshot.threads) {+ val previous = lastThreadsByKey[thread.key]+ if (previous != null && thread.timestampMillis > previous.timestampMillis &&+ thread.unreadCount > 0+ ) {+ node.sendMessage(+ WearCommunicateProtocol.NEW_MESSAGE_PATH,+ WearCommunicateProtocol.json.encodeToString(+ buildWearNewMessageAlert(thread, thread.timestampMillis),+ ).encodeToByteArray(),+ )+ }+ }+ }+ lastThreadsByKey = snapshot.threads.associateBy { it.key }+ val sent = node.putData(+ WearCommunicateProtocol.SNAPSHOT_PATH,+ WearCommunicateProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ )+ if (sent) {+ _state.update {+ it.copy(+ lastPublishedAtMillis = snapshot.generatedAtMillis,+ lastPublishedThreadCount = snapshot.threads.size,+ )+ }+ } else {+ Log.status(TAG, "publish snapshot not delivered (no live WearLink session)")+ }+ }++ /** Answers one thread-page request with a message carrying that page only. */+ suspend fun publishThreadPage(request: WearThreadRequest) {+ val thread = CommunicateRepository.loadSmsThreadsMerged(appContext)+ .firstOrNull { wearThreadKey(it.line.toWearLine(), it.remoteId, it.threadId) == request.threadKey }+ ?: return+ val disappearing = isDisappearing(thread)+ val messages = CommunicateRepository.loadSmsMessagesMerged(appContext, thread)+ .map { it.toWearMessage(thread, disappearing) }+ val page = buildWearThreadPage(+ threadKey = request.threadKey,+ messages = messages,+ beforeTimestampMillis = request.beforeTimestampMillis,+ generatedAtMillis = System.currentTimeMillis(),+ )+ node.sendMessage(+ WearCommunicateProtocol.THREAD_PAGE_PATH,+ WearCommunicateProtocol.json.encodeToString(page).encodeToByteArray(),+ requireAck = true,+ )+ }++ /** WhatsApp is the line whose unified cache knows its disappearing timer today. */+ private suspend fun isDisappearing(thread: SmsThread): Boolean {+ if (thread.line != CommunicateLine.WhatsApp) return false+ val jid = thread.remoteId?.takeIf { it.isNotBlank() } ?: return false+ return runCatching {+ WhatsAppDatabase.getDatabase(appContext).conversationDao()+ .getConversation(jid)?.ephemeralExpiration ?: 0L+ }.getOrDefault(0L) > 0L+ }++ private fun SmsThread.toWearThread(disappearing: Boolean): WearThread = WearThread(+ key = wearThreadKey(line.toWearLine(), remoteId, threadId),+ threadId = threadId,+ line = line.toWearLine(),+ address = address,+ remoteId = remoteId,+ subscriptionId = subscriptionId,+ displayName = displayName ?: groupTitle ?: address,+ snippet = snippet,+ timestampMillis = timestampMillis,+ unreadCount = unreadCount,+ isGroup = isGroup,+ groupTitle = groupTitle,+ participants = participants,+ disappearing = disappearing,+ )++ private fun SmsMessage.toWearMessage(thread: SmsThread, disappearing: Boolean): WearMessage {+ // Media crosses as a label only: no content URI, no mediaUrl from serviceData.+ val mediaLabel = when {+ attachments.isNotEmpty() -> mediaLabelFor(attachments.first().mimeType)+ WhatsAppServiceData.parse(serviceData)?.mediaMime != null ->+ mediaLabelFor(WhatsAppServiceData.parse(serviceData)?.mediaMime)+ SignalServiceData.parse(serviceData)?.mediaMime != null ->+ mediaLabelFor(SignalServiceData.parse(serviceData)?.mediaMime)+ else -> null+ }+ return WearMessage(+ messageKey = remoteId?.takeIf { it.isNotBlank() }+ ?: "${wearThreadKey(thread.line.toWearLine(), thread.remoteId, thread.threadId)}:$id",+ threadKey = wearThreadKey(thread.line.toWearLine(), thread.remoteId, thread.threadId),+ body = body,+ timestampMillis = timestampMillis,+ outgoing = outgoing,+ read = read,+ senderLabel = senderAddress.takeIf { thread.isGroup && !outgoing },+ mediaLabel = mediaLabel,+ status = status.name,+ disappearing = disappearing,+ )+ }++ private fun CommunicateCallLogEntry.toWearCall(): com.vayunmathur.communicate.domain.WearCallEntry =+ com.vayunmathur.communicate.domain.WearCallEntry(+ key = "${line.name}:$id",+ displayName = displayName ?: phoneNumber,+ phoneNumber = phoneNumber,+ type = type.name,+ timestampMillis = timestampMillis,+ durationSeconds = durationSeconds,+ line = line.toWearLine(),+ )++ private fun VoicemailEntry.toWearVoicemail(): com.vayunmathur.communicate.domain.WearVoicemail =+ com.vayunmathur.communicate.domain.WearVoicemail(+ key = wearVoicemailKey(this),+ phoneNumber = phoneNumber,+ timestampMillis = timestampMillis,+ durationSeconds = durationSeconds,+ transcript = transcript.orEmpty(),+ isRead = isRead,+ line = line.toWearLine(),+ )+}++/** Voicemail watch key; never the content URI or GV remote media reference. */+internal fun wearVoicemailKey(entry: VoicemailEntry): String =+ "${entry.line.name}:${entry.remoteId ?: entry.id}"++/** Incoming-call watch key from the registry's line + peer id. */+internal fun wearCallKey(line: CommunicateLine?, peerId: String): String =+ "${line?.name ?: WearCommLine.Sim.name}:$peerId"++internal fun CommunicateLine.toWearLine(): WearCommLine = WearCommLine.valueOf(name)++private fun mediaLabelFor(mimeType: String?): String = when {+ mimeType == null -> "File"+ mimeType.startsWith("image/") -> "Photo"+ mimeType.startsWith("video/") -> "Video"+ mimeType.startsWith("audio/") -> "Voice message"+ else -> "File"+}
communicate/src/main/java/com/vayunmathur/communicate/domain/WearCommunicateProtocol.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/domain/WearCommunicateProtocol.kt b/communicate/src/main/java/com/vayunmathur/communicate/domain/WearCommunicateProtocol.ktnew file mode 100644index 0000000000..1ac9aed386--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/domain/WearCommunicateProtocol.kt@@ -0,0 +1,421 @@+package com.vayunmathur.communicate.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/src/test/java/com/vayunmathur/communicate/data/WearCommunicateOpTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/WearCommunicateOpTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/WearCommunicateOpTest.ktnew file mode 100644index 0000000000..9d149fc991--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/WearCommunicateOpTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.communicate.data++import com.vayunmathur.communicate.domain.WearCommLine+import com.vayunmathur.communicate.domain.WearCommOp+import com.vayunmathur.communicate.domain.WearOpKind+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++class WearCommunicateOpTest {++ private class FakeHandler(+ var replyOk: Boolean = true,+ var readOk: Boolean = true,+ ) : WearOpHandler {+ val calls = mutableListOf<String>()++ override suspend fun quickReply(op: WearCommOp, body: String): Boolean {+ calls += "reply:${op.threadKey}:$body"+ return replyOk+ }++ override suspend fun markRead(op: WearCommOp): Boolean {+ calls += "read:${op.threadKey}"+ return readOk+ }++ override suspend fun markVoicemailRead(op: WearCommOp): Boolean {+ calls += "voicemail:${op.targetKey}"+ return true+ }++ override suspend fun declineCall(op: WearCommOp): Boolean {+ calls += "decline:${op.targetKey}"+ return true+ }+ }++ @Test+ fun quickReplyReachesHandlerTrimmed() = runBlocking {+ val handler = FakeHandler()+ val op = WearCommOp(+ opId = "1", kind = WearOpKind.QuickReply, threadKey = "Sim:3",+ line = WearCommLine.Sim, body = " OK ",+ )+ assertTrue(applyWearCommOp(op, handler))+ assertEquals(listOf("reply:Sim:3:OK"), handler.calls)+ }++ @Test+ fun blankReplyAndMissingTargetsNeverReachHandler() = runBlocking {+ val handler = FakeHandler()+ assertFalse(+ applyWearCommOp(+ WearCommOp(opId = "1", kind = WearOpKind.QuickReply, threadKey = "Sim:3", body = " "),+ handler,+ ),+ )+ assertFalse(+ applyWearCommOp(WearCommOp(opId = "2", kind = WearOpKind.MarkRead), handler),+ )+ assertFalse(+ applyWearCommOp(WearCommOp(opId = "3", kind = WearOpKind.DeclineCall), handler),+ )+ assertFalse(+ applyWearCommOp(WearCommOp(opId = "4", kind = WearOpKind.MarkVoicemailRead), handler),+ )+ assertEquals(emptyList(), handler.calls)+ }++ @Test+ fun markReadVoicemailAndDeclineDispatch() = runBlocking {+ val handler = FakeHandler()+ assertTrue(+ applyWearCommOp(+ WearCommOp(opId = "1", kind = WearOpKind.MarkRead, threadKey = "Signal:c1"),+ handler,+ ),+ )+ assertTrue(+ applyWearCommOp(+ WearCommOp(+ opId = "2", kind = WearOpKind.MarkVoicemailRead, targetKey = "Sim:9",+ ),+ handler,+ ),+ )+ assertTrue(+ applyWearCommOp(+ WearCommOp(+ opId = "3", kind = WearOpKind.DeclineCall, targetKey = "WhatsApp:peer",+ ),+ handler,+ ),+ )+ assertEquals(+ listOf("read:Signal:c1", "voicemail:Sim:9", "decline:WhatsApp:peer"),+ handler.calls,+ )+ }++ @Test+ fun handlerFailurePropagatesAsFailure() = runBlocking {+ val handler = FakeHandler(replyOk = false)+ assertFalse(+ applyWearCommOp(+ WearCommOp(+ opId = "1", kind = WearOpKind.QuickReply, threadKey = "Sim:3", body = "OK",+ ),+ handler,+ ),+ )+ }+}
communicate/src/test/java/com/vayunmathur/communicate/domain/WearCommunicateProtocolTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/domain/WearCommunicateProtocolTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/domain/WearCommunicateProtocolTest.ktnew file mode 100644index 0000000000..cb4fba2b14--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/domain/WearCommunicateProtocolTest.kt@@ -0,0 +1,186 @@+package com.vayunmathur.communicate.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))+ }+}
music/build.gradle.kts
diff --git a/music/build.gradle.kts b/music/build.gradle.ktsindex c577dfd917..fb8913511d 100644--- a/music/build.gradle.kts+++ b/music/build.gradle.kts@@ -42,6 +42,8 @@ dependencies { // Opus transcoder: every cast audio track is 48 kHz Opus, and most of the library is not. implementation(project(":sdk:cast")) implementation(project(":library:media"))+ implementation(project(":library:wearlink"))+ implementation(libs.kotlinx.serialization.json) // Car-view store-listing screenshots render through the shared host renderer. add("screenshotTestImplementation", project(":library:carhost"))
music/src/main/java/com/vayunmathur/music/MainActivity.kt
diff --git a/music/src/main/java/com/vayunmathur/music/MainActivity.kt b/music/src/main/java/com/vayunmathur/music/MainActivity.ktindex 0f976f7d64..183ef1299a 100644--- a/music/src/main/java/com/vayunmathur/music/MainActivity.kt+++ b/music/src/main/java/com/vayunmathur/music/MainActivity.kt@@ -13,6 +13,7 @@ import com.vayunmathur.music.data.MusicRepository import com.vayunmathur.music.platform.MusicViewModel import com.vayunmathur.music.platform.MusicViewModelFactory import com.vayunmathur.music.platform.PlaybackManager+import com.vayunmathur.music.sync.WearMusicSync /** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() {@@ -20,6 +21,12 @@ class MainActivity : MaActivity() { MusicViewModelFactory(application, MusicRepository.get(application), PlaybackManager.getInstance(this)) } + override fun onCreateBeforeContent() {+ // Phone side of the Wear OS companion: page server + playback-state+ // streamer + op executor (see sync/WearMusicSync.kt).+ WearMusicSync.start(this)+ }+ @Composable override fun Content() { val (permissions, message) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
music/src/main/java/com/vayunmathur/music/domain/WearMusicProtocol.kt
diff --git a/music/src/main/java/com/vayunmathur/music/domain/WearMusicProtocol.kt b/music/src/main/java/com/vayunmathur/music/domain/WearMusicProtocol.ktnew file mode 100644index 0000000000..2ff3b515f2--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/domain/WearMusicProtocol.kt@@ -0,0 +1,198 @@+package com.vayunmathur.music.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/src/main/java/com/vayunmathur/music/sync/WearMusicSync.kt
diff --git a/music/src/main/java/com/vayunmathur/music/sync/WearMusicSync.kt b/music/src/main/java/com/vayunmathur/music/sync/WearMusicSync.ktnew file mode 100644index 0000000000..6cff958694--- /dev/null+++ b/music/src/main/java/com/vayunmathur/music/sync/WearMusicSync.kt@@ -0,0 +1,202 @@+package com.vayunmathur.music.sync++import android.content.Context+import com.vayunmathur.library.wearlink.WearLinkListener+import com.vayunmathur.library.wearlink.WearLinkNode+import com.vayunmathur.music.data.MusicRepository+import com.vayunmathur.music.domain.WearAlbum+import com.vayunmathur.music.domain.WearArtist+import com.vayunmathur.music.domain.WearMusicOp+import com.vayunmathur.music.domain.WearMusicProtocol+import com.vayunmathur.music.domain.WearOpKind+import com.vayunmathur.music.domain.WearPageId+import com.vayunmathur.music.domain.WearPageKey+import com.vayunmathur.music.domain.WearPageRequest+import com.vayunmathur.music.domain.WearPageSnapshot+import com.vayunmathur.music.domain.WearPlaylist+import com.vayunmathur.music.domain.WearPlaybackState+import com.vayunmathur.music.domain.WearSearchRequest+import com.vayunmathur.music.domain.WearTrack+import com.vayunmathur.music.domain.capWearTrack+import com.vayunmathur.music.domain.paginateWearPage+import com.vayunmathur.music.platform.PlaybackManager+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.launch+import kotlinx.serialization.encodeToString++/**+ * Phone side of the Music WearLink companion: serves bounded page snapshots+ * from the phone library, streams now-playing state, and executes watch ops+ * in the phone playback service. The catalog and all audio stay here.+ */+object WearMusicSync {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var node: WearLinkNode? = null+ private var generation = 0L++ /** Start phone-side WearLink (call from the app's main activity once). */+ fun start(context: Context) {+ val appContext = context.applicationContext+ if (node != null) return+ synchronized(this) {+ if (node != null) return+ val listener = object : WearLinkListener {+ override fun onMessage(path: String, body: ByteArray) {+ val text = body.decodeToString()+ when (path) {+ WearMusicProtocol.PAGE_REQUEST_PATH -> runCatching {+ WearMusicProtocol.json.decodeFromString<WearPageRequest>(text)+ }.onSuccess { scope.launch { publishPage(appContext, it) } }+ WearMusicProtocol.SEARCH_REQUEST_PATH -> runCatching {+ WearMusicProtocol.json.decodeFromString<WearSearchRequest>(text)+ }.onSuccess { req ->+ scope.launch {+ publishPage(+ appContext,+ WearPageRequest(WearPageId(WearPageKey.SEARCH, query = req.query), req.cursor),+ )+ }+ }+ WearMusicProtocol.OP_PATH -> runCatching {+ WearMusicProtocol.json.decodeFromString<WearMusicOp>(text)+ }.onSuccess { op -> scope.launch { executeOp(appContext, op) } }+ }+ }+ }+ node = WearLinkNode(appContext, WearMusicProtocol.CAPABILITY, listener).also { it.start() }+ observePlayback(appContext)+ }+ }++ private fun observePlayback(context: Context) {+ val playback = PlaybackManager.getInstance(context)+ scope.launch {+ combine(+ playback.isPlaying, playback.currentMediaItem, playback.shuffleMode, playback.repeatMode,+ ) { playing, item, shuffle, repeat ->+ WearPlaybackState(+ title = item?.mediaMetadata?.title?.toString().orEmpty(),+ artist = item?.mediaMetadata?.artist?.toString().orEmpty(),+ album = item?.mediaMetadata?.albumTitle?.toString().orEmpty(),+ isPlaying = playing,+ positionMs = playback.currentPosition.value,+ durationMs = playback.duration.value,+ shuffle = shuffle,+ repeatMode = repeat,+ )+ }.collect { state ->+ node?.putData(+ WearMusicProtocol.PLAYBACK_PATH,+ WearMusicProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }+ }++ private suspend fun publishPage(context: Context, request: WearPageRequest) {+ val snapshot = buildPage(context, request)+ node?.putData(+ WearMusicProtocol.PAGE_PATH,+ WearMusicProtocol.json.encodeToString(snapshot).encodeToByteArray(),+ )+ }++ /** Builds one bounded page from the phone library; ordering matches the phone tabs. */+ suspend fun buildPage(context: Context, request: WearPageRequest): WearPageSnapshot {+ val repo = MusicRepository.get(context)+ val allTracks = repo.getAllMusic()+ val gen = ++generation+ fun tracksPage(tracks: List<com.vayunmathur.music.data.Music>): WearPageSnapshot {+ val (slice, next) = paginateWearPage(tracks.map { it.toWear() }, request.cursor)+ return WearPageSnapshot(+ page = request.page, generation = gen, tracks = slice.map(::capWearTrack),+ nextCursor = next, totalCount = tracks.size,+ )+ }+ return when (request.page.key) {+ WearPageKey.HOME, WearPageKey.TRACKS -> tracksPage(allTracks)+ WearPageKey.ALBUMS -> {+ val (slice, next) = paginateWearPage(+ repo.getAllAlbums().map { WearAlbum(it.id, it.name) }, request.cursor,+ )+ WearPageSnapshot(request.page, gen, albums = slice, nextCursor = next, totalCount = repo.getAllAlbums().size)+ }+ WearPageKey.ARTISTS -> {+ val (slice, next) = paginateWearPage(+ repo.getAllArtists().map { WearArtist(it.id, it.name) }, request.cursor,+ )+ WearPageSnapshot(request.page, gen, artists = slice, nextCursor = next, totalCount = repo.getAllArtists().size)+ }+ WearPageKey.PLAYLISTS -> {+ val (slice, next) = paginateWearPage(+ repo.getAllPlaylists().map { WearPlaylist(it.id, it.name) }, request.cursor,+ )+ WearPageSnapshot(request.page, gen, playlists = slice, nextCursor = next, totalCount = repo.getAllPlaylists().size)+ }+ WearPageKey.ALBUM_DETAIL -> tracksPage(allTracks.filter { it.albumId == request.page.entityId })+ WearPageKey.ARTIST_DETAIL -> tracksPage(allTracks.filter { it.artistId == request.page.entityId })+ WearPageKey.PLAYLIST_DETAIL -> {+ val ids = repo.getFromRight(request.page.entityId, com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST)+ val byId = allTracks.associateBy { it.id }+ tracksPage(ids.mapNotNull { byId[it] })+ }+ WearPageKey.SEARCH -> {+ val q = request.page.query.lowercase()+ tracksPage(+ allTracks.filter {+ q.isEmpty() || it.title.lowercase().contains(q) ||+ it.artist.lowercase().contains(q) || it.album.lowercase().contains(q)+ },+ )+ }+ WearPageKey.QUEUE, WearPageKey.NOW_PLAYING, WearPageKey.SETTINGS ->+ WearPageSnapshot(request.page, gen, totalCount = 0)+ }+ }++ /** Executes one watch op in the phone playback service / library. */+ suspend fun executeOp(context: Context, op: WearMusicOp) {+ val playback = PlaybackManager.getInstance(context)+ val repo = MusicRepository.get(context)+ val allTracks = repo.getAllMusic()+ val byId = allTracks.associateBy { it.id }+ when (op.kind) {+ WearOpKind.PLAY_TRACKS -> playback.playSong(+ op.trackIds.mapNotNull { byId[it] }, op.startIndex.coerceAtLeast(0),+ )+ WearOpKind.PLAY_SHUFFLED -> playback.playShuffled(op.trackIds.mapNotNull { byId[it] })+ WearOpKind.TOGGLE_PLAY_PAUSE -> playback.togglePlayPause()+ WearOpKind.SEEK -> playback.seekTo(op.positionMs)+ WearOpKind.SKIP_NEXT -> playback.skipNext()+ WearOpKind.SKIP_PREVIOUS -> playback.skipPrevious()+ WearOpKind.TOGGLE_SHUFFLE -> playback.toggleShuffle()+ WearOpKind.CYCLE_REPEAT -> playback.toggleRepeat()+ WearOpKind.PLAY_ALBUM -> {+ val tracks = allTracks.filter { it.albumId == op.entityId }+ if (tracks.isNotEmpty()) playback.playSong(tracks, 0)+ }+ WearOpKind.PLAY_ARTIST -> {+ val tracks = allTracks.filter { it.artistId == op.entityId }+ if (tracks.isNotEmpty()) playback.playSong(tracks, 0)+ }+ WearOpKind.PLAY_PLAYLIST -> {+ val ids = repo.getFromRight(op.entityId, com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST)+ val tracks = ids.mapNotNull { byId[it] }+ if (tracks.isNotEmpty()) playback.playSong(tracks, 0)+ }+ WearOpKind.ADD_TO_QUEUE -> Unit // queue append runs through playSong on phone; no silent watch-side claim+ WearOpKind.ADD_TO_PLAYLIST -> op.trackIds.forEach {+ repo.upsertMatching(com.vayunmathur.library.util.ManyManyMatching(it, op.entityId, com.vayunmathur.music.data.TYPE_MUSIC_PLAYLIST))+ }+ WearOpKind.CREATE_PLAYLIST -> if (op.text.isNotBlank()) repo.upsertPlaylist(com.vayunmathur.music.data.Playlist(name = op.text))+ }+ }++ private fun com.vayunmathur.music.data.Music.toWear(): WearTrack =+ WearTrack(id = id, title = title, artist = artist, album = album, durationMs = duration)+}
music/src/test/java/com/vayunmathur/music/domain/WearMusicProtocolTest.kt
diff --git a/music/src/test/java/com/vayunmathur/music/domain/WearMusicProtocolTest.kt b/music/src/test/java/com/vayunmathur/music/domain/WearMusicProtocolTest.ktnew file mode 100644index 0000000000..a593e62d17--- /dev/null+++ b/music/src/test/java/com/vayunmathur/music/domain/WearMusicProtocolTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.music.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearMusicProtocolTest {++ @Test+ fun goldenPageJson() {+ val snapshot = WearPageSnapshot(+ page = WearPageId(WearPageKey.HOME),+ generation = 7L,+ tracks = listOf(WearTrack(3L, "Blue", "Artist", "Album", 1_000L)),+ nextCursor = "30",+ totalCount = 31,+ )+ assertEquals(+ """{"page":{"key":"HOME"},"generation":7,"tracks":[{"id":3,"title":"Blue","artist":"Artist","album":"Album","durationMs":1000}],"nextCursor":"30","totalCount":31}""",+ WearMusicProtocol.json.encodeToString(snapshot),+ )+ }++ @Test+ fun goldenOpJson() {+ val op = WearMusicOp(WearOpKind.PLAY_TRACKS, trackIds = listOf(3L, 4L), startIndex = 1)+ assertEquals(+ """{"kind":"PLAY_TRACKS","trackIds":[3,4],"startIndex":1}""",+ WearMusicProtocol.json.encodeToString(op),+ )+ }++ @Test+ fun goldenPlaybackJson() {+ val state = WearPlaybackState(trackId = 3L, title = "Blue", isPlaying = true, shuffle = true, repeatMode = 2)+ assertEquals(+ """{"trackId":3,"title":"Blue","isPlaying":true,"shuffle":true,"repeatMode":2}""",+ WearMusicProtocol.json.encodeToString(state),+ )+ }++ @Test+ fun paginationWalksAllItemsOnce() {+ val items = (1..75).toList()+ val seen = mutableListOf<Int>()+ var cursor = ""+ var pages = 0+ do {+ val (slice, next) = paginateWearPage(items, cursor, pageSize = 30)+ seen += slice+ cursor = next+ pages+++ } while (cursor.isNotEmpty())+ assertEquals(items, seen)+ assertEquals(3, pages)+ }++ @Test+ fun paginationMalformedCursorRestarts() {+ val (slice, _) = paginateWearPage((1..10).toList(), "junk", pageSize = 4)+ assertEquals(listOf(1, 2, 3, 4), slice)+ }++ @Test+ fun playbackReducerReflectsPhoneReportOnly() {+ val before = WearPlaybackState(title = "Old", isPlaying = false)+ val reported = WearPlaybackState(title = "New", isPlaying = true, positionMs = 5L)+ val after = reducePlayback(before, WearMusicOp(WearOpKind.TOGGLE_PLAY_PAUSE), reported)+ assertEquals(reported, after)+ assertTrue(after.isPlaying)+ }++ @Test+ fun repeatCycleMatchesPhoneOrder() {+ assertEquals(2, nextWearRepeatMode(0))+ assertEquals(1, nextWearRepeatMode(2))+ assertEquals(0, nextWearRepeatMode(1))+ }++ @Test+ fun pageRoundTrip() {+ val snapshot = WearPageSnapshot(+ WearPageId(WearPageKey.SEARCH, query = "blue"),+ tracks = listOf(WearTrack(1L, "Blue Suede")),+ totalCount = 1,+ )+ assertEquals(+ snapshot,+ WearMusicProtocol.json.decodeFromString<WearPageSnapshot>(WearMusicProtocol.json.encodeToString(snapshot)),+ )+ }+}
settings.gradle.kts
diff --git a/settings.gradle.kts b/settings.gradle.ktsindex df5214d43b..c2aaeebcdd 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -108,6 +108,8 @@ include(":games:chess") include(":games:unblockjam") include(":games:wordmaker") include(":music")+include(":music:wear")+project(":music:wear").projectDir = file("music-wear") include(":clock") include(":clock:wear") project(":clock:wear").projectDir = file("clock-wear")@@ -133,6 +135,7 @@ include(":sdk:cast") include(":sdk:controller") include(":things") include(":todo")+include(":todo-wear") include(":education") include(":everysync") include(":travel")@@ -154,6 +157,7 @@ include(":fooddelivery") include(":measure") include(":taxi") include(":communicate")+include(":communicate-wear") include(":euicc") include(":globalesim") include(":backup")
todo-wear/AGENTS.md
diff --git a/todo-wear/AGENTS.md b/todo-wear/AGENTS.mdnew file mode 100644index 0000000000..488d7a51ed--- /dev/null+++ b/todo-wear/AGENTS.md@@ -0,0 +1,63 @@+# AGENTS.md — todo-wear/ (':todo-wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `todo-wear/` + `todo/` (the phone side of the same feature).++- Gradle: :todo-wear / dir: todo-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 Todo (`:todo`). This module deliberately+uses `applicationId = "com.vayunmathur.todo"` (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.++## Navigation mirror (phone Route -> watch WearRoute)+- `Route.TodoList("inbox"|"today"|"upcoming"|"priority"|"all"|"completed")`+ -> `WearRoute.Page` with the same key (smart views, phone drawer order)+- `Route.TodoList("list:<syncId>")` / `("tag:<tag>")` -> `WearRoute.Page`+ with the same key (catalog carries every list/tag from the phone drawer)+- `Route.TodoDetail(id)` -> `WearRoute.TaskDetail(syncId)` (syncId, not the+ phone's Room id, is the cross-device identity)+- Quick-add sheet -> `WearRoute.QuickAdd(pageKey)`; detail edit ->+ `WearRoute.EditTask(syncId)`; delete -> `WearRoute.ConfirmDelete(syncId)`+- `Route.Settings`: NO watch counterpart — settings, sync setup, import/+ export and data management stay on the phone (screen + data-entry cost+ with no watch benefit). Also omitted, deliberately: search, sort,+ manual reorder, bulk selection, list/tag/section editing, recurrence+ and reminder-offset editing, blocked-by/estimates, subtask creation+ (existing subtasks show and can be checked off). These remain fully+ available in the phone detail editor the watch data comes from.++## Protocol+`domain/WearTodoProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearTodoProtocolTest` pins the same golden JSON.++- Catalog + page snapshots: WearLink data items (`/todo/catalog`,+ `/todo/page`, phone -> watch; paginated, PAGE_SIZE tasks per page)+- Page/sync requests: WearLink messages (`/todo/request-page`,+ `/todo/request-sync`, watch -> phone)+- Watch-originated ops: WearLink message (`/todo/op`: SET_DONE incl.+ repeating-task roll-forward on the phone, SNOOZE_HOUR/SNOOZE_TOMORROW,+ QUICK_ADD parsed by the phone's QuickAddParser, EDIT title/due/priority,+ DELETE with watch-side confirmation)+- Transport: :library:wearlink (RFCOMM, no Play services); app-lifecycle-bound++## Sync semantics (stated, not implied)+- Phone -> watch: bounded catalog (≤100 views) + per-view pages of 20+ tasks, ≤90_000 JSON bytes each. The watch caches catalog and every+ visited page in app-private files and renders them fully offline.+- Watch -> phone: ops apply on the phone only (source of truth). An op+ stays pending (persisted, resent on reconnect) until a refreshed+ catalog/page reflects it; SET_DONE/EDIT/DELETE also overlay the cached+ pages locally so the watch never shows pre-op state as confirmed.++## Verify (this module only)+```+./gradlew :todo-wear:assembleDev+./gradlew :todo-wear:testDebugUnitTest+```
todo-wear/build.gradle.kts
diff --git a/todo-wear/build.gradle.kts b/todo-wear/build.gradle.ktsnew file mode 100644index 0000000000..d793be5dd6--- /dev/null+++ b/todo-wear/build.gradle.kts@@ -0,0 +1,39 @@+plugins {+ id("common-conventions-wear")+}++launcherIcon {+ symbol = "checklist"+}++// 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.todo.wear"+ defaultConfig {+ applicationId = "com.vayunmathur.todo"+ // 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/WearTodoProtocol.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)+}
todo-wear/src/main/AndroidManifest.xml
diff --git a/todo-wear/src/main/AndroidManifest.xml b/todo-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..7ccb8c3001--- /dev/null+++ b/todo-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>
todo-wear/src/main/java/com/vayunmathur/todo/wear/data/WearTodoStore.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/data/WearTodoStore.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/data/WearTodoStore.ktnew file mode 100644index 0000000000..0728e7253b--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/data/WearTodoStore.kt@@ -0,0 +1,170 @@+package com.vayunmathur.todo.wear.data++import android.content.Context+import com.vayunmathur.library.log.Log+import com.vayunmathur.todo.wear.domain.WearTodoCatalog+import com.vayunmathur.todo.wear.domain.WearTodoOp+import com.vayunmathur.todo.wear.domain.WearTodoOpKind+import com.vayunmathur.todo.wear.domain.WearTodoPage+import com.vayunmathur.todo.wear.domain.WearTodoProtocol+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.encodeToString++/**+ * The watch's local cache: the last phone catalog, every visited page+ * snapshot, and this watch's pending ops — all persisted as JSON in+ * app-private storage so every page reads fully offline (phone absent,+ * process cold-started). The phone stays the source of truth; pending ops+ * leave the queue only when a fresh page/catalog no longer needs their+ * local overlay, never on send alone. Reflected-op detection here is+ * deliberately simple: when a page for the op's view is republished with a+ * newer generation, ops targeting tasks it contains (or no longer+ * contains, for deletes) are dropped.+ */+class WearTodoStore private constructor(private val context: Context) {++ companion object {+ private const val TAG = "WearTodoStore"++ @Volatile+ private var instance: WearTodoStore? = null++ /** The process-wide store (bridge and UI must agree on one). */+ fun get(context: Context): WearTodoStore = instance ?: synchronized(this) {+ instance ?: WearTodoStore(context.applicationContext).also { instance = it }+ }++ /** New op / quick-add task ids use the phone's syncId shape (32 hex chars). */+ fun newId(): String = UUID.randomUUID().toString().replace("-", "")+ }++ private val catalogFile = File(context.filesDir, "wear-todo-catalog.json")+ private val pagesFile = File(context.filesDir, "wear-todo-pages.json")+ private val pendingFile = File(context.filesDir, "wear-todo-pending.json")++ private val _catalog = MutableStateFlow(loadCatalog())+ private val _pages = MutableStateFlow(loadPages())+ private val _pendingOps = MutableStateFlow(loadPending())++ val catalog: StateFlow<WearTodoCatalog> = _catalog.asStateFlow()++ /** Cached pages by "pageKey@offset". */+ val pages: StateFlow<Map<String, WearTodoPage>> = _pages.asStateFlow()++ /** Watch-originated ops not yet reflected by the phone. */+ val pendingOps: StateFlow<List<WearTodoOp>> = _pendingOps.asStateFlow()++ val appliedCatalogAtMillis: Long get() = _catalog.value.generatedAtMillis++ fun setCatalog(catalog: WearTodoCatalog) {+ if (catalog.generatedAtMillis < _catalog.value.generatedAtMillis) return+ _catalog.value = catalog+ persist(catalogFile, WearTodoProtocol.json.encodeToString(catalog))+ com.vayunmathur.todo.wear.sync.WearLinkBridge.publishWatchState(context)+ }++ fun setPage(page: WearTodoPage) {+ val key = pageKey(page.pageKey, page.offset)+ val existing = _pages.value[key]+ if (existing != null && page.generatedAtMillis < existing.generatedAtMillis) return+ _pages.value = _pages.value + (key to page)+ persist(pagesFile, WearTodoProtocol.json.encodeToString(_pages.value))+ dropReflected(page)+ com.vayunmathur.todo.wear.sync.WearLinkBridge.publishWatchState(context)+ }++ /** All cached slices of one view, in offset order (for offline paging). */+ fun pagesFor(pageKey: String): List<WearTodoPage> =+ _pages.value.values.filter { it.pageKey == pageKey }.sortedBy { it.offset }++ fun setDone(syncId: String, done: Boolean) =+ queue(WearTodoOp(WearTodoOpKind.SET_DONE, opId = newId(), syncId = syncId, done = done))++ fun snooze(syncId: String, tomorrow: Boolean) = queue(+ WearTodoOp(+ if (tomorrow) WearTodoOpKind.SNOOZE_TOMORROW else WearTodoOpKind.SNOOZE_HOUR,+ opId = newId(),+ syncId = syncId,+ ),+ )++ fun quickAdd(text: String, pageKey: String): WearTodoOp {+ val op = WearTodoOp(+ WearTodoOpKind.QUICK_ADD,+ opId = newId(),+ syncId = newId(),+ text = text.trim().take(WearTodoProtocol.MAX_TEXT_CHARS),+ pageKey = pageKey,+ )+ queue(op)+ return op+ }++ fun edit(syncId: String, title: String?, dueAt: Long?, clearDue: Boolean, priority: Int?) =+ queue(+ WearTodoOp(+ WearTodoOpKind.EDIT,+ opId = newId(),+ syncId = syncId,+ title = title,+ dueAt = dueAt,+ clearDue = clearDue,+ priority = priority,+ ),+ )++ fun delete(syncId: String) =+ queue(WearTodoOp(WearTodoOpKind.DELETE, opId = newId(), syncId = syncId))++ private fun queue(op: WearTodoOp) {+ // One pending op per (kind, task): a newer local action supersedes the+ // older one. QUICK_ADDs are exempt (opId-keyed, each is a new task).+ _pendingOps.value = _pendingOps.value.filter {+ op.kind == WearTodoOpKind.QUICK_ADD || it.kind != op.kind || it.syncId != op.syncId+ } + op+ persist(pendingFile, WearTodoProtocol.json.encodeToString(_pendingOps.value))+ com.vayunmathur.todo.wear.sync.WearLinkBridge.flushPending(context)+ }++ private fun dropReflected(page: WearTodoPage) {+ if (_pendingOps.value.isEmpty()) return+ val ids = page.tasks.flatMap { listOf(it.syncId) + it.subtasks.map { s -> s.syncId } }.toSet()+ val kept = _pendingOps.value.filter { op ->+ when (op.kind) {+ // A republished page decides these: present tasks carry the+ // phone's post-op state; a delete is reflected by absence+ // once its page is republished (checked by caller pages too).+ WearTodoOpKind.SET_DONE, WearTodoOpKind.EDIT -> op.syncId !in ids+ WearTodoOpKind.DELETE -> op.syncId in ids+ else -> true+ }+ }+ if (kept.size != _pendingOps.value.size) {+ _pendingOps.value = kept+ persist(pendingFile, WearTodoProtocol.json.encodeToString(kept))+ }+ }++ private fun pageKey(pageKey: String, offset: Int) = "$pageKey@$offset"++ private fun loadCatalog(): WearTodoCatalog = runCatching {+ WearTodoProtocol.json.decodeFromString<WearTodoCatalog>(catalogFile.readText())+ }.getOrDefault(WearTodoCatalog())++ private fun loadPages(): Map<String, WearTodoPage> = runCatching {+ WearTodoProtocol.json.decodeFromString<Map<String, WearTodoPage>>(pagesFile.readText())+ }.getOrDefault(emptyMap())++ private fun loadPending(): List<WearTodoOp> = runCatching {+ WearTodoProtocol.json.decodeFromString<List<WearTodoOp>>(pendingFile.readText())+ }.getOrDefault(emptyList())++ private fun persist(file: File, text: String) {+ runCatching { file.writeText(text) }+ .onFailure { Log.status(TAG, "persist ${file.name} failed: ${it.message}") }+ }+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/domain/WearTodoProtocol.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/domain/WearTodoProtocol.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/domain/WearTodoProtocol.ktnew file mode 100644index 0000000000..56b6e871a5--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/domain/WearTodoProtocol.kt@@ -0,0 +1,303 @@+package com.vayunmathur.todo.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch protocol for the Wear OS Todo companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: Gradle cannot let one+ * application module depend on another, so the wear module (`:todo-wear`,+ * applicationId `com.vayunmathur.todo`) carries a copy of this file under+ * `com.vayunmathur.todo.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: the phone+ * `Route.TodoList(viewKey)` destinations (smart views, per-list views, tag+ * views) become watch pages with the SAME [WearTodoViewEntry.key] strings+ * (`TodoView.key`: "inbox", "today", "upcoming", "priority", "all",+ * "completed", "list:<syncId>", "tag:<tag>"), and `Route.TodoDetail(id)`+ * becomes a watch task page keyed by the task's stable syncId. The phone's+ * `Route.Settings` has no watch counterpart (see todo-wear/AGENTS.md).+ *+ * Transport (WearLink, :library:wearlink — RFCOMM, no Play services):+ * - Data items: [CATALOG_PATH] phone -> watch (view index with counts),+ * [PAGE_PATH] phone -> watch (one bounded paginated page snapshot),+ * [WATCH_STATE_PATH] watch -> phone (what the watch cached + pending ops).+ * - Messages: [OP_PATH] watch -> phone (one op), [REQUEST_PAGE_PATH]+ * watch -> phone (ask for one page), [REQUEST_SYNC_PATH] watch -> phone+ * (ask for catalog + the default/last pages). Delivery needs a live+ * session; nothing wakes a dead phone process, so the watch caches every+ * catalog/page it receives and reads fully offline.+ *+ * Data lives on the phone. The watch never holds the task database: it+ * renders cached catalog/page snapshots and queues ops. Ops apply on the+ * phone only (source of truth); an op stays pending on the watch until a+ * refreshed catalog/page reflects it, and the watch UI says so.+ */+object WearTodoProtocol {+ /** WearLink appId the phone requires in the peer handshake. */+ const val CAPABILITY = "todo_wear_companion"++ /** Data-item path (phone -> watch): the [WearTodoCatalog] JSON. */+ const val CATALOG_PATH = "/todo/catalog"++ /** Data-item path (phone -> watch): one [WearTodoPage] JSON. */+ const val PAGE_PATH = "/todo/page"++ /** Data-item path (watch -> phone): the [WearTodoWatchState] JSON. */+ const val WATCH_STATE_PATH = "/todo/watch-state"++ /** Message path (watch -> phone): one [WearTodoOp] JSON. */+ const val OP_PATH = "/todo/op"++ /** Message path (watch -> phone): one [WearTodoPageRequest] JSON. */+ const val REQUEST_PAGE_PATH = "/todo/request-page"++ /** Message path (watch -> phone): ask for catalog + default pages. */+ const val REQUEST_SYNC_PATH = "/todo/request-sync"++ /** Tasks per page snapshot; "load more" fetches the next offset. */+ const val PAGE_SIZE = 20++ /** Largest catalog/page JSON in UTF-8 bytes (near the old 100 KB ceiling). */+ const val MAX_JSON_BYTES = 90_000++ /** Largest view index kept in one catalog; extras are dropped (tags last). */+ const val MAX_VIEWS = 100++ /** Field caps applied when a snapshot is built. */+ const val MAX_TITLE_CHARS = 120+ const val MAX_NOTES_CHARS = 1_000+ const val MAX_SUBTASKS = 20++ /** Cap on watch-entered text (quick-add / edit title) before it is sent. */+ const val MAX_TEXT_CHARS = 500++ /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+ val json: Json = Json { ignoreUnknownKeys = true }+}++/** One phone navigation destination in the watch catalog (a `TodoView.key`). */+@Serializable+data class WearTodoViewEntry(+ val key: String,+ val title: String,+ /** SMART, LIST or TAG — mirrors the phone drawer's sections. */+ val kind: String = "SMART",+ val openCount: Int = 0,+ val totalCount: Int = 0,+)++/** The phone's view index for the watch home page ([WearTodoProtocol.CATALOG_PATH]). */+@Serializable+data class WearTodoCatalog(+ val generatedAtMillis: Long = 0L,+ val views: List<WearTodoViewEntry> = emptyList(),+ /** The phone's default view key; the watch opens here first. */+ val defaultViewKey: String = "today",+ /** True when the view-count/byte caps dropped entries. */+ val truncated: Boolean = false,+)++/** One subtask trimmed to watch size, shown on the task page. */+@Serializable+data class WearTodoSubtask(+ val syncId: String,+ val title: String,+ val done: Boolean = false,+)++/** One top-level task trimmed to watch size. [syncId] is the stable sync identity. */+@Serializable+data class WearTodoTask(+ val syncId: String,+ val title: String,+ val notes: String = "",+ val done: Boolean = false,+ val dueAt: Long? = null,+ val dueAllDay: Boolean = true,+ val priority: Int = 0,+ val listSyncId: String? = null,+ val listName: String? = null,+ val section: String? = null,+ val tags: List<String> = emptyList(),+ val recurrence: String? = null,+ val reminderAt: Long? = null,+ val completedAt: Long? = null,+ val updatedAt: Long = 0L,+ val subtasks: List<WearTodoSubtask> = emptyList(),+ val overdue: Boolean = false,+ val blocked: Boolean = false,+ /** Due-bucket / section / "Completed" label the phone list groups this row under. */+ val groupLabel: String = "",+ val notesTruncated: Boolean = false,+)++/**+ * One bounded page of one view ([WearTodoProtocol.PAGE_PATH]). Paging is by+ * [offset] into the phone-ordered rows of [pageKey]; [totalCount] is the+ * full row count on the phone at [generatedAtMillis].+ */+@Serializable+data class WearTodoPage(+ val pageKey: String,+ val title: String = "",+ val generatedAtMillis: Long = 0L,+ val offset: Int = 0,+ val totalCount: Int = 0,+ val tasks: List<WearTodoTask> = emptyList(),+ /** True when the byte cap cut this page short (the rest pages normally). */+ val truncated: Boolean = false,+) {+ val hasMore: Boolean get() = offset + tasks.size < totalCount+ val nextOffset: Int get() = offset + tasks.size+}++/** What the watch last cached, published at [WearTodoProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearTodoWatchState(+ val appliedCatalogAtMillis: Long = 0L,+ val cachedPages: Int = 0,+ /** Watch-originated ops not yet reflected by the phone. */+ val pendingOps: Int = 0,+)++/** Ask the phone for one page (message [WearTodoProtocol.REQUEST_PAGE_PATH]). */+@Serializable+data class WearTodoPageRequest(+ val pageKey: String,+ val offset: Int = 0,+)++/** Kind of a watch-originated change. */+@Serializable+enum class WearTodoOpKind { SET_DONE, SNOOZE_HOUR, SNOOZE_TOMORROW, QUICK_ADD, EDIT, DELETE }++/**+ * One watch-originated op, as [WearTodoProtocol.OP_PATH]. [opId] is unique+ * per user action so quick-adds never dedupe against each other; the other+ * kinds carry the target task's [syncId]. EDIT uses null fields for+ * "unchanged" and [clearDue] for removing the due date. QUICK_ADD carries+ * raw [text] — the PHONE parses it with its QuickAddParser, so watch+ * dictation gets the phone's exact date/list/tag/priority semantics.+ */+@Serializable+data class WearTodoOp(+ val kind: WearTodoOpKind,+ val opId: String = "",+ val syncId: String = "",+ val done: Boolean = false,+ val text: String = "",+ val pageKey: String = "",+ val title: String? = null,+ val dueAt: Long? = null,+ val clearDue: Boolean = false,+ val priority: Int? = null,+)++/** Builds a bounded catalog: view caps then the byte cap (last entries drop first). */+fun buildWearCatalog(+ views: List<WearTodoViewEntry>,+ generatedAtMillis: Long,+ defaultViewKey: String,+): WearTodoCatalog {+ var kept = views.take(WearTodoProtocol.MAX_VIEWS)+ var truncated = kept.size < views.size+ var catalog = WearTodoCatalog(generatedAtMillis, kept, defaultViewKey, truncated)+ while (kept.isNotEmpty() &&+ WearTodoProtocol.json.encodeToString(catalog).encodeToByteArray().size >+ WearTodoProtocol.MAX_JSON_BYTES+ ) {+ kept = kept.dropLast(1)+ truncated = true+ catalog = catalog.copy(views = kept, truncated = true)+ }+ return catalog+}++/**+ * Builds one bounded page: field caps, the [WearTodoProtocol.PAGE_SIZE]+ * slice at [offset], then the byte cap enforced by shortening the page+ * (paging continues from the shortened end via [WearTodoPage.nextOffset]).+ */+fun buildWearPage(+ pageKey: String,+ title: String,+ allTasks: List<WearTodoTask>,+ offset: Int,+ generatedAtMillis: Long,+): WearTodoPage {+ val capped = allTasks.map { task ->+ task.copy(+ title = task.title.take(WearTodoProtocol.MAX_TITLE_CHARS),+ notes = task.notes.take(WearTodoProtocol.MAX_NOTES_CHARS),+ notesTruncated = task.notesTruncated ||+ task.notes.length > WearTodoProtocol.MAX_NOTES_CHARS,+ subtasks = task.subtasks.take(WearTodoProtocol.MAX_SUBTASKS).map {+ it.copy(title = it.title.take(WearTodoProtocol.MAX_TITLE_CHARS))+ },+ )+ }+ val safeOffset = offset.coerceIn(0, capped.size)+ var kept = capped.drop(safeOffset).take(WearTodoProtocol.PAGE_SIZE)+ var page = WearTodoPage(+ pageKey = pageKey,+ title = title,+ generatedAtMillis = generatedAtMillis,+ offset = safeOffset,+ totalCount = capped.size,+ tasks = kept,+ )+ while (kept.isNotEmpty() &&+ WearTodoProtocol.json.encodeToString(page).encodeToByteArray().size >+ WearTodoProtocol.MAX_JSON_BYTES+ ) {+ kept = kept.dropLast(1)+ page = page.copy(tasks = kept, truncated = true)+ }+ return page+}++/**+ * The watch's local view of a cached page while ops are pending: SET_DONE,+ * EDIT and DELETE apply to the cached rows so the watch does not show+ * pre-op state as truth; SNOOZE and QUICK_ADD cannot be rendered locally+ * (the phone computes reminder times and parses quick-add text) and only+ * count as pending. Phone snapshots remain the source of truth.+ */+fun overlayPendingTasks(tasks: List<WearTodoTask>, pendingOps: List<WearTodoOp>): List<WearTodoTask> {+ if (pendingOps.isEmpty()) return tasks+ var result = tasks+ for (op in pendingOps) {+ result = when (op.kind) {+ WearTodoOpKind.DELETE -> result.filter { it.syncId != op.syncId }+ WearTodoOpKind.SET_DONE -> result.map { task ->+ when {+ task.syncId == op.syncId -> task.copy(done = op.done)+ task.subtasks.any { it.syncId == op.syncId } -> task.copy(+ subtasks = task.subtasks.map {+ if (it.syncId == op.syncId) it.copy(done = op.done) else it+ },+ )+ else -> task+ }+ }+ WearTodoOpKind.EDIT -> result.map { task ->+ if (task.syncId != op.syncId) task else task.copy(+ title = op.title?.take(WearTodoProtocol.MAX_TITLE_CHARS) ?: task.title,+ dueAt = when {+ op.clearDue -> null+ op.dueAt != null -> op.dueAt+ else -> task.dueAt+ },+ priority = op.priority ?: task.priority,+ )+ }+ WearTodoOpKind.SNOOZE_HOUR, WearTodoOpKind.SNOOZE_TOMORROW,+ WearTodoOpKind.QUICK_ADD -> result+ }+ }+ return result+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/sync/WearLinkBridge.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/sync/WearLinkBridge.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/sync/WearLinkBridge.ktnew file mode 100644index 0000000000..ab5c02727e--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/sync/WearLinkBridge.kt@@ -0,0 +1,116 @@+package com.vayunmathur.todo.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.todo.wear.data.WearTodoStore+import com.vayunmathur.todo.wear.domain.WearTodoCatalog+import com.vayunmathur.todo.wear.domain.WearTodoPage+import com.vayunmathur.todo.wear.domain.WearTodoPageRequest+import com.vayunmathur.todo.wear.domain.WearTodoProtocol+import com.vayunmathur.todo.wear.domain.WearTodoWatchState+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 Todo: catalog/page data items land in+ * [WearTodoStore], watch state goes back as a data item, pending ops and+ * page/sync requests are messages. Pending ops are (re)sent whenever a+ * session connects and whenever a new op is queued — they leave the queue+ * only when a phone page reflects them, never on send alone.+ */+object WearLinkBridge {+ private const val TAG = "WearLinkBridge"+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var node: WearLinkNode? = null++ fun get(context: Context): WearLinkNode {+ val appContext = context.applicationContext+ return node ?: synchronized(this) {+ node ?: create(appContext).also { node = it }+ }+ }++ private fun create(context: Context): WearLinkNode {+ val listener = object : WearLinkListener {+ override fun onData(path: String, body: ByteArray) {+ val store = WearTodoStore.get(context)+ when (path) {+ WearTodoProtocol.CATALOG_PATH -> runCatching {+ WearTodoProtocol.json.decodeFromString<WearTodoCatalog>(body.decodeToString())+ }.onSuccess { store.setCatalog(it) }+ .onFailure { Log.status(TAG, "ignoring malformed catalog") }+ WearTodoProtocol.PAGE_PATH -> runCatching {+ WearTodoProtocol.json.decodeFromString<WearTodoPage>(body.decodeToString())+ }.onSuccess { store.setPage(it) }+ .onFailure { Log.status(TAG, "ignoring malformed page") }+ }+ }+ }+ val created = WearLinkNode(context, WearTodoProtocol.CAPABILITY, listener)+ scope.launch {+ var wasConnected = false+ created.state.collect { linkState ->+ val connected = linkState is WearLinkState.Connected+ if (connected && !wasConnected) {+ flushPending(context)+ requestSync(context)+ publishWatchState(context)+ }+ wasConnected = connected+ }+ }+ created.start()+ return created+ }++ /** Sends every pending op; ops stay queued until a phone page reflects them. */+ fun flushPending(context: Context) {+ val ops = WearTodoStore.get(context).pendingOps.value+ if (ops.isEmpty()) return+ scope.launch {+ val link = get(context)+ for (op in ops) {+ link.sendMessage(+ WearTodoProtocol.OP_PATH,+ WearTodoProtocol.json.encodeToString(op).encodeToByteArray(),+ requireAck = true,+ )+ }+ }+ }++ fun publishWatchState(context: Context) {+ val store = WearTodoStore.get(context)+ val state = WearTodoWatchState(+ appliedCatalogAtMillis = store.appliedCatalogAtMillis,+ cachedPages = store.pages.value.size,+ pendingOps = store.pendingOps.value.size,+ )+ scope.launch {+ get(context).putData(+ WearTodoProtocol.WATCH_STATE_PATH,+ WearTodoProtocol.json.encodeToString(state).encodeToByteArray(),+ )+ }+ }++ /** Ask the phone for a fresh catalog + default pages; false when no session is live. */+ suspend fun requestSync(context: Context): Boolean =+ get(context).sendMessage(WearTodoProtocol.REQUEST_SYNC_PATH, ByteArray(0))++ /** Ask the phone for one page slice; the cached slice keeps rendering meanwhile. */+ suspend fun requestPage(context: Context, pageKey: String, offset: Int): Boolean =+ get(context).sendMessage(+ WearTodoProtocol.REQUEST_PAGE_PATH,+ WearTodoProtocol.json.encodeToString(WearTodoPageRequest(pageKey, offset))+ .encodeToByteArray(),+ )+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearMainActivity.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearMainActivity.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..6e83df355e--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearMainActivity.kt@@ -0,0 +1,81 @@+package com.vayunmathur.todo.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.todo.wear.data.WearTodoStore+import com.vayunmathur.todo.wear.sync.WearLinkBridge++/**+ * Watch todo entry: the phone app's navigation (view index -> task pages ->+ * task detail) rendered from the locally cached catalog/page snapshots, so+ * it works standalone. Watch-originated changes queue in the store and+ * flow back over WearLink; nothing here claims a phone write.+ */+class WearMainActivity : ComponentActivity() {++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ com.vayunmathur.library.wearlink.WearLinkPermissions.requestIfNeeded(this)+ val store = WearTodoStore.get(this)+ WearLinkBridge.get(this)+ WearLinkBridge.publishWatchState(this)+ setContent {+ MaterialTheme {+ var route by remember { mutableStateOf<WearRoute>(WearRoute.Home) }+ when (val current = route) {+ WearRoute.Home -> WearTodoHomeScreen(+ store = store,+ onOpenPage = { route = WearRoute.Page(it) },+ onQuickAdd = {+ route = WearRoute.QuickAdd(store.catalog.value.defaultViewKey)+ },+ )+ is WearRoute.Page -> WearTodoPageScreen(+ store = store,+ pageKey = current.pageKey,+ onOpenTask = { route = WearRoute.TaskDetail(it, current.pageKey) },+ onQuickAdd = { route = WearRoute.QuickAdd(current.pageKey) },+ onBack = { route = WearRoute.Home },+ )+ is WearRoute.TaskDetail -> WearTodoTaskScreen(+ store = store,+ syncId = current.syncId,+ pageKey = current.pageKey,+ onEdit = { route = WearRoute.EditTask(it, current.pageKey) },+ onConfirmDelete = {+ route = WearRoute.ConfirmDelete(it, current.pageKey)+ },+ onOpenSubtask = { route = WearRoute.TaskDetail(it, current.pageKey) },+ onBack = { route = WearRoute.Page(current.pageKey) },+ )+ is WearRoute.QuickAdd -> WearTodoQuickAddScreen(+ store = store,+ pageKey = current.pageKey,+ onDone = { route = WearRoute.Page(current.pageKey) },+ )+ is WearRoute.EditTask -> WearTodoEditScreen(+ store = store,+ syncId = current.syncId,+ onDone = {+ route = WearRoute.TaskDetail(current.syncId, current.pageKey)+ },+ )+ is WearRoute.ConfirmDelete -> WearTodoConfirmDeleteScreen(+ store = store,+ syncId = current.syncId,+ onDone = { route = WearRoute.Page(current.pageKey) },+ onCancel = {+ route = WearRoute.TaskDetail(current.syncId, current.pageKey)+ },+ )+ }+ }+ }+ }+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearRoute.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearRoute.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..78e1023c07--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearRoute.kt@@ -0,0 +1,26 @@+package com.vayunmathur.todo.wear.ui++/**+ * Watch navigation destinations mirroring the phone's `Route`: page routes+ * carry the phone `TodoView.key`, detail routes carry the task syncId —+ * never selection state held in a view model (root AGENTS.md rule).+ */+sealed interface WearRoute {+ /** Home: the phone drawer's view index (smart views, lists, tags) + quick add. */+ data object Home : WearRoute++ /** One `Route.TodoList(viewKey)` page: tasks of [pageKey] at its cached slices. */+ data class Page(val pageKey: String) : WearRoute++ /** One `Route.TodoDetail` page, identified by stable syncId. */+ data class TaskDetail(val syncId: String, val pageKey: String) : WearRoute++ /** Quick-add entry (text/dictation); the phone parses it. */+ data class QuickAdd(val pageKey: String) : WearRoute++ /** Watch-sized edit of one task: title, due date, priority. */+ data class EditTask(val syncId: String, val pageKey: String) : WearRoute++ /** Delete confirmation for one task. */+ data class ConfirmDelete(val syncId: String, val pageKey: String) : WearRoute+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoConfirmDeleteScreen.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoConfirmDeleteScreen.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoConfirmDeleteScreen.ktnew file mode 100644index 0000000000..e744a62fae--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoConfirmDeleteScreen.kt@@ -0,0 +1,56 @@+package com.vayunmathur.todo.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.todo.wear.R+import com.vayunmathur.todo.wear.data.WearTodoStore++/** Delete needs an explicit confirmation on the watch (no swipe-to-delete). */+@Composable+fun WearTodoConfirmDeleteScreen(+ store: WearTodoStore,+ syncId: String,+ onDone: () -> Unit,+ onCancel: () -> Unit,+) {+ ScalingLazyColumn(state = rememberScalingLazyListState()) {+ item {+ Text(+ stringResource(R.string.wear_delete_confirm),+ style = MaterialTheme.typography.title3,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ item {+ Chip(+ onClick = {+ store.delete(syncId)+ onDone()+ },+ label = { Text(stringResource(R.string.wear_delete), maxLines = 1) },+ colors = ChipDefaults.primaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ item {+ Chip(+ onClick = onCancel,+ label = { Text(stringResource(R.string.wear_cancel), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoEditScreen.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoEditScreen.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoEditScreen.ktnew file mode 100644index 0000000000..b96c4271d1--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoEditScreen.kt@@ -0,0 +1,141 @@+package com.vayunmathur.todo.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.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.todo.wear.R+import com.vayunmathur.todo.wear.data.WearTodoStore+import java.time.LocalDate+import java.time.ZoneId++/**+ * Watch-sized task edit: title (system IME, whose microphone is the+ * dictation path), due shortcuts (none/today/tomorrow/next week, sent as+ * local-midnight millis the phone stores as an all-day due date), and+ * priority. Save queues an EDIT op; the phone applies and republishes.+ */+@Composable+fun WearTodoEditScreen(+ store: WearTodoStore,+ syncId: String,+ onDone: () -> Unit,+) {+ val pagesMap by store.pages.collectAsState()+ val existing = store.pagesForAll().firstOrNull { it.syncId == syncId }+ var title by remember(syncId) { mutableStateOf(existing?.title.orEmpty()) }+ var dueAt by remember(syncId) { mutableStateOf(existing?.dueAt) }+ var clearDue by remember(syncId) { mutableStateOf(false) }+ var priority by remember(syncId) { mutableStateOf(existing?.priority ?: 0) }+ val zone = ZoneId.systemDefault()+ fun startOfDay(date: LocalDate): Long =+ date.atStartOfDay(zone).toInstant().toEpochMilli()++ ScalingLazyColumn(state = rememberScalingLazyListState()) {+ item {+ Text(+ stringResource(R.string.wear_title_hint),+ style = MaterialTheme.typography.caption1,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ item {+ BasicTextField(+ value = title,+ onValueChange = { title = it },+ textStyle = TextStyle(color = MaterialTheme.colors.onSurface),+ cursorBrush = SolidColor(MaterialTheme.colors.onSurface),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+ )+ }+ val dueOptions: List<Pair<Int, () -> Unit>> = listOf(+ R.string.wear_due_none to { clearDue = true; dueAt = null },+ R.string.wear_due_today to {+ clearDue = false; dueAt = startOfDay(LocalDate.now(zone))+ },+ R.string.wear_due_tomorrow to {+ clearDue = false; dueAt = startOfDay(LocalDate.now(zone).plusDays(1))+ },+ R.string.wear_due_next_week to {+ clearDue = false; dueAt = startOfDay(LocalDate.now(zone).plusWeeks(1))+ },+ )+ dueOptions.forEach { (label, apply) ->+ item {+ Chip(+ onClick = apply,+ label = { Text(stringResource(label), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ for (p in 0..4) {+ item {+ Chip(+ onClick = { priority = p },+ label = {+ Text(+ stringResource(+ R.string.wear_priority,+ if (p == 0) "none" else p.toString(),+ ),+ maxLines = 1,+ )+ },+ colors = if (priority == p) {+ ChipDefaults.primaryChipColors()+ } else {+ ChipDefaults.secondaryChipColors()+ },+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+ item {+ Chip(+ onClick = {+ store.edit(+ syncId = syncId,+ title = title.trim().takeIf { it.isNotEmpty() },+ dueAt = dueAt,+ clearDue = clearDue,+ priority = priority,+ )+ onDone()+ },+ label = { Text(stringResource(R.string.wear_save), 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),+ )+ }+ }+}++/** Every cached task across pages (edit/detail lookups are not page-scoped). */+internal fun WearTodoStore.pagesForAll() =+ pages.value.values.flatMap { it.tasks }.distinctBy { it.syncId }
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoHomeScreen.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoHomeScreen.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoHomeScreen.ktnew file mode 100644index 0000000000..32b7c05731--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoHomeScreen.kt@@ -0,0 +1,124 @@+package com.vayunmathur.todo.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.todo.wear.R+import com.vayunmathur.todo.wear.data.WearTodoStore+import com.vayunmathur.todo.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * Watch home = the phone app's drawer: smart views in phone order, then+ * lists, then tags, each with its open-task count, plus quick add. Rendered+ * from the cached catalog, so it works with the phone absent.+ */+@Composable+fun WearTodoHomeScreen(+ store: WearTodoStore,+ onOpenPage: (String) -> Unit,+ onQuickAdd: () -> Unit,+) {+ val catalog by store.catalog.collectAsState()+ val pending by store.pendingOps.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),+ )+ }+ 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 = onQuickAdd,+ label = { Text(stringResource(R.string.wear_quick_add), maxLines = 1) },+ colors = ChipDefaults.primaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ if (catalog.views.isEmpty()) {+ item {+ Text(+ stringResource(R.string.wear_empty),+ style = MaterialTheme.typography.body2,+ textAlign = TextAlign.Center,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+ )+ }+ } else {+ items(catalog.views, key = { it.key }) { view ->+ Chip(+ onClick = { onOpenPage(view.key) },+ label = { Text(view.title.ifBlank { view.key }, maxLines = 1) },+ secondaryLabel = {+ Text("${view.openCount} open", 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_sync), maxLines = 1) },+ colors = ChipDefaults.secondaryChipColors(),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ )+ }+ }+}
todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoPageScreen.kt
diff --git a/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoPageScreen.kt b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoPageScreen.ktnew file mode 100644index 0000000000..0b48259981--- /dev/null+++ b/todo-wear/src/main/java/com/vayunmathur/todo/wear/ui/WearTodoPageScreen.kt@@ -0,0 +1,141 @@+package com.vayunmathur.todo.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.todo.wear.R+import com.vayunmathur.todo.wear.data.WearTodoStore+import com.vayunmathur.todo.wear.domain.overlayPendingTasks+import com.vayunmathur.todo.wear.sync.WearLinkBridge+import kotlinx.coroutines.launch++/**+ * One phone `Route.TodoList` page at watch size: cached slices of the view+ * in phone order (group labels kept), pending ops overlaid, with explicit+ * "load more" paging — the next slice is requested from the phone and the+ * cached slices keep rendering while it is in flight or unreachable.+ */+@Composable+fun WearTodoPageScreen(+ store: WearTodoStore,+ pageKey: String,+ onOpenTask: (String) -> Unit,+ onQuickAdd: () -> Unit,+ onBack: () -> Unit,+) {+ val pagesMap by store.pages.collectAsState()+ val pending by store.pendingOps.collectAsState()+ val catalog by store.catalog.collectAsState()+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val slices = store.pagesFor(pageKey)+ val title = slices.firstOrNull()?.title+ ?: catalog.views.firstOrNull { it.key == pageKey }?.title+ ?: pageKey+ val allTasks = overlayPendingTasks(slices.flatMap { it.tasks }, pending)+ val last = slices.lastOrNull()+ val hasMore = last?.hasMore == true++ LaunchedEffect(pageKey) {+ if (slices.isEmpty()) WearLinkBridge.requestPage(context, pageKey, 0)+ }++ ScalingLazyColumn(state = rememberScalingLazyListState()) {+ item {+ Text(+ title,+ style
Diff truncated.